Compare commits
221 Commits
5.1.0-rc.1
...
5.0.4
Author | SHA1 | Date | |
---|---|---|---|
cbd93fe0d0 | |||
e1dfd9b17a | |||
e95b5d77bc | |||
9e69d97b77 | |||
b450c83091 | |||
38be44df9f | |||
e4ce695b66 | |||
4da184c29b | |||
647ca64216 | |||
53aff1fb83 | |||
71a6f1768e | |||
108b6e77dd | |||
ead759670b | |||
bdaee508cf | |||
e099911dd0 | |||
66fd1f8ce6 | |||
0e8f0288cb | |||
c7b211ca3c | |||
22bbd6e045 | |||
2a5b6194bb | |||
264260f997 | |||
c70cd258d5 | |||
2b0c896d78 | |||
c0bf1b0545 | |||
65a40e659b | |||
215832d8c6 | |||
686c4efe6d | |||
efce39605b | |||
b567f9cc21 | |||
4ff60c3562 | |||
bc904b19a4 | |||
135cf226bf | |||
0550383fc9 | |||
07699cbaec | |||
e4bb077d27 | |||
27e7439c3b | |||
66d160215e | |||
0feba49c4b | |||
9ca6ee9eed | |||
a5a82296b7 | |||
f9f2c20a57 | |||
662422a67e | |||
b53ead4c45 | |||
d0abfa3acc | |||
3bf36e9492 | |||
82aace63ea | |||
15795d09cf | |||
8ddbed8f7b | |||
81f1d42328 | |||
3df1542c87 | |||
8e1e7faef4 | |||
27f8c69d8a | |||
5d0dd97402 | |||
814f06289b | |||
b1f8eb14c8 | |||
f983d1cc50 | |||
12857922c5 | |||
dbdf9f76be | |||
d5eaf4de3c | |||
2d6126ec1b | |||
259f6bf638 | |||
03d549be05 | |||
bc4b4b5b55 | |||
00f2055c59 | |||
91efc7f70b | |||
8b1a6b1f24 | |||
b732fb935b | |||
0e2d962acb | |||
7acbc19b94 | |||
c69eda8f60 | |||
210ff78f4d | |||
96766f7336 | |||
52b50c4b6c | |||
398690d47c | |||
dc01fb167b | |||
7c26c06495 | |||
82dc7fa628 | |||
3101e89cf5 | |||
79c3e1b968 | |||
c96967b235 | |||
422cd0b665 | |||
eea2039bce | |||
612f508dff | |||
aa3d75ba83 | |||
4cc6abbbf8 | |||
222758bed3 | |||
516107fd04 | |||
bd70aece52 | |||
2ca6bdd110 | |||
2aefac841f | |||
ec496c2fda | |||
346dbcf24a | |||
48843a9f47 | |||
8f2fb02048 | |||
89e4262188 | |||
424a323316 | |||
28985cb2de | |||
5d1cd57787 | |||
9de45fa650 | |||
953a0e07d6 | |||
511e56d633 | |||
1f1741c5ad | |||
408ffb634e | |||
73d857cb38 | |||
3ab0963309 | |||
da22c48ef1 | |||
f80d41f3e5 | |||
2b7ca4e9f8 | |||
4292540939 | |||
708379128f | |||
131368c774 | |||
94e0ef77ea | |||
e4cd3b0564 | |||
22dc3ad94c | |||
7077a61614 | |||
9811bef278 | |||
3298c4a79f | |||
5a6efa7a3f | |||
a8c786c8c9 | |||
799cbb932c | |||
e6f16a7629 | |||
1bb0333c23 | |||
9fa0ffd8a5 | |||
678d1cfae1 | |||
a897d6842f | |||
25843fed53 | |||
762da3b154 | |||
37a740b5b2 | |||
067e926c08 | |||
bc52e97eba | |||
9b579d85be | |||
895d78c0ed | |||
803b0f0fb3 | |||
86399958dd | |||
d550b6872a | |||
92e4c34d01 | |||
e84695389b | |||
4e48bdff22 | |||
2185e466db | |||
6f05dab2fc | |||
18197bd56d | |||
c75740e585 | |||
16d72584cb | |||
9c9867e840 | |||
55092ace87 | |||
70edca3cec | |||
120ebe8225 | |||
7695ad570b | |||
7a708ad387 | |||
71f1ed5795 | |||
ced5186ca4 | |||
e48dc270b5 | |||
aa574710c9 | |||
d62ef132d2 | |||
428f80e8ae | |||
260c9b763c | |||
5f6d71d39a | |||
8133a8d335 | |||
3e05d62a99 | |||
db7f2a9ca7 | |||
59a2fbe74f | |||
3274e1a79a | |||
6979a29d1f | |||
9da5ca7ae6 | |||
e51ac3671f | |||
3393009b69 | |||
12e4b5667e | |||
0f8b83200a | |||
253e89dfac | |||
c4772ee002 | |||
35ec4af2b1 | |||
19b48429ef | |||
b796419e7e | |||
a1ec65b1dd | |||
851e1cfcfd | |||
a363be6b5c | |||
e1fb65cac4 | |||
b497e9e6ee | |||
706ba38498 | |||
78052e4984 | |||
bf861f5539 | |||
d99a5ec494 | |||
d651fc0d6a | |||
5775376bcf | |||
896b853519 | |||
5225fdbc0e | |||
f5b7f2b9a5 | |||
509f392ab0 | |||
cf5fce8d5e | |||
f1248b69e6 | |||
4498dddbe3 | |||
812786f44e | |||
de24d54517 | |||
c295aeeca2 | |||
a8add78fe1 | |||
e3a16ed02d | |||
fd37f3fbab | |||
85e95cc32b | |||
de71ba74bb | |||
a01c877534 | |||
2d508a3ef0 | |||
4285b6c3e3 | |||
5542517b9c | |||
fef3539608 | |||
f4d5729cb3 | |||
d343bf7885 | |||
9ce7f0e538 | |||
4a23df3909 | |||
14016c781f | |||
47caebfe86 | |||
5cfd9c6020 | |||
47bc6f105d | |||
40fa2593a9 | |||
680bcf7b8a | |||
ef08330341 | |||
6cc042e2ba | |||
9b26455740 | |||
18bce5987c | |||
f1108fea76 | |||
64b3e3e41a | |||
a82f863e24 |
18
.bazelrc
Normal file
18
.bazelrc
Normal file
@ -0,0 +1,18 @@
|
||||
# Make compilation fast, by keeping a few copies of the compilers
|
||||
# running as daemons, and cache SourceFile AST's to reduce parse time.
|
||||
build --strategy=TypeScriptCompile=worker
|
||||
build --strategy=AngularTemplateCompile=worker
|
||||
|
||||
# Don't create bazel-* symlinks in the WORKSPACE directory.
|
||||
# These require .gitignore and may scare users.
|
||||
# Also, it's a workaround for https://github.com/bazelbuild/rules_typescript/issues/12
|
||||
# which affects the common case of having `tsconfig.json` in the WORKSPACE directory.
|
||||
#
|
||||
# Instead, you should run `bazel info bazel-bin` to find out where the outputs went.
|
||||
build --symlink_prefix=/
|
||||
|
||||
# Performance: avoid stat'ing input files
|
||||
build --watchfs
|
||||
|
||||
# Don't print all the .d.ts output locations after builds
|
||||
build --show_result=0
|
@ -279,7 +279,7 @@ groups:
|
||||
files:
|
||||
- "packages/benchpress/*"
|
||||
users:
|
||||
# needs primary
|
||||
- alxhub #primary
|
||||
# needs secondary
|
||||
- IgorMinar #fallback
|
||||
- mhevery #fallback
|
||||
|
120
CHANGELOG.md
120
CHANGELOG.md
@ -1,61 +1,3 @@
|
||||
<a name="5.1.0-rc.1"></a>
|
||||
# [5.1.0-rc.1](https://github.com/angular/angular/compare/5.1.0-rc.0...5.1.0-rc.1) (2017-12-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **compiler-cli:** propagate ts.SourceFile moduleName into metadata ([f841fbe](https://github.com/angular/angular/commit/f841fbe))
|
||||
* **service-worker:** allow disabling SW while still using services ([65f4fad](https://github.com/angular/angular/commit/65f4fad))
|
||||
* **service-worker:** don't crash if SW not supported ([b9a91a5](https://github.com/angular/angular/commit/b9a91a5))
|
||||
* **service-worker:** send initialization signal from the application ([3fbcde9](https://github.com/angular/angular/commit/3fbcde9))
|
||||
* **service-worker:** use relative path for ngsw.json ([f582620](https://github.com/angular/angular/commit/f582620))
|
||||
|
||||
|
||||
|
||||
<a name="5.0.5"></a>
|
||||
## [5.0.5](https://github.com/angular/angular/compare/5.0.4...5.0.5) (2017-12-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **compiler-cli:** propagate ts.SourceFile moduleName into metadata ([a2ff4ab](https://github.com/angular/angular/commit/a2ff4ab))
|
||||
* **service-worker:** allow disabling SW while still using services ([f99335b](https://github.com/angular/angular/commit/f99335b))
|
||||
* **service-worker:** don't crash if SW not supported ([ee37d4b](https://github.com/angular/angular/commit/ee37d4b))
|
||||
* **service-worker:** send initialization signal from the application ([6bf07b4](https://github.com/angular/angular/commit/6bf07b4))
|
||||
* **service-worker:** use relative path for ngsw.json ([56c98f7](https://github.com/angular/angular/commit/56c98f7))
|
||||
|
||||
|
||||
|
||||
<a name="5.1.0-rc.0"></a>
|
||||
# [5.1.0-rc.0](https://github.com/angular/angular/compare/5.1.0-beta.2...5.1.0-rc.0) (2017-12-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **animations:** ensure multi-level enter animations work ([#19455](https://github.com/angular/angular/issues/19455)) ([dd6237e](https://github.com/angular/angular/commit/dd6237e))
|
||||
* **animations:** ensure multi-level enter animations work ([#19455](https://github.com/angular/angular/issues/19455)) ([b2a586c](https://github.com/angular/angular/commit/b2a586c))
|
||||
* **animations:** ensure multi-level leave animations work ([#19455](https://github.com/angular/angular/issues/19455)) ([1366762](https://github.com/angular/angular/commit/1366762))
|
||||
* **animations:** ensure multi-level leave animations work ([#19455](https://github.com/angular/angular/issues/19455)) ([c2b3792](https://github.com/angular/angular/commit/c2b3792))
|
||||
* **bazel:** produce named AMD modules for codegen ([#20547](https://github.com/angular/angular/issues/20547)) ([6e83204](https://github.com/angular/angular/commit/6e83204)), closes [#19422](https://github.com/angular/angular/issues/19422)
|
||||
* **common:** accept falsy values as HTTP bodies ([#19958](https://github.com/angular/angular/issues/19958)) ([15a54df](https://github.com/angular/angular/commit/15a54df)), closes [#19825](https://github.com/angular/angular/issues/19825) [#19195](https://github.com/angular/angular/issues/19195)
|
||||
* **common:** don't strip XSSI prefix for if error isn't JSON ([#19958](https://github.com/angular/angular/issues/19958)) ([aafa75d](https://github.com/angular/angular/commit/aafa75d))
|
||||
* **common:** remove useless guard in HttpClient ([#19958](https://github.com/angular/angular/issues/19958)) ([eb01ad5](https://github.com/angular/angular/commit/eb01ad5)), closes [#19223](https://github.com/angular/angular/issues/19223)
|
||||
* **common:** treat an empty body as null when parsing JSON in HttpClient ([#19958](https://github.com/angular/angular/issues/19958)) ([503be69](https://github.com/angular/angular/commit/503be69)), closes [#18680](https://github.com/angular/angular/issues/18680) [#19413](https://github.com/angular/angular/issues/19413) [#19502](https://github.com/angular/angular/issues/19502) [#19555](https://github.com/angular/angular/issues/19555)
|
||||
* **compiler:** correctly detect when to serialze summary metadata ([#20668](https://github.com/angular/angular/issues/20668)) ([8bb42df](https://github.com/angular/angular/commit/8bb42df))
|
||||
* **compiler-cli:** fix memory leak in program creation ([#20692](https://github.com/angular/angular/issues/20692)) ([71e5de6](https://github.com/angular/angular/commit/71e5de6)), closes [#20691](https://github.com/angular/angular/issues/20691)
|
||||
* **compiler-cli:** normalize sourcepaths for i18n extracted files ([#20417](https://github.com/angular/angular/issues/20417)) ([de78307](https://github.com/angular/angular/commit/de78307)), closes [#20416](https://github.com/angular/angular/issues/20416)
|
||||
* **core:** should use native addEventListener in ngZone ([#20672](https://github.com/angular/angular/issues/20672)) ([65a2cb8](https://github.com/angular/angular/commit/65a2cb8))
|
||||
* **language-service:** Allow empty templates ([#20651](https://github.com/angular/angular/issues/20651)) ([3203069](https://github.com/angular/angular/commit/3203069)), closes [#19406](https://github.com/angular/angular/issues/19406)
|
||||
* **language-service:** Fix crash when no script files are found ([#20550](https://github.com/angular/angular/issues/20550)) ([54bfe14](https://github.com/angular/angular/commit/54bfe14)), closes [#19325](https://github.com/angular/angular/issues/19325)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **common:** add locale id parameter to `registerLocaleData` ([#20623](https://github.com/angular/angular/issues/20623)) ([24bf3e2](https://github.com/angular/angular/commit/24bf3e2))
|
||||
* **compiler-cli:** improve error messages produced during structural errors ([#20459](https://github.com/angular/angular/issues/20459)) ([8ecda94](https://github.com/angular/angular/commit/8ecda94))
|
||||
|
||||
|
||||
|
||||
<a name="5.0.4"></a>
|
||||
## [5.0.4](https://github.com/angular/angular/compare/5.0.3...5.0.4) (2017-12-01)
|
||||
|
||||
@ -73,30 +15,6 @@
|
||||
|
||||
|
||||
|
||||
<a name="5.1.0-beta.2"></a>
|
||||
# [5.1.0-beta.2](https://github.com/angular/angular/compare/5.1.0-beta.1...5.1.0-beta.2) (2017-11-22)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **animations:** always fire inner trigger callbacks even if blocked by parent animations ([#19753](https://github.com/angular/angular/issues/19753)) ([0e012c9](https://github.com/angular/angular/commit/0e012c9)), closes [#19100](https://github.com/angular/angular/issues/19100)
|
||||
* **animations:** always fire start and done callbacks in order for noop animations ([#20570](https://github.com/angular/angular/issues/20570)) ([ffb6dbe](https://github.com/angular/angular/commit/ffb6dbe))
|
||||
* **animations:** validate against trigger() names that use @ symbols ([#20326](https://github.com/angular/angular/issues/20326)) ([1861e41](https://github.com/angular/angular/commit/1861e41))
|
||||
* **benchpress:** Allow ignoring navigationStart events in perflog metric. ([#20312](https://github.com/angular/angular/issues/20312)) ([717ac5a](https://github.com/angular/angular/commit/717ac5a))
|
||||
* **common:** return ISubscription from Location.subscribe() ([#20429](https://github.com/angular/angular/issues/20429)) ([437a044](https://github.com/angular/angular/commit/437a044)), closes [#20406](https://github.com/angular/angular/issues/20406)
|
||||
* **compiler:** emit correct type-check-blocks with TemplateRef's ([#20463](https://github.com/angular/angular/issues/20463)) ([68b53c0](https://github.com/angular/angular/commit/68b53c0))
|
||||
* **compiler:** support event bindings in `fullTemplateTypeCheck` ([#20490](https://github.com/angular/angular/issues/20490)) ([4ed0439](https://github.com/angular/angular/commit/4ed0439))
|
||||
* **core:** fix [#20532](https://github.com/angular/angular/issues/20532), should be able to cancel listener from mixed zone ([#20538](https://github.com/angular/angular/issues/20538)) ([a740e4f](https://github.com/angular/angular/commit/a740e4f))
|
||||
* **core:** should support event.stopImmediatePropagation ([#20469](https://github.com/angular/angular/issues/20469)) ([997336b](https://github.com/angular/angular/commit/997336b))
|
||||
* **forms:** updateOn should check if change occurred ([#20358](https://github.com/angular/angular/issues/20358)) ([69c53c3](https://github.com/angular/angular/commit/69c53c3)), closes [#20259](https://github.com/angular/angular/issues/20259)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **platform-browser-dynamic:** export `JitCompilerFactory` ([#20478](https://github.com/angular/angular/issues/20478)) ([d7a727c](https://github.com/angular/angular/commit/d7a727c)), closes [#20125](https://github.com/angular/angular/issues/20125)
|
||||
|
||||
|
||||
|
||||
<a name="5.0.3"></a>
|
||||
## [5.0.3](https://github.com/angular/angular/compare/5.0.2...5.0.3) (2017-11-22)
|
||||
|
||||
@ -114,28 +32,6 @@
|
||||
* **forms:** updateOn should check if change occurred ([#20358](https://github.com/angular/angular/issues/20358)) ([f9f2c20](https://github.com/angular/angular/commit/f9f2c20)), closes [#20259](https://github.com/angular/angular/issues/20259)
|
||||
|
||||
|
||||
<a name="5.1.0-beta.1"></a>
|
||||
# [5.1.0-beta.1](https://github.com/angular/angular/compare/5.1.0-beta.0...5.1.0-beta.1) (2017-11-16)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **animations:** always fire inner trigger callbacks even if blocked by parent animations ([#19753](https://github.com/angular/angular/issues/19753)) ([d47b2a6](https://github.com/angular/angular/commit/d47b2a6)), closes [#19100](https://github.com/angular/angular/issues/19100)
|
||||
* **animations:** ensure final state() styles are applied within @.disabled animations ([#20267](https://github.com/angular/angular/issues/20267)) ([20aafff](https://github.com/angular/angular/commit/20aafff)), closes [#20266](https://github.com/angular/angular/issues/20266)
|
||||
* **bazel:** adjust mock of tsconfig for ng_module rule unit test ([#20175](https://github.com/angular/angular/issues/20175)) ([c2a24b4](https://github.com/angular/angular/commit/c2a24b4))
|
||||
* **compiler:** fix corner cases in shadow CSS ([c32f5fd](https://github.com/angular/angular/commit/c32f5fd))
|
||||
* **compiler:** recognize @NgModule with a redundant @Injectable ([#20320](https://github.com/angular/angular/issues/20320)) ([c33a576](https://github.com/angular/angular/commit/c33a576))
|
||||
* **compiler:** show explanatory text in template errors ([#20313](https://github.com/angular/angular/issues/20313)) ([3257fcd](https://github.com/angular/angular/commit/3257fcd))
|
||||
* **core:** ensure init lifecycle events are called ([#20258](https://github.com/angular/angular/issues/20258)) ([24cf8b3](https://github.com/angular/angular/commit/24cf8b3))
|
||||
* **language-service:** pass compilerOptions.paths to ReflectorHost ([#20222](https://github.com/angular/angular/issues/20222)) ([eb8013e](https://github.com/angular/angular/commit/eb8013e))
|
||||
* **router:** 'merge' queryParamHandling strategy should be able to remove query params ([#19733](https://github.com/angular/angular/issues/19733)) ([a622e19](https://github.com/angular/angular/commit/a622e19)), closes [#18463](https://github.com/angular/angular/issues/18463) [#17202](https://github.com/angular/angular/issues/17202)
|
||||
* Update test code to type-check under TS 2.5 ([#20175](https://github.com/angular/angular/issues/20175)) ([5ec1717](https://github.com/angular/angular/commit/5ec1717))
|
||||
|
||||
### Features
|
||||
|
||||
* **typescript:** support TypeScript 2.5 ([a9f3e2b](https://github.com/angular/angular/commit/a9f3e2b)), closes [#20175](https://github.com/angular/angular/issues/20175)
|
||||
|
||||
> Note, if you do `Injector.get(Token)` where `Token` has static members, you'll run into https://github.com/Microsoft/TypeScript/issues/20102 where the returned type is `{}` rather than `Token`. Use `Injector.get<Token>(Token)` to work around.
|
||||
|
||||
<a name="5.0.2"></a>
|
||||
## [5.0.2](https://github.com/angular/angular/compare/5.0.1...5.0.2) (2017-11-16)
|
||||
@ -150,22 +46,6 @@
|
||||
* **router:** 'merge' queryParamHandling strategy should be able to remove query params ([#19733](https://github.com/angular/angular/issues/19733)) ([b732fb9](https://github.com/angular/angular/commit/b732fb9)), closes [#18463](https://github.com/angular/angular/issues/18463) [#17202](https://github.com/angular/angular/issues/17202)
|
||||
|
||||
|
||||
<a name="5.1.0-beta.0"></a>
|
||||
# [5.1.0-beta.0](https://github.com/angular/angular/compare/5.0.0-rc.4...5.1.0-beta.0) (2017-11-08)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **compiler:** don't overwrite missingTranslation's value in JIT ([#19952](https://github.com/angular/angular/issues/19952)) ([799cbb9](https://github.com/angular/angular/commit/799cbb9))
|
||||
* **compiler:** report a reasonable error with invalid metadata ([#20062](https://github.com/angular/angular/issues/20062)) ([da22c48](https://github.com/angular/angular/commit/da22c48))
|
||||
* **compiler-cli:** don't report emit diagnostics when `--noEmitOnError` is off ([#20063](https://github.com/angular/angular/issues/20063)) ([8639995](https://github.com/angular/angular/commit/8639995))
|
||||
* **core:** `__symbol__` should return `__zone_symbol__` without zone.js loaded ([#19541](https://github.com/angular/angular/issues/19541)) ([678d1cf](https://github.com/angular/angular/commit/678d1cf))
|
||||
* **core:** should support event.stopImmediatePropagation ([#19222](https://github.com/angular/angular/issues/19222)) ([7083791](https://github.com/angular/angular/commit/7083791))
|
||||
* **platform-browser:** support Symbols in custom `jasmineToString()` method ([#19794](https://github.com/angular/angular/issues/19794)) ([5a6efa7](https://github.com/angular/angular/commit/5a6efa7))
|
||||
|
||||
### Features
|
||||
|
||||
* **compiler:** introduce `TestBed.overrideTemplateUsingTestingModule` ([a460066](https://github.com/angular/angular/commit/a460066)), closes [#19815](https://github.com/angular/angular/issues/19815)
|
||||
|
||||
|
||||
<a name="5.0.1"></a>
|
||||
## [5.0.1](https://github.com/angular/angular/compare/5.0.0...5.0.1) (2017-11-08)
|
||||
|
@ -69,37 +69,36 @@ You can file new issues by filling out our [new issue form](https://github.com/a
|
||||
### <a name="submit-pr"></a> Submitting a Pull Request (PR)
|
||||
Before you submit your Pull Request (PR) consider the following guidelines:
|
||||
|
||||
1. Search [GitHub](https://github.com/angular/angular/pulls) for an open or closed PR
|
||||
* Search [GitHub](https://github.com/angular/angular/pulls) for an open or closed PR
|
||||
that relates to your submission. You don't want to duplicate effort.
|
||||
1. Please sign our [Contributor License Agreement (CLA)](#cla) before sending PRs.
|
||||
* Please sign our [Contributor License Agreement (CLA)](#cla) before sending PRs.
|
||||
We cannot accept code without this.
|
||||
1. Fork the angular/angular repo.
|
||||
1. Make your changes in a new git branch:
|
||||
* Make your changes in a new git branch:
|
||||
|
||||
```shell
|
||||
git checkout -b my-fix-branch master
|
||||
```
|
||||
|
||||
1. Create your patch, **including appropriate test cases**.
|
||||
1. Follow our [Coding Rules](#rules).
|
||||
1. Run the full Angular test suite, as described in the [developer documentation][dev-doc],
|
||||
* Create your patch, **including appropriate test cases**.
|
||||
* Follow our [Coding Rules](#rules).
|
||||
* Run the full Angular test suite, as described in the [developer documentation][dev-doc],
|
||||
and ensure that all tests pass.
|
||||
1. Commit your changes using a descriptive commit message that follows our
|
||||
* Commit your changes using a descriptive commit message that follows our
|
||||
[commit message conventions](#commit). Adherence to these conventions
|
||||
is necessary because release notes are automatically generated from these messages.
|
||||
|
||||
```shell
|
||||
git commit -a
|
||||
```
|
||||
Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files.
|
||||
Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files.
|
||||
|
||||
1. Push your branch to GitHub:
|
||||
* Push your branch to GitHub:
|
||||
|
||||
```shell
|
||||
git push origin my-fix-branch
|
||||
```
|
||||
|
||||
1. In GitHub, send a pull request to `angular:master`.
|
||||
* In GitHub, send a pull request to `angular:master`.
|
||||
* If we suggest changes then:
|
||||
* Make the required updates.
|
||||
* Re-run the Angular test suites to ensure tests are still passing.
|
||||
|
@ -5,7 +5,8 @@ load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
|
||||
git_repository(
|
||||
name = "build_bazel_rules_nodejs",
|
||||
remote = "https://github.com/bazelbuild/rules_nodejs.git",
|
||||
commit = "0.2.1",
|
||||
# TODO(alexeagle): use the correct tag here.
|
||||
commit = "2c6243df53fd33fdab283ebdd01582e4eb815db8",
|
||||
)
|
||||
|
||||
load("@build_bazel_rules_nodejs//:defs.bzl", "node_repositories")
|
||||
|
@ -3,7 +3,7 @@ load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
|
||||
git_repository(
|
||||
name = "build_bazel_rules_nodejs",
|
||||
remote = "https://github.com/bazelbuild/rules_nodejs.git",
|
||||
tag = "0.2.1",
|
||||
tag = "0.0.2",
|
||||
)
|
||||
|
||||
load("@build_bazel_rules_nodejs//:defs.bzl", "node_repositories")
|
||||
|
@ -1,19 +0,0 @@
|
||||
import { AppPage } from './app.po';
|
||||
|
||||
describe('dynamic-compiler App', () => {
|
||||
let page: AppPage;
|
||||
|
||||
beforeEach(() => {
|
||||
page = new AppPage();
|
||||
});
|
||||
|
||||
it('should display welcome message', () => {
|
||||
page.navigateTo();
|
||||
expect(page.getParagraphText()).toEqual('Hello world!');
|
||||
});
|
||||
|
||||
it('should display lazy-loaded component', () => {
|
||||
page.navigateTo();
|
||||
expect(page.getLazyLoadedText()).toEqual('Lazy-loaded component!');
|
||||
});
|
||||
});
|
@ -1,16 +0,0 @@
|
||||
import {browser, by, element, protractor} from 'protractor';
|
||||
|
||||
export class AppPage {
|
||||
navigateTo() {
|
||||
return browser.get('/');
|
||||
}
|
||||
|
||||
getParagraphText() {
|
||||
return element(by.css('app-root h1')).getText();
|
||||
}
|
||||
|
||||
getLazyLoadedText() {
|
||||
const el = element(by.css('app-root lazy-component'));
|
||||
return browser.wait(protractor.ExpectedConditions.presenceOf(el)).then(() => el.getText(), err => el.getText());
|
||||
}
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
{
|
||||
"open": false,
|
||||
"logLevel": "silent",
|
||||
"port": 8080,
|
||||
"server": {
|
||||
"baseDir": ".",
|
||||
"routes": {
|
||||
"/dist": "dist",
|
||||
"/node_modules": "node_modules"
|
||||
},
|
||||
"middleware": {
|
||||
"0": null
|
||||
}
|
||||
}
|
||||
}
|
@ -1,16 +0,0 @@
|
||||
exports.config = {
|
||||
specs: [
|
||||
'../dist/e2e/*.e2e-spec.js'
|
||||
],
|
||||
capabilities: {
|
||||
browserName: 'chrome',
|
||||
chromeOptions: {
|
||||
args: ['--no-sandbox'],
|
||||
binary: process.env.CHROME_BIN,
|
||||
}
|
||||
},
|
||||
directConnect: true,
|
||||
baseUrl: 'http://localhost:8080/',
|
||||
framework: 'jasmine',
|
||||
useAllAngular2AppRoots: true
|
||||
};
|
@ -1,7 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"outDir": "../dist/e2e",
|
||||
"types": ["jasmine"],
|
||||
"skipLibCheck": true
|
||||
}
|
||||
}
|
@ -1,14 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title></title>
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
<script src="/node_modules/zone.js/dist/zone.js"></script>
|
||||
<script src="/node_modules/reflect-metadata/Reflect.js"></script>
|
||||
<script src="/node_modules/systemjs/dist/system.js"></script>
|
||||
<script src="/dist/bundle.js"></script>
|
||||
</body>
|
||||
</html>
|
@ -1,44 +0,0 @@
|
||||
{
|
||||
"name": "dynamic-compiler",
|
||||
"version": "0.0.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"build": "npm run clean && npm run ngc && npm run rollup && npm run rollup:lazy && npm run es5 && npm run es5:lazy",
|
||||
"clean": "rm -rf dist",
|
||||
"es5": "tsc --target es5 --skipLibCheck --allowJs dist/bundle.es2015.js --out dist/bundle.js",
|
||||
"es5:lazy": "tsc --target es5 --skipLibCheck --allowJs dist/lazy.bundle.es2015.js --out dist/lazy.bundle.js",
|
||||
"ngc": "ngc -p tsconfig.json",
|
||||
"rollup": "rollup -f iife -c rollup.config.js -o dist/bundle.es2015.js",
|
||||
"rollup:lazy": "rollup -f cjs -c rollup.lazy.config.js -o dist/lazy.bundle.es2015.js",
|
||||
"postinstall": "webdriver-manager update --gecko false",
|
||||
"preprotractor": "tsc -p e2e",
|
||||
"protractor": "protractor e2e/protractor.config.js",
|
||||
"serve": "lite-server -c e2e/browser.config.json",
|
||||
"test": "npm run build && concurrently \"yarn run serve\" \"yarn run protractor\" --kill-others --success first"
|
||||
},
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jasmine": "file:../../node_modules/@types/jasmine",
|
||||
"@angular/compiler-cli": "file:../../dist/packages-dist/compiler-cli",
|
||||
"concurrently": "3.4.0",
|
||||
"lite-server": "2.2.2",
|
||||
"protractor": "file:../../node_modules/protractor",
|
||||
"rollup": "file:../../node_modules/rollup",
|
||||
"rollup-plugin-commonjs": "file:../../node_modules/rollup-plugin-commonjs",
|
||||
"rollup-plugin-node-resolve": "file:../../node_modules/rollup-plugin-node-resolve",
|
||||
"typescript": "file:../../node_modules/typescript"
|
||||
},
|
||||
"dependencies": {
|
||||
"@angular/animations": "file:../../dist/packages-dist/animations",
|
||||
"@angular/common": "file:../../dist/packages-dist/common",
|
||||
"@angular/compiler": "file:../../dist/packages-dist/compiler",
|
||||
"@angular/core": "file:../../dist/packages-dist/core",
|
||||
"@angular/platform-browser": "file:../../dist/packages-dist/platform-browser",
|
||||
"@angular/platform-browser-dynamic": "file:../../dist/packages-dist/platform-browser-dynamic",
|
||||
"@angular/platform-server": "file:../../dist/packages-dist/platform-server",
|
||||
"core-js": "file:../../node_modules/core-js",
|
||||
"rxjs": "file:../../node_modules/rxjs",
|
||||
"systemjs": "file:../../node_modules/systemjs",
|
||||
"zone.js": "file:../../node_modules/zone.js"
|
||||
}
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
import nodeResolve from 'rollup-plugin-node-resolve';
|
||||
import commonjs from 'rollup-plugin-commonjs';
|
||||
|
||||
export default {
|
||||
entry: 'dist/src/main.js',
|
||||
sourceMap: true,
|
||||
treeshake: true,
|
||||
moduleName: 'main',
|
||||
plugins: [
|
||||
commonjs({
|
||||
include: 'node_modules/**'
|
||||
}),
|
||||
nodeResolve({
|
||||
jsnext: true, main: true, module: true
|
||||
})
|
||||
]
|
||||
};
|
@ -1,19 +0,0 @@
|
||||
import nodeResolve from 'rollup-plugin-node-resolve';
|
||||
import commonjs from 'rollup-plugin-commonjs';
|
||||
|
||||
// a real app should make a common bundle for libraries instead of bundling them
|
||||
// in both the main module & the lazy module, but we don't care about size here
|
||||
export default {
|
||||
entry: 'dist/src/lazy.module.js',
|
||||
sourceMap: true,
|
||||
treeshake: true,
|
||||
moduleName: 'lazy',
|
||||
plugins: [
|
||||
commonjs({
|
||||
include: 'node_modules/**'
|
||||
}),
|
||||
nodeResolve({
|
||||
jsnext: true, main: true, module: true
|
||||
})
|
||||
]
|
||||
};
|
@ -1,27 +0,0 @@
|
||||
import {AfterViewInit, Compiler, Component, ViewChild, ViewContainerRef} from '@angular/core';
|
||||
|
||||
declare var System: any;
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
template: `
|
||||
<h1>Hello world!</h1>
|
||||
<div #vc></div>
|
||||
`,
|
||||
})
|
||||
export class AppComponent implements AfterViewInit {
|
||||
@ViewChild('vc', {read: ViewContainerRef}) container: ViewContainerRef;
|
||||
|
||||
constructor(private compiler: Compiler) {
|
||||
}
|
||||
|
||||
ngAfterViewInit() {
|
||||
System.import('./dist/lazy.bundle.js').then((module: any) => {
|
||||
this.compiler.compileModuleAndAllComponentsAsync(module.LazyModule)
|
||||
.then((compiled) => {
|
||||
const factory = compiled.componentFactories[0];
|
||||
this.container.createComponent(factory);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
import {Compiler, COMPILER_OPTIONS, CompilerFactory, NgModule} from '@angular/core';
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import {JitCompilerFactory} from '@angular/platform-browser-dynamic';
|
||||
|
||||
import { AppComponent } from './app.component';
|
||||
|
||||
export function createCompiler(compilerFactory: CompilerFactory) {
|
||||
return compilerFactory.createCompiler();
|
||||
}
|
||||
|
||||
@NgModule({
|
||||
imports: [BrowserModule],
|
||||
bootstrap: [AppComponent],
|
||||
declarations: [AppComponent],
|
||||
providers: [
|
||||
{provide: COMPILER_OPTIONS, useValue: {}, multi: true},
|
||||
{provide: CompilerFactory, useClass: JitCompilerFactory, deps: [COMPILER_OPTIONS]},
|
||||
{provide: Compiler, useFactory: createCompiler, deps: [CompilerFactory]}
|
||||
]
|
||||
})
|
||||
export class AppModule {}
|
||||
|
@ -1,17 +0,0 @@
|
||||
import {NgModule} from "@angular/core";
|
||||
import {Component} from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'lazy-component',
|
||||
template: 'Lazy-loaded component!'
|
||||
})
|
||||
export class LazyComponent {
|
||||
constructor() {
|
||||
}
|
||||
}
|
||||
|
||||
@NgModule({
|
||||
declarations: [LazyComponent]
|
||||
})
|
||||
export class LazyModule {
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
import { enableProdMode } from '@angular/core';
|
||||
import { platformBrowser } from '@angular/platform-browser';
|
||||
|
||||
import { AppModuleNgFactory } from './app.module.ngfactory';
|
||||
|
||||
enableProdMode();
|
||||
|
||||
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);
|
@ -1,28 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2015",
|
||||
"module": "es2015",
|
||||
"moduleResolution": "node",
|
||||
"declaration": false,
|
||||
"removeComments": true,
|
||||
"noLib": false,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"lib": ["es6", "es2015", "dom"],
|
||||
"sourceMap": true,
|
||||
"pretty": true,
|
||||
"allowUnreachableCode": false,
|
||||
"allowUnusedLabels": false,
|
||||
"noImplicitAny": true,
|
||||
"noImplicitReturns": true,
|
||||
"noImplicitUseStrict": false,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"outDir": "./dist",
|
||||
"types": [
|
||||
]
|
||||
},
|
||||
"files": [
|
||||
"src/main.ts",
|
||||
"src/lazy.module.ts"
|
||||
]
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "angular-integration",
|
||||
"description": "Assert that users with TypeScript 2.4 can type-check an Angular application",
|
||||
"description": "Assert that users with TypeScript 2.2 can type-check an Angular application",
|
||||
"version": "0.0.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@ -18,7 +18,7 @@
|
||||
"@angular/upgrade": "file:../../dist/packages-dist/upgrade",
|
||||
"@types/jasmine": "2.5.41",
|
||||
"rxjs": "file:../../node_modules/rxjs",
|
||||
"typescript": "2.4.x",
|
||||
"typescript": "file:../../node_modules/typescript",
|
||||
"zone.js": "file:../../node_modules/zone.js"
|
||||
},
|
||||
"scripts": {
|
||||
|
@ -1,41 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import * as compiler from '@angular/compiler';
|
||||
import * as compilerTesting from '@angular/compiler/testing';
|
||||
import * as core from '@angular/core';
|
||||
import * as coreTesting from '@angular/core/testing';
|
||||
import * as forms from '@angular/forms';
|
||||
import * as http from '@angular/http';
|
||||
import * as httpTesting from '@angular/http/testing';
|
||||
import * as platformBrowserDynamic from '@angular/platform-browser-dynamic';
|
||||
import * as platformBrowser from '@angular/platform-browser';
|
||||
import * as platformBrowserTesting from '@angular/platform-browser/testing';
|
||||
import * as platformServer from '@angular/platform-server';
|
||||
import * as platformServerTesting from '@angular/platform-server/testing';
|
||||
import * as router from '@angular/router';
|
||||
import * as routerTesting from '@angular/router/testing';
|
||||
import * as upgrade from '@angular/upgrade';
|
||||
|
||||
export default {
|
||||
compiler,
|
||||
compilerTesting,
|
||||
core,
|
||||
coreTesting,
|
||||
forms,
|
||||
http,
|
||||
httpTesting,
|
||||
platformBrowser,
|
||||
platformBrowserTesting,
|
||||
platformBrowserDynamic,
|
||||
platformServer,
|
||||
platformServerTesting,
|
||||
router,
|
||||
routerTesting,
|
||||
upgrade
|
||||
};
|
@ -1,27 +0,0 @@
|
||||
{
|
||||
"name": "angular-integration",
|
||||
"description": "Assert that users with TypeScript 2.5 can type-check an Angular application",
|
||||
"version": "0.0.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@angular/animations": "file:../../dist/packages-dist/animations",
|
||||
"@angular/common": "file:../../dist/packages-dist/common",
|
||||
"@angular/compiler": "file:../../dist/packages-dist/compiler",
|
||||
"@angular/compiler-cli": "file:../../dist/packages-dist/compiler-cli",
|
||||
"@angular/core": "file:../../dist/packages-dist/core",
|
||||
"@angular/forms": "file:../../dist/packages-dist/forms",
|
||||
"@angular/http": "file:../../dist/packages-dist/http",
|
||||
"@angular/platform-browser": "file:../../dist/packages-dist/platform-browser",
|
||||
"@angular/platform-browser-dynamic": "file:../../dist/packages-dist/platform-browser-dynamic",
|
||||
"@angular/platform-server": "file:../../dist/packages-dist/platform-server",
|
||||
"@angular/router": "file:../../dist/packages-dist/router",
|
||||
"@angular/upgrade": "file:../../dist/packages-dist/upgrade",
|
||||
"@types/jasmine": "2.5.41",
|
||||
"rxjs": "file:../../node_modules/rxjs",
|
||||
"typescript": "2.5.x",
|
||||
"zone.js": "file:../../node_modules/zone.js"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "tsc"
|
||||
}
|
||||
}
|
@ -1,24 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"outDir": "../../dist/typings_test_ts25/",
|
||||
"rootDir": ".",
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"es5",
|
||||
"dom",
|
||||
"es2015.collection",
|
||||
"es2015.iterable",
|
||||
"es2015.promise"
|
||||
],
|
||||
"types": [],
|
||||
"strictNullChecks": true
|
||||
},
|
||||
"files": [
|
||||
"include-all.ts",
|
||||
"node_modules/@types/jasmine/index.d.ts"
|
||||
]
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "angular-srcs",
|
||||
"version": "5.1.0-rc.1",
|
||||
"version": "5.0.4",
|
||||
"private": true,
|
||||
"branchPattern": "2.0.*",
|
||||
"description": "Angular - a web framework for modern web apps",
|
||||
@ -32,7 +32,7 @@
|
||||
"fsevents": "1.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@bazel/typescript": "0.3.2",
|
||||
"@bazel/typescript": "0.2.x",
|
||||
"@types/angularjs": "1.5.14-alpha",
|
||||
"@types/base64-js": "1.2.5",
|
||||
"@types/chokidar": "1.7.3",
|
||||
@ -95,10 +95,10 @@
|
||||
"source-map-support": "0.4.18",
|
||||
"systemjs": "0.18.10",
|
||||
"ts-api-guardian": "0.2.2",
|
||||
"tsickle": "0.25.5",
|
||||
"tsickle": "0.24.x",
|
||||
"tslint": "5.7.0",
|
||||
"tslint-eslint-rules": "4.1.1",
|
||||
"typescript": "2.5.x",
|
||||
"typescript": "2.4.2",
|
||||
"uglify-js": "2.8.29",
|
||||
"universal-analytics": "0.4.15",
|
||||
"vlq": "0.2.2",
|
||||
|
@ -62,8 +62,8 @@ export class NoopAnimationPlayer implements AnimationPlayer {
|
||||
init(): void {}
|
||||
play(): void {
|
||||
if (!this.hasStarted()) {
|
||||
this._onStart();
|
||||
this.triggerMicrotask();
|
||||
this._onStart();
|
||||
}
|
||||
this._started = true;
|
||||
}
|
||||
|
@ -6,9 +6,9 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
import {fakeAsync} from '@angular/core/testing';
|
||||
|
||||
import {flushMicrotasks} from '../../core/testing/src/fake_async';
|
||||
import {NoopAnimationPlayer} from '../src/players/animation_player';
|
||||
import {scheduleMicroTask} from '../src/util';
|
||||
|
||||
export function main() {
|
||||
describe('NoopAnimationPlayer', function() {
|
||||
@ -61,21 +61,6 @@ export function main() {
|
||||
player.finish();
|
||||
expect(log).toEqual(['started', 'done']);
|
||||
|
||||
flushMicrotasks();
|
||||
expect(log).toEqual(['started', 'done']);
|
||||
}));
|
||||
|
||||
it('should fire off start callbacks before triggering the finish callback', fakeAsync(() => {
|
||||
const log: string[] = [];
|
||||
|
||||
const player = new NoopAnimationPlayer();
|
||||
player.onStart(() => { scheduleMicroTask(() => log.push('started')); });
|
||||
player.onDone(() => log.push('done'));
|
||||
expect(log).toEqual([]);
|
||||
|
||||
player.play();
|
||||
expect(log).toEqual([]);
|
||||
|
||||
flushMicrotasks();
|
||||
expect(log).toEqual(['started', 'done']);
|
||||
}));
|
||||
|
@ -6,10 +6,10 @@
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@angular/compiler-cli": "0.0.0-PLACEHOLDER",
|
||||
"typescript": ">=2.4.2 <2.6"
|
||||
"typescript": ">=2.4.2 <2.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@bazel/typescript": "0.3.2",
|
||||
"@bazel/typescript": "0.2.x",
|
||||
"@types/node": "6.0.84"
|
||||
},
|
||||
"repository": {
|
||||
|
@ -5,7 +5,8 @@
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
// TODO(tbosch): figure out why we need this as it breaks node code within ngc-wrapped
|
||||
/// <reference types="node" />
|
||||
import * as ng from '@angular/compiler-cli';
|
||||
import {BazelOptions, CachedFileLoader, CompilerHost, FileCache, FileLoader, UncachedFileLoader, constructManifest, debug, fixUmdModuleDeclarations, parseTsconfig, runAsWorker, runWorkerLoop} from '@bazel/typescript';
|
||||
import * as fs from 'fs';
|
||||
@ -164,19 +165,11 @@ export function compile({allowNonHermeticReads, allDepsCompiledWithBazel = true,
|
||||
}
|
||||
return origBazelHostFileExist.call(bazelHost, fileName);
|
||||
};
|
||||
const origBazelHostShouldNameModule = bazelHost.shouldNameModule.bind(bazelHost);
|
||||
bazelHost.shouldNameModule = (fileName: string) =>
|
||||
origBazelHostShouldNameModule(fileName) || NGC_GEN_FILES.test(fileName);
|
||||
|
||||
const ngHost = ng.createCompilerHost({options: compilerOpts, tsHost: bazelHost});
|
||||
|
||||
ngHost.fileNameToModuleName = (importedFilePath: string, containingFilePath: string) => {
|
||||
if ((compilerOpts.module === ts.ModuleKind.UMD || compilerOpts.module === ts.ModuleKind.AMD) &&
|
||||
ngHost.amdModuleName) {
|
||||
return ngHost.amdModuleName({ fileName: importedFilePath } as ts.SourceFile);
|
||||
}
|
||||
return relativeToRootDirs(importedFilePath, compilerOpts.rootDirs).replace(EXT, '');
|
||||
};
|
||||
ngHost.fileNameToModuleName = (importedFilePath: string, containingFilePath: string) =>
|
||||
relativeToRootDirs(importedFilePath, compilerOpts.rootDirs).replace(EXT, '');
|
||||
ngHost.toSummaryFileName = (fileName: string, referringSrcFileName: string) =>
|
||||
ngHost.fileNameToModuleName(fileName, referringSrcFileName);
|
||||
if (allDepsCompiledWithBazel) {
|
||||
|
@ -64,10 +64,6 @@ export function createTsConfig(options: TsConfigOptions) {
|
||||
'es5Mode': true,
|
||||
'manifest': createManifestPath(options),
|
||||
'compilationTargetSrc': options.compilationTargetSrc,
|
||||
// Override this property from the real tsconfig we read
|
||||
// Because we ask for :empty_tsconfig.json, we get the ES6 version which
|
||||
// expects to write externs, yet that doesn't work under this fixture.
|
||||
'tsickleExternsPath': '',
|
||||
},
|
||||
'files': options.files,
|
||||
'angularCompilerOptions': {
|
||||
|
@ -81,9 +81,7 @@ export class Runner {
|
||||
{provide: WebDriverAdapter, useValue: adapter}
|
||||
]);
|
||||
|
||||
// TODO: With TypeScript 2.5 injector.get does not infer correctly the
|
||||
// return type. Remove 'any' and investigate the issue.
|
||||
const sampler = injector.get(Sampler) as any;
|
||||
const sampler = injector.get(Sampler);
|
||||
return sampler.sample();
|
||||
});
|
||||
}
|
||||
|
@ -17,7 +17,7 @@ export function main() {
|
||||
ids.map(id => ({provide: id, useValue: new MockMetric(id)})),
|
||||
MultiMetric.provideWith(ids)
|
||||
])
|
||||
.get<MultiMetric>(MultiMetric);
|
||||
.get(MultiMetric);
|
||||
return Promise.resolve(m);
|
||||
}
|
||||
|
||||
|
@ -34,7 +34,7 @@ export function main() {
|
||||
}
|
||||
}
|
||||
];
|
||||
return Injector.create(providers).get<JsonFileReporter>(JsonFileReporter);
|
||||
return Injector.create(providers).get(JsonFileReporter);
|
||||
}
|
||||
|
||||
it('should write all data into a file',
|
||||
|
@ -17,7 +17,7 @@ export function main() {
|
||||
ids.map(id => ({provide: id, useValue: new MockReporter(id)})),
|
||||
MultiReporter.provideWith(ids)
|
||||
])
|
||||
.get<MultiReporter>(MultiReporter);
|
||||
.get(MultiReporter);
|
||||
return Promise.resolve(r);
|
||||
}
|
||||
|
||||
|
@ -4895,5 +4895,6 @@ switch (goog.LOCALE) {
|
||||
}
|
||||
|
||||
if (l) {
|
||||
registerLocaleData(l, goog.LOCALE);
|
||||
l[0] = goog.LOCALE;
|
||||
registerLocaleData(l);
|
||||
}
|
||||
|
@ -17,17 +17,9 @@ export const LOCALE_DATA: {[localeId: string]: any} = {};
|
||||
*
|
||||
* @experimental i18n support is experimental.
|
||||
*/
|
||||
// The signature registerLocaleData(data: any, extraData?: any) is deprecated since v5.1
|
||||
export function registerLocaleData(data: any, localeId?: string | any, extraData?: any): void {
|
||||
if (typeof localeId !== 'string') {
|
||||
extraData = localeId;
|
||||
localeId = data[LocaleDataIndex.LocaleId];
|
||||
}
|
||||
|
||||
localeId = localeId.toLowerCase().replace(/_/g, '-');
|
||||
|
||||
export function registerLocaleData(data: any, extraData?: any) {
|
||||
const localeId = data[LocaleDataIndex.LocaleId].toLowerCase().replace(/_/g, '-');
|
||||
LOCALE_DATA[localeId] = data;
|
||||
|
||||
if (extraData) {
|
||||
LOCALE_DATA[localeId][LocaleDataIndex.ExtraData] = extraData;
|
||||
}
|
||||
|
@ -10,8 +10,8 @@ import localeCaESVALENCIA from '../../locales/ca-ES-VALENCIA';
|
||||
import localeEn from '../../locales/en';
|
||||
import localeFr from '../../locales/fr';
|
||||
import localeFrCA from '../../locales/fr-CA';
|
||||
import {registerLocaleData} from '../../src/i18n/locale_data';
|
||||
import {findLocaleData} from '../../src/i18n/locale_data_api';
|
||||
import {registerLocaleData} from '../../src/i18n/locale_data';
|
||||
|
||||
export function main() {
|
||||
describe('locale data api', () => {
|
||||
@ -20,8 +20,6 @@ export function main() {
|
||||
registerLocaleData(localeEn);
|
||||
registerLocaleData(localeFr);
|
||||
registerLocaleData(localeFrCA);
|
||||
registerLocaleData(localeFr, 'fake-id');
|
||||
registerLocaleData(localeFrCA, 'fake_Id2');
|
||||
});
|
||||
|
||||
describe('findLocaleData', () => {
|
||||
@ -44,12 +42,6 @@ export function main() {
|
||||
expect(findLocaleData('ca-ES-VALENCIA')).toEqual(localeCaESVALENCIA);
|
||||
expect(findLocaleData('CA_es_Valencia')).toEqual(localeCaESVALENCIA);
|
||||
});
|
||||
|
||||
it(`should find the LOCALE_DATA if the locale id was registered`, () => {
|
||||
expect(findLocaleData('fake-id')).toEqual(localeFr);
|
||||
expect(findLocaleData('fake_iD')).toEqual(localeFr);
|
||||
expect(findLocaleData('fake-id2')).toEqual(localeFrCA);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
@ -42,9 +42,7 @@ export class SpyLocation implements Location {
|
||||
return currPath == givenPath + (query.length > 0 ? ('?' + query) : '');
|
||||
}
|
||||
|
||||
simulateUrlPop(pathname: string) {
|
||||
this._subject.emit({'url': pathname, 'pop': true, 'type': 'popstate'});
|
||||
}
|
||||
simulateUrlPop(pathname: string) { this._subject.emit({'url': pathname, 'pop': true}); }
|
||||
|
||||
simulateHashChange(pathname: string) {
|
||||
// Because we don't prevent the native event, the browser will independently update the path
|
||||
|
@ -11,11 +11,11 @@
|
||||
"dependencies": {
|
||||
"reflect-metadata": "^0.1.2",
|
||||
"minimist": "^1.2.0",
|
||||
"tsickle": "^0.25.5",
|
||||
"tsickle": "^0.24.0",
|
||||
"chokidar": "^1.4.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": ">=2.4.2 <2.6",
|
||||
"typescript": ">=2.4.2 <2.5",
|
||||
"@angular/compiler": "0.0.0-PLACEHOLDER"
|
||||
},
|
||||
"repository": {
|
||||
|
@ -20,6 +20,7 @@ import {GENERATED_FILES} from './transformers/util';
|
||||
|
||||
import {exitCodeFromResult, performCompilation, readConfiguration, formatDiagnostics, Diagnostics, ParsedConfiguration, PerformCompilationResult, filterErrorsAndWarnings} from './perform_compile';
|
||||
import {performWatchCompilation, createPerformWatchHost} from './perform_watch';
|
||||
import {isSyntaxError} from '@angular/compiler';
|
||||
|
||||
export function main(
|
||||
args: string[], consoleError: (s: string) => void = console.error,
|
||||
|
@ -8,8 +8,8 @@
|
||||
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {Evaluator, errorSymbol, recordMapEntry} from './evaluator';
|
||||
import {ClassMetadata, ConstructorMetadata, FunctionMetadata, InterfaceMetadata, METADATA_VERSION, MemberMetadata, MetadataEntry, MetadataError, MetadataMap, MetadataSymbolicBinaryExpression, MetadataSymbolicCallExpression, MetadataSymbolicExpression, MetadataSymbolicIfExpression, MetadataSymbolicIndexExpression, MetadataSymbolicPrefixExpression, MetadataSymbolicReferenceExpression, MetadataSymbolicSelectExpression, MetadataSymbolicSpreadExpression, MetadataValue, MethodMetadata, ModuleExportMetadata, ModuleMetadata, isClassMetadata, isConstructorMetadata, isFunctionMetadata, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataImportDefaultReference, isMetadataImportedSymbolReferenceExpression, isMetadataSymbolicExpression, isMetadataSymbolicReferenceExpression, isMetadataSymbolicSelectExpression, isMethodMetadata} from './schema';
|
||||
import {Evaluator, errorSymbol} from './evaluator';
|
||||
import {ClassMetadata, ConstructorMetadata, FunctionMetadata, InterfaceMetadata, METADATA_VERSION, MemberMetadata, MetadataEntry, MetadataError, MetadataMap, MetadataSymbolicBinaryExpression, MetadataSymbolicCallExpression, MetadataSymbolicExpression, MetadataSymbolicIfExpression, MetadataSymbolicIndexExpression, MetadataSymbolicPrefixExpression, MetadataSymbolicReferenceExpression, MetadataSymbolicSelectExpression, MetadataSymbolicSpreadExpression, MetadataValue, MethodMetadata, ModuleExportMetadata, ModuleMetadata, isClassMetadata, isConstructorMetadata, isFunctionMetadata, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataSymbolicExpression, isMetadataSymbolicReferenceExpression, isMetadataSymbolicSelectExpression, isMethodMetadata} from './schema';
|
||||
import {Symbols} from './symbols';
|
||||
|
||||
const isStatic = (node: ts.Node) => ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Static;
|
||||
@ -76,7 +76,8 @@ export class MetadataCollector {
|
||||
}
|
||||
|
||||
function recordEntry<T extends MetadataEntry>(entry: T, node: ts.Node): T {
|
||||
return recordMapEntry(entry, node, nodeMap, sourceFile);
|
||||
nodeMap.set(entry, node);
|
||||
return entry;
|
||||
}
|
||||
|
||||
function errorSym(
|
||||
@ -115,8 +116,8 @@ export class MetadataCollector {
|
||||
function classMetadataOf(classDeclaration: ts.ClassDeclaration): ClassMetadata {
|
||||
const result: ClassMetadata = {__symbolic: 'class'};
|
||||
|
||||
function getDecorators(decorators: ReadonlyArray<ts.Decorator>| undefined):
|
||||
MetadataSymbolicExpression[]|undefined {
|
||||
function getDecorators(decorators: ts.Decorator[] | undefined): MetadataSymbolicExpression[]|
|
||||
undefined {
|
||||
if (decorators && decorators.length)
|
||||
return decorators.map(decorator => objFromDecorator(decorator));
|
||||
return undefined;
|
||||
@ -550,7 +551,6 @@ export class MetadataCollector {
|
||||
__symbolic: 'module',
|
||||
version: this.options.version || METADATA_VERSION, metadata
|
||||
};
|
||||
if (sourceFile.moduleName) result.importAs = sourceFile.moduleName;
|
||||
if (exports) result.exports = exports;
|
||||
return result;
|
||||
}
|
||||
|
@ -9,11 +9,10 @@
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {CollectorOptions} from './collector';
|
||||
import {ClassMetadata, FunctionMetadata, InterfaceMetadata, MetadataEntry, MetadataError, MetadataImportedSymbolReferenceExpression, MetadataSourceLocationInfo, MetadataSymbolicCallExpression, MetadataValue, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataImportDefaultReference, isMetadataImportedSymbolReferenceExpression, isMetadataModuleReferenceExpression, isMetadataSymbolicReferenceExpression, isMetadataSymbolicSpreadExpression} from './schema';
|
||||
import {MetadataEntry, MetadataError, MetadataImportedSymbolReferenceExpression, MetadataSymbolicCallExpression, MetadataValue, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataModuleReferenceExpression, isMetadataSymbolicReferenceExpression, isMetadataSymbolicSpreadExpression} from './schema';
|
||||
import {Symbols} from './symbols';
|
||||
|
||||
|
||||
|
||||
// In TypeScript 2.1 the spread element kind was renamed.
|
||||
const spreadElementSyntaxKind: ts.SyntaxKind =
|
||||
(ts.SyntaxKind as any).SpreadElement || (ts.SyntaxKind as any).SpreadElementExpression;
|
||||
@ -39,24 +38,6 @@ function isCallOf(callExpression: ts.CallExpression, ident: string): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function recordMapEntry<T extends MetadataEntry>(
|
||||
entry: T, node: ts.Node,
|
||||
nodeMap: Map<MetadataValue|ClassMetadata|InterfaceMetadata|FunctionMetadata, ts.Node>,
|
||||
sourceFile?: ts.SourceFile) {
|
||||
if (!nodeMap.has(entry)) {
|
||||
nodeMap.set(entry, node);
|
||||
if (node && (isMetadataImportedSymbolReferenceExpression(entry) ||
|
||||
isMetadataImportDefaultReference(entry)) &&
|
||||
entry.line == null) {
|
||||
const info = sourceInfo(node, sourceFile);
|
||||
if (info.line != null) entry.line = info.line;
|
||||
if (info.character != null) entry.character = info.character;
|
||||
}
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* ts.forEachChild stops iterating children when the callback return a truthy value.
|
||||
* This method inverts this to implement an `every` style iterator. It will return
|
||||
@ -95,23 +76,22 @@ function getSourceFileOfNode(node: ts.Node | undefined): ts.SourceFile {
|
||||
return <ts.SourceFile>node;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function sourceInfo(
|
||||
node: ts.Node | undefined, sourceFile: ts.SourceFile | undefined): MetadataSourceLocationInfo {
|
||||
if (node) {
|
||||
sourceFile = sourceFile || getSourceFileOfNode(node);
|
||||
if (sourceFile) {
|
||||
return ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile));
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function errorSymbol(
|
||||
message: string, node?: ts.Node, context?: {[name: string]: string},
|
||||
sourceFile?: ts.SourceFile): MetadataError {
|
||||
const result: MetadataError = {__symbolic: 'error', message, ...sourceInfo(node, sourceFile)};
|
||||
let result: MetadataError|undefined = undefined;
|
||||
if (node) {
|
||||
sourceFile = sourceFile || getSourceFileOfNode(node);
|
||||
if (sourceFile) {
|
||||
const {line, character} =
|
||||
ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile));
|
||||
result = {__symbolic: 'error', message, line, character};
|
||||
}
|
||||
}
|
||||
if (!result) {
|
||||
result = {__symbolic: 'error', message};
|
||||
}
|
||||
if (context) {
|
||||
result.context = context;
|
||||
}
|
||||
@ -262,7 +242,8 @@ export class Evaluator {
|
||||
}
|
||||
entry = newEntry;
|
||||
}
|
||||
return recordMapEntry(entry, node, t.nodeMap);
|
||||
t.nodeMap.set(entry, node);
|
||||
return entry;
|
||||
}
|
||||
|
||||
function isFoldableError(value: any): value is MetadataError {
|
||||
@ -275,9 +256,6 @@ export class Evaluator {
|
||||
// Encode as a global reference. StaticReflector will check the reference.
|
||||
return recordEntry({__symbolic: 'reference', name}, node);
|
||||
}
|
||||
if (reference && isMetadataSymbolicReferenceExpression(reference)) {
|
||||
return recordEntry({...reference}, node);
|
||||
}
|
||||
return reference;
|
||||
};
|
||||
|
||||
@ -650,7 +628,7 @@ export class Evaluator {
|
||||
return recordEntry({__symbolic: 'if', condition, thenExpression, elseExpression}, node);
|
||||
case ts.SyntaxKind.FunctionExpression:
|
||||
case ts.SyntaxKind.ArrowFunction:
|
||||
return recordEntry(errorSymbol('Lambda not supported', node), node);
|
||||
return recordEntry(errorSymbol('Function call not supported', node), node);
|
||||
case ts.SyntaxKind.TaggedTemplateExpression:
|
||||
return recordEntry(
|
||||
errorSymbol('Tagged template expressions are not supported in metadata', node), node);
|
||||
|
@ -178,20 +178,7 @@ export function isMetadataSymbolicIfExpression(value: any): value is MetadataSym
|
||||
return value && value.__symbolic === 'if';
|
||||
}
|
||||
|
||||
export interface MetadataSourceLocationInfo {
|
||||
/**
|
||||
* The line number of the error in the .ts file the metadata was created for.
|
||||
*/
|
||||
line?: number;
|
||||
|
||||
/**
|
||||
* The number of utf8 code-units from the beginning of the file of the error.
|
||||
*/
|
||||
character?: number;
|
||||
}
|
||||
|
||||
export interface MetadataGlobalReferenceExpression extends MetadataSymbolicExpression,
|
||||
MetadataSourceLocationInfo {
|
||||
export interface MetadataGlobalReferenceExpression extends MetadataSymbolicExpression {
|
||||
__symbolic: 'reference';
|
||||
name: string;
|
||||
arguments?: MetadataValue[];
|
||||
@ -201,8 +188,7 @@ export function isMetadataGlobalReferenceExpression(value: any):
|
||||
return value && value.name && !value.module && isMetadataSymbolicReferenceExpression(value);
|
||||
}
|
||||
|
||||
export interface MetadataModuleReferenceExpression extends MetadataSymbolicExpression,
|
||||
MetadataSourceLocationInfo {
|
||||
export interface MetadataModuleReferenceExpression extends MetadataSymbolicExpression {
|
||||
__symbolic: 'reference';
|
||||
module: string;
|
||||
}
|
||||
@ -212,8 +198,7 @@ export function isMetadataModuleReferenceExpression(value: any):
|
||||
isMetadataSymbolicReferenceExpression(value);
|
||||
}
|
||||
|
||||
export interface MetadataImportedSymbolReferenceExpression extends MetadataSymbolicExpression,
|
||||
MetadataSourceLocationInfo {
|
||||
export interface MetadataImportedSymbolReferenceExpression extends MetadataSymbolicExpression {
|
||||
__symbolic: 'reference';
|
||||
module: string;
|
||||
name: string;
|
||||
@ -224,8 +209,7 @@ export function isMetadataImportedSymbolReferenceExpression(value: any):
|
||||
return value && value.module && !!value.name && isMetadataSymbolicReferenceExpression(value);
|
||||
}
|
||||
|
||||
export interface MetadataImportedDefaultReferenceExpression extends MetadataSymbolicExpression,
|
||||
MetadataSourceLocationInfo {
|
||||
export interface MetadataImportedDefaultReferenceExpression extends MetadataSymbolicExpression {
|
||||
__symbolic: 'reference';
|
||||
module: string;
|
||||
default:
|
||||
@ -234,7 +218,7 @@ export interface MetadataImportedDefaultReferenceExpression extends MetadataSymb
|
||||
}
|
||||
export function isMetadataImportDefaultReference(value: any):
|
||||
value is MetadataImportedDefaultReferenceExpression {
|
||||
return value && value.module && value.default && isMetadataSymbolicReferenceExpression(value);
|
||||
return value.module && value.default && isMetadataSymbolicReferenceExpression(value);
|
||||
}
|
||||
|
||||
export type MetadataSymbolicReferenceExpression = MetadataGlobalReferenceExpression |
|
||||
@ -264,7 +248,7 @@ export function isMetadataSymbolicSpreadExpression(value: any):
|
||||
return value && value.__symbolic === 'spread';
|
||||
}
|
||||
|
||||
export interface MetadataError extends MetadataSourceLocationInfo {
|
||||
export interface MetadataError {
|
||||
__symbolic: 'error';
|
||||
|
||||
/**
|
||||
@ -275,6 +259,16 @@ export interface MetadataError extends MetadataSourceLocationInfo {
|
||||
*/
|
||||
message: string;
|
||||
|
||||
/**
|
||||
* The line number of the error in the .ts file the metadata was created for.
|
||||
*/
|
||||
line?: number;
|
||||
|
||||
/**
|
||||
* The number of utf8 code-units from the beginning of the file of the error.
|
||||
*/
|
||||
character?: number;
|
||||
|
||||
/**
|
||||
* The module of the error (only used in bundled metadata)
|
||||
*/
|
||||
@ -286,7 +280,6 @@ export interface MetadataError extends MetadataSourceLocationInfo {
|
||||
*/
|
||||
context?: {[name: string]: string};
|
||||
}
|
||||
|
||||
export function isMetadataError(value: any): value is MetadataError {
|
||||
return value && value.__symbolic === 'error';
|
||||
}
|
||||
|
@ -6,7 +6,7 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {Position, isSyntaxError, syntaxError} from '@angular/compiler';
|
||||
import {isSyntaxError, syntaxError} from '@angular/compiler';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as ts from 'typescript';
|
||||
@ -29,76 +29,30 @@ const defaultFormatHost: ts.FormatDiagnosticsHost = {
|
||||
getNewLine: () => ts.sys.newLine
|
||||
};
|
||||
|
||||
function displayFileName(fileName: string, host: ts.FormatDiagnosticsHost): string {
|
||||
return path.relative(host.getCurrentDirectory(), host.getCanonicalFileName(fileName));
|
||||
}
|
||||
|
||||
export function formatDiagnosticPosition(
|
||||
position: Position, host: ts.FormatDiagnosticsHost = defaultFormatHost): string {
|
||||
return `${displayFileName(position.fileName, host)}(${position.line + 1},${position.column+1})`;
|
||||
}
|
||||
|
||||
export function flattenDiagnosticMessageChain(
|
||||
chain: api.DiagnosticMessageChain, host: ts.FormatDiagnosticsHost = defaultFormatHost): string {
|
||||
let result = chain.messageText;
|
||||
let indent = 1;
|
||||
let current = chain.next;
|
||||
const newLine = host.getNewLine();
|
||||
while (current) {
|
||||
result += newLine;
|
||||
for (let i = 0; i < indent; i++) {
|
||||
result += ' ';
|
||||
}
|
||||
result += current.messageText;
|
||||
const position = current.position;
|
||||
if (position) {
|
||||
result += ` at ${formatDiagnosticPosition(position, host)}`;
|
||||
}
|
||||
current = current.next;
|
||||
indent++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function formatDiagnostic(
|
||||
diagnostic: api.Diagnostic, host: ts.FormatDiagnosticsHost = defaultFormatHost) {
|
||||
let result = '';
|
||||
const newLine = host.getNewLine();
|
||||
const span = diagnostic.span;
|
||||
if (span) {
|
||||
result += `${formatDiagnosticPosition({
|
||||
fileName: span.start.file.url,
|
||||
line: span.start.line,
|
||||
column: span.start.col
|
||||
}, host)}: `;
|
||||
} else if (diagnostic.position) {
|
||||
result += `${formatDiagnosticPosition(diagnostic.position, host)}: `;
|
||||
}
|
||||
if (diagnostic.span && diagnostic.span.details) {
|
||||
result += `: ${diagnostic.span.details}, ${diagnostic.messageText}${newLine}`;
|
||||
} else if (diagnostic.chain) {
|
||||
result += `${flattenDiagnosticMessageChain(diagnostic.chain, host)}.${newLine}`;
|
||||
} else {
|
||||
result += `: ${diagnostic.messageText}${newLine}`;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function formatDiagnostics(
|
||||
diags: Diagnostics, host: ts.FormatDiagnosticsHost = defaultFormatHost): string {
|
||||
diags: Diagnostics, tsFormatHost: ts.FormatDiagnosticsHost = defaultFormatHost): string {
|
||||
if (diags && diags.length) {
|
||||
return diags
|
||||
.map(diagnostic => {
|
||||
if (api.isTsDiagnostic(diagnostic)) {
|
||||
return ts.formatDiagnostics([diagnostic], host);
|
||||
.map(d => {
|
||||
if (api.isTsDiagnostic(d)) {
|
||||
return ts.formatDiagnostics([d], tsFormatHost);
|
||||
} else {
|
||||
return formatDiagnostic(diagnostic, host);
|
||||
let res = ts.DiagnosticCategory[d.category];
|
||||
if (d.span) {
|
||||
res +=
|
||||
` at ${d.span.start.file.url}(${d.span.start.line + 1},${d.span.start.col + 1})`;
|
||||
}
|
||||
if (d.span && d.span.details) {
|
||||
res += `: ${d.span.details}, ${d.messageText}\n`;
|
||||
} else {
|
||||
res += `: ${d.messageText}\n`;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
})
|
||||
.join('');
|
||||
} else {
|
||||
} else
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export interface ParsedConfiguration {
|
||||
|
@ -6,24 +6,16 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {GeneratedFile, ParseSourceSpan, Position} from '@angular/compiler';
|
||||
import {GeneratedFile, ParseSourceSpan} from '@angular/compiler';
|
||||
import * as ts from 'typescript';
|
||||
|
||||
export const DEFAULT_ERROR_CODE = 100;
|
||||
export const UNKNOWN_ERROR_CODE = 500;
|
||||
export const SOURCE = 'angular' as 'angular';
|
||||
|
||||
export interface DiagnosticMessageChain {
|
||||
messageText: string;
|
||||
position?: Position;
|
||||
next?: DiagnosticMessageChain;
|
||||
}
|
||||
|
||||
export interface Diagnostic {
|
||||
messageText: string;
|
||||
span?: ParseSourceSpan;
|
||||
position?: Position;
|
||||
chain?: DiagnosticMessageChain;
|
||||
category: ts.DiagnosticCategory;
|
||||
code: number;
|
||||
source: 'angular';
|
||||
@ -200,13 +192,6 @@ export interface CompilerHost extends ts.CompilerHost {
|
||||
* cause a diagnostics diagnostic error or an exception to be thrown.
|
||||
*/
|
||||
readResource?(fileName: string): Promise<string>|string;
|
||||
/**
|
||||
* Produce an AMD module name for the source file. Used in Bazel.
|
||||
*
|
||||
* An AMD module can have an arbitrary name, so that it is require'd by name
|
||||
* rather than by path. See http://requirejs.org/docs/whyamd.html#namedmodules
|
||||
*/
|
||||
amdModuleName?(sf: ts.SourceFile): string|undefined;
|
||||
}
|
||||
|
||||
export enum EmitFlags {
|
||||
|
@ -41,13 +41,6 @@ export interface CodeGenerator {
|
||||
findGeneratedFileNames(fileName: string): string[];
|
||||
}
|
||||
|
||||
function assert<T>(condition: T | null | undefined) {
|
||||
if (!condition) {
|
||||
// TODO(chuckjaz): do the right thing
|
||||
}
|
||||
return condition !;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements the following hosts based on an api.CompilerHost:
|
||||
* - ts.CompilerHost to be consumed by a ts.Program
|
||||
@ -120,7 +113,7 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos
|
||||
return sf ? this.metadataProvider.getMetadata(sf) : undefined;
|
||||
},
|
||||
fileExists: (filePath) => this.originalFileExists(filePath),
|
||||
readFile: (filePath) => assert(this.context.readFile(filePath)),
|
||||
readFile: (filePath) => this.context.readFile(filePath),
|
||||
};
|
||||
}
|
||||
|
||||
@ -303,11 +296,6 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos
|
||||
/* emitSourceMaps */ false);
|
||||
const sf = ts.createSourceFile(
|
||||
genFile.genFileUrl, sourceText, this.options.target || ts.ScriptTarget.Latest);
|
||||
if ((this.options.module === ts.ModuleKind.AMD || this.options.module === ts.ModuleKind.UMD) &&
|
||||
this.context.amdModuleName) {
|
||||
const moduleName = this.context.amdModuleName(sf);
|
||||
if (moduleName) sf.moduleName = moduleName;
|
||||
}
|
||||
this.generatedSourceFiles.set(genFile.genFileUrl, {
|
||||
sourceFile: sf,
|
||||
emitCtx: context, externalReferences,
|
||||
@ -433,7 +421,7 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos
|
||||
return summary.text;
|
||||
}
|
||||
if (this.originalFileExists(filePath)) {
|
||||
return assert(this.context.readFile(filePath));
|
||||
return this.context.readFile(filePath);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@ -484,7 +472,7 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos
|
||||
if (!this.originalFileExists(filePath)) {
|
||||
throw syntaxError(`Error: Resource file not found: ${filePath}`);
|
||||
}
|
||||
return assert(this.context.readFile(filePath));
|
||||
return this.context.readFile(filePath);
|
||||
}
|
||||
|
||||
private hasBundleIndex(filePath: string): boolean {
|
||||
@ -502,13 +490,13 @@ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHos
|
||||
if (this.originalFileExists(packageFile)) {
|
||||
// Once we see a package.json file, assume false until it we find the bundle index.
|
||||
result = false;
|
||||
const packageContent: any = JSON.parse(assert(this.context.readFile(packageFile)));
|
||||
const packageContent: any = JSON.parse(this.context.readFile(packageFile));
|
||||
if (packageContent.typings) {
|
||||
const typings = path.normalize(path.join(directory, packageContent.typings));
|
||||
if (DTS.test(typings)) {
|
||||
const metadataFile = typings.replace(DTS, '.metadata.json');
|
||||
if (this.originalFileExists(metadataFile)) {
|
||||
const metadata = JSON.parse(assert(this.context.readFile(metadataFile)));
|
||||
const metadata = JSON.parse(this.context.readFile(metadataFile));
|
||||
if (metadata.flatModuleIndexRedirect) {
|
||||
this.flatModuleIndexRedirectNames.add(typings);
|
||||
// Note: don't set result = true,
|
||||
|
@ -112,7 +112,6 @@ function upgradeMetadataWithDtsData(
|
||||
newMetadata.metadata[prop] = dtsMetadata.metadata[prop];
|
||||
}
|
||||
}
|
||||
if (dtsMetadata['importAs']) newMetadata['importAs'] = dtsMetadata['importAs'];
|
||||
|
||||
// Only copy exports from exports from metadata prior to version 3.
|
||||
// Starting with version 3 the collector began collecting exports and
|
||||
|
@ -6,7 +6,7 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {AotCompiler, AotCompilerHost, AotCompilerOptions, EmitterVisitorContext, FormattedMessageChain, GeneratedFile, MessageBundle, NgAnalyzedFile, NgAnalyzedModules, ParseSourceSpan, Position, Serializer, TypeScriptEmitter, Xliff, Xliff2, Xmb, core, createAotCompiler, getParseErrors, isFormattedError, isSyntaxError} from '@angular/compiler';
|
||||
import {AotCompiler, AotCompilerHost, AotCompilerOptions, EmitterVisitorContext, GeneratedFile, MessageBundle, NgAnalyzedFile, NgAnalyzedModules, ParseSourceSpan, Serializer, TypeScriptEmitter, Xliff, Xliff2, Xmb, core, createAotCompiler, getParseErrors, isSyntaxError} from '@angular/compiler';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as ts from 'typescript';
|
||||
@ -14,13 +14,14 @@ import * as ts from 'typescript';
|
||||
import {TypeCheckHost, translateDiagnostics} from '../diagnostics/translate_diagnostics';
|
||||
import {ModuleMetadata, createBundleIndexHost} from '../metadata/index';
|
||||
|
||||
import {CompilerHost, CompilerOptions, CustomTransformers, DEFAULT_ERROR_CODE, Diagnostic, DiagnosticMessageChain, EmitFlags, LazyRoute, LibrarySummary, Program, SOURCE, TsEmitArguments, TsEmitCallback} from './api';
|
||||
import {CompilerHost, CompilerOptions, CustomTransformers, DEFAULT_ERROR_CODE, Diagnostic, EmitFlags, LazyRoute, LibrarySummary, Program, SOURCE, TsEmitArguments, TsEmitCallback} from './api';
|
||||
import {CodeGenerator, TsCompilerAotCompilerTypeCheckHostAdapter, getOriginalReferences} from './compiler_host';
|
||||
import {LowerMetadataCache, getExpressionLoweringTransformFactory} from './lower_expressions';
|
||||
import {getAngularEmitterTransformFactory} from './node_emitter_transform';
|
||||
import {GENERATED_FILES, StructureIsReused, createMessageDiagnostic, isInRootDir, ngToTsDiagnostic, tsStructureIsReused} from './util';
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Maximum number of files that are emitable via calling ts.Program.emit
|
||||
* passing individual targetSourceFiles.
|
||||
@ -377,12 +378,10 @@ class AngularCompilerProgram implements Program {
|
||||
}
|
||||
|
||||
private get structuralDiagnostics(): Diagnostic[] {
|
||||
let diagnostics = this._structuralDiagnostics;
|
||||
if (!diagnostics) {
|
||||
if (!this._structuralDiagnostics) {
|
||||
this.initSync();
|
||||
diagnostics = (this._structuralDiagnostics = this._structuralDiagnostics || []);
|
||||
}
|
||||
return diagnostics;
|
||||
return this._structuralDiagnostics !;
|
||||
}
|
||||
|
||||
private get tsProgram(): ts.Program {
|
||||
@ -431,9 +430,16 @@ class AngularCompilerProgram implements Program {
|
||||
this.rootNames, this.options, this.host, this.metadataCache, codegen,
|
||||
this.oldProgramLibrarySummaries);
|
||||
const aotOptions = getAotCompilerOptions(this.options);
|
||||
const errorCollector = (this.options.collectAllErrors || this.options.fullTemplateTypeCheck) ?
|
||||
(err: any) => this._addStructuralDiagnostics(err) :
|
||||
undefined;
|
||||
this._structuralDiagnostics = [];
|
||||
const errorCollector =
|
||||
(this.options.collectAllErrors || this.options.fullTemplateTypeCheck) ? (err: any) => {
|
||||
this._structuralDiagnostics !.push({
|
||||
messageText: err.toString(),
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
source: SOURCE,
|
||||
code: DEFAULT_ERROR_CODE
|
||||
});
|
||||
} : undefined;
|
||||
this._compiler = createAotCompiler(this._hostAdapter, aotOptions, errorCollector).compiler;
|
||||
}
|
||||
|
||||
@ -516,26 +522,33 @@ class AngularCompilerProgram implements Program {
|
||||
this._hostAdapter.isSourceFile = () => false;
|
||||
this._tsProgram = ts.createProgram(this.rootNames, this.options, this.hostAdapter);
|
||||
if (isSyntaxError(e)) {
|
||||
this._addStructuralDiagnostics(e);
|
||||
const parserErrors = getParseErrors(e);
|
||||
if (parserErrors && parserErrors.length) {
|
||||
this._structuralDiagnostics = [
|
||||
...(this._structuralDiagnostics || []),
|
||||
...parserErrors.map<Diagnostic>(e => ({
|
||||
messageText: e.contextualMessage(),
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
span: e.span,
|
||||
source: SOURCE,
|
||||
code: DEFAULT_ERROR_CODE
|
||||
}))
|
||||
];
|
||||
} else {
|
||||
this._structuralDiagnostics = [
|
||||
...(this._structuralDiagnostics || []), {
|
||||
messageText: e.message,
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
source: SOURCE,
|
||||
code: DEFAULT_ERROR_CODE
|
||||
}
|
||||
];
|
||||
}
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
private _addStructuralDiagnostics(error: Error) {
|
||||
const diagnostics = this._structuralDiagnostics || (this._structuralDiagnostics = []);
|
||||
if (isSyntaxError(error)) {
|
||||
diagnostics.push(...syntaxErrorToDiagnostics(error));
|
||||
} else {
|
||||
diagnostics.push({
|
||||
messageText: error.toString(),
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
source: SOURCE,
|
||||
code: DEFAULT_ERROR_CODE
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Note: this returns a ts.Diagnostic so that we
|
||||
// can return errors in a ts.EmitResult
|
||||
private generateFilesForEmit(emitFlags: EmitFlags):
|
||||
@ -593,8 +606,7 @@ class AngularCompilerProgram implements Program {
|
||||
|
||||
private writeFile(
|
||||
outFileName: string, outData: string, writeByteOrderMark: boolean,
|
||||
onError?: (message: string) => void, genFile?: GeneratedFile,
|
||||
sourceFiles?: ReadonlyArray<ts.SourceFile>) {
|
||||
onError?: (message: string) => void, genFile?: GeneratedFile, sourceFiles?: ts.SourceFile[]) {
|
||||
// collect emittedLibrarySummaries
|
||||
let baseFile: ts.SourceFile|undefined;
|
||||
if (genFile) {
|
||||
@ -641,8 +653,7 @@ class AngularCompilerProgram implements Program {
|
||||
if (baseFile) {
|
||||
sourceFiles = sourceFiles ? [...sourceFiles, baseFile] : [baseFile];
|
||||
}
|
||||
// TODO: remove any when TS 2.4 support is removed.
|
||||
this.host.writeFile(outFileName, outData, writeByteOrderMark, onError, sourceFiles as any);
|
||||
this.host.writeFile(outFileName, outData, writeByteOrderMark, onError, sourceFiles);
|
||||
}
|
||||
}
|
||||
|
||||
@ -830,56 +841,3 @@ function mergeEmitResults(emitResults: ts.EmitResult[]): ts.EmitResult {
|
||||
}
|
||||
return {diagnostics, emitSkipped, emittedFiles};
|
||||
}
|
||||
|
||||
function diagnosticSourceOfSpan(span: ParseSourceSpan): ts.SourceFile {
|
||||
// For diagnostics, TypeScript only uses the fileName and text properties.
|
||||
// The redundant '()' are here is to avoid having clang-format breaking the line incorrectly.
|
||||
return ({ fileName: span.start.file.url, text: span.start.file.content } as any);
|
||||
}
|
||||
|
||||
function diagnosticSourceOfFileName(fileName: string, program: ts.Program): ts.SourceFile {
|
||||
const sourceFile = program.getSourceFile(fileName);
|
||||
if (sourceFile) return sourceFile;
|
||||
|
||||
// If we are reporting diagnostics for a source file that is not in the project then we need
|
||||
// to fake a source file so the diagnostic formatting routines can emit the file name.
|
||||
// The redundant '()' are here is to avoid having clang-format breaking the line incorrectly.
|
||||
return ({ fileName, text: '' } as any);
|
||||
}
|
||||
|
||||
|
||||
function diagnosticChainFromFormattedDiagnosticChain(chain: FormattedMessageChain):
|
||||
DiagnosticMessageChain {
|
||||
return {
|
||||
messageText: chain.message,
|
||||
next: chain.next && diagnosticChainFromFormattedDiagnosticChain(chain.next),
|
||||
position: chain.position
|
||||
};
|
||||
}
|
||||
|
||||
function syntaxErrorToDiagnostics(error: Error): Diagnostic[] {
|
||||
const parserErrors = getParseErrors(error);
|
||||
if (parserErrors && parserErrors.length) {
|
||||
return parserErrors.map<Diagnostic>(e => ({
|
||||
messageText: e.contextualMessage(),
|
||||
file: diagnosticSourceOfSpan(e.span),
|
||||
start: e.span.start.offset,
|
||||
length: e.span.end.offset - e.span.start.offset,
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
source: SOURCE,
|
||||
code: DEFAULT_ERROR_CODE
|
||||
}));
|
||||
} else {
|
||||
if (isFormattedError(error)) {
|
||||
return [{
|
||||
messageText: error.message,
|
||||
chain: error.chain && diagnosticChainFromFormattedDiagnosticChain(error.chain),
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
source: SOURCE,
|
||||
code: DEFAULT_ERROR_CODE,
|
||||
position: error.position
|
||||
}];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
@ -27,7 +27,7 @@ describe('metadata bundler', () => {
|
||||
|
||||
const originalOne = './src/one';
|
||||
const originalTwo = './src/two/index';
|
||||
expect(Object.keys(result.metadata.origins !)
|
||||
expect(Object.keys(result.metadata.origins)
|
||||
.sort()
|
||||
.map(name => ({name, value: result.metadata.origins ![name]})))
|
||||
.toEqual([
|
||||
|
@ -45,7 +45,6 @@ describe('Collector', () => {
|
||||
're-exports.ts',
|
||||
're-exports-2.ts',
|
||||
'export-as.d.ts',
|
||||
'named-module.d.ts',
|
||||
'static-field-reference.ts',
|
||||
'static-method.ts',
|
||||
'static-method-call.ts',
|
||||
@ -102,12 +101,6 @@ describe('Collector', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should preserve module names from TypeScript sources', () => {
|
||||
const sourceFile = program.getSourceFile('named-module.d.ts');
|
||||
const metadata = collector.getMetadata(sourceFile);
|
||||
expect(metadata !['importAs']).toEqual('some-named-module');
|
||||
});
|
||||
|
||||
it('should be able to collect a simple component\'s metadata', () => {
|
||||
const sourceFile = program.getSourceFile('app/hero-detail.component.ts');
|
||||
const metadata = collector.getMetadata(sourceFile);
|
||||
@ -119,13 +112,7 @@ describe('Collector', () => {
|
||||
__symbolic: 'class',
|
||||
decorators: [{
|
||||
__symbolic: 'call',
|
||||
expression: {
|
||||
__symbolic: 'reference',
|
||||
module: 'angular2/core',
|
||||
name: 'Component',
|
||||
line: 4,
|
||||
character: 7
|
||||
},
|
||||
expression: {__symbolic: 'reference', module: 'angular2/core', name: 'Component'},
|
||||
arguments: [{
|
||||
selector: 'my-hero-detail',
|
||||
template: `
|
||||
@ -145,13 +132,8 @@ describe('Collector', () => {
|
||||
__symbolic: 'property',
|
||||
decorators: [{
|
||||
__symbolic: 'call',
|
||||
expression: {
|
||||
__symbolic: 'reference',
|
||||
module: 'angular2/core',
|
||||
name: 'Input',
|
||||
line: 18,
|
||||
character: 9
|
||||
}
|
||||
expression:
|
||||
{__symbolic: 'reference', module: 'angular2/core', name: 'Input'}
|
||||
}]
|
||||
}]
|
||||
}
|
||||
@ -171,13 +153,7 @@ describe('Collector', () => {
|
||||
__symbolic: 'class',
|
||||
decorators: [{
|
||||
__symbolic: 'call',
|
||||
expression: {
|
||||
__symbolic: 'reference',
|
||||
module: 'angular2/core',
|
||||
name: 'Component',
|
||||
line: 9,
|
||||
character: 7
|
||||
},
|
||||
expression: {__symbolic: 'reference', module: 'angular2/core', name: 'Component'},
|
||||
arguments: [{
|
||||
selector: 'my-app',
|
||||
template: `
|
||||
@ -196,52 +172,20 @@ describe('Collector', () => {
|
||||
__symbolic: 'reference',
|
||||
module: './hero-detail.component',
|
||||
name: 'HeroDetailComponent',
|
||||
line: 22,
|
||||
character: 21
|
||||
},
|
||||
{
|
||||
__symbolic: 'reference',
|
||||
module: 'angular2/common',
|
||||
name: 'NgFor',
|
||||
line: 22,
|
||||
character: 42
|
||||
}
|
||||
{__symbolic: 'reference', module: 'angular2/common', name: 'NgFor'}
|
||||
],
|
||||
providers: [{
|
||||
__symbolic: 'reference',
|
||||
module: './hero.service',
|
||||
default: true,
|
||||
line: 23,
|
||||
character: 20
|
||||
}],
|
||||
providers: [{__symbolic: 'reference', module: './hero.service', default: true}],
|
||||
pipes: [
|
||||
{
|
||||
__symbolic: 'reference',
|
||||
module: 'angular2/common',
|
||||
name: 'LowerCasePipe',
|
||||
line: 24,
|
||||
character: 16
|
||||
},
|
||||
{
|
||||
__symbolic: 'reference',
|
||||
module: 'angular2/common',
|
||||
name: 'UpperCasePipe',
|
||||
line: 24,
|
||||
character: 38
|
||||
}
|
||||
{__symbolic: 'reference', module: 'angular2/common', name: 'LowerCasePipe'},
|
||||
{__symbolic: 'reference', module: 'angular2/common', name: 'UpperCasePipe'}
|
||||
]
|
||||
}]
|
||||
}],
|
||||
members: {
|
||||
__ctor__: [{
|
||||
__symbolic: 'constructor',
|
||||
parameters: [{
|
||||
__symbolic: 'reference',
|
||||
module: './hero.service',
|
||||
default: true,
|
||||
line: 31,
|
||||
character: 42
|
||||
}]
|
||||
parameters: [{__symbolic: 'reference', module: './hero.service', default: true}]
|
||||
}],
|
||||
onSelect: [{__symbolic: 'method'}],
|
||||
ngOnInit: [{__symbolic: 'method'}],
|
||||
@ -292,23 +236,22 @@ describe('Collector', () => {
|
||||
});
|
||||
|
||||
it('should record annotations on set and get declarations', () => {
|
||||
const propertyData = (line: number) => ({
|
||||
const propertyData = {
|
||||
name: [{
|
||||
__symbolic: 'property',
|
||||
decorators: [{
|
||||
__symbolic: 'call',
|
||||
expression:
|
||||
{__symbolic: 'reference', module: 'angular2/core', name: 'Input', line, character: 9},
|
||||
expression: {__symbolic: 'reference', module: 'angular2/core', name: 'Input'},
|
||||
arguments: ['firstName']
|
||||
}]
|
||||
}]
|
||||
});
|
||||
};
|
||||
const caseGetProp = <ClassMetadata>casesMetadata.metadata['GetProp'];
|
||||
expect(caseGetProp.members).toEqual(propertyData(11));
|
||||
expect(caseGetProp.members).toEqual(propertyData);
|
||||
const caseSetProp = <ClassMetadata>casesMetadata.metadata['SetProp'];
|
||||
expect(caseSetProp.members).toEqual(propertyData(19));
|
||||
expect(caseSetProp.members).toEqual(propertyData);
|
||||
const caseFullProp = <ClassMetadata>casesMetadata.metadata['FullProp'];
|
||||
expect(caseFullProp.members).toEqual(propertyData(27));
|
||||
expect(caseFullProp.members).toEqual(propertyData);
|
||||
});
|
||||
|
||||
it('should record references to parameterized types', () => {
|
||||
@ -317,13 +260,7 @@ describe('Collector', () => {
|
||||
__symbolic: 'class',
|
||||
decorators: [{
|
||||
__symbolic: 'call',
|
||||
expression: {
|
||||
__symbolic: 'reference',
|
||||
module: 'angular2/core',
|
||||
name: 'Injectable',
|
||||
line: 40,
|
||||
character: 7
|
||||
}
|
||||
expression: {__symbolic: 'reference', module: 'angular2/core', name: 'Injectable'}
|
||||
}],
|
||||
members: {
|
||||
__ctor__: [{
|
||||
@ -376,7 +313,7 @@ describe('Collector', () => {
|
||||
const ctor = <ConstructorMetadata>someClass.members !['__ctor__'][0];
|
||||
const parameters = ctor.parameters;
|
||||
expect(parameters).toEqual([
|
||||
{__symbolic: 'reference', module: 'angular2/common', name: 'NgFor', line: 6, character: 29}
|
||||
{__symbolic: 'reference', module: 'angular2/common', name: 'NgFor'}
|
||||
]);
|
||||
});
|
||||
|
||||
@ -461,7 +398,7 @@ describe('Collector', () => {
|
||||
const ctor = <ConstructorMetadata>someClass.members !['__ctor__'][0];
|
||||
const parameters = ctor.parameters;
|
||||
expect(parameters).toEqual([
|
||||
{__symbolic: 'reference', module: 'angular2/common', name: 'NgFor', line: 6, character: 29}
|
||||
{__symbolic: 'reference', module: 'angular2/common', name: 'NgFor'}
|
||||
]);
|
||||
});
|
||||
|
||||
@ -490,13 +427,7 @@ describe('Collector', () => {
|
||||
B: 1,
|
||||
C: 30,
|
||||
D: 40,
|
||||
E: {
|
||||
__symbolic: 'reference',
|
||||
module: './exported-consts',
|
||||
name: 'constValue',
|
||||
line: 5,
|
||||
character: 75
|
||||
}
|
||||
E: {__symbolic: 'reference', module: './exported-consts', name: 'constValue'}
|
||||
});
|
||||
});
|
||||
|
||||
@ -526,25 +457,13 @@ describe('Collector', () => {
|
||||
expect(classData).toBeDefined();
|
||||
expect(classData.decorators).toEqual([{
|
||||
__symbolic: 'call',
|
||||
expression: {
|
||||
__symbolic: 'reference',
|
||||
module: 'angular2/core',
|
||||
name: 'Component',
|
||||
line: 4,
|
||||
character: 5
|
||||
},
|
||||
expression: {__symbolic: 'reference', module: 'angular2/core', name: 'Component'},
|
||||
arguments: [{
|
||||
providers: {
|
||||
__symbolic: 'call',
|
||||
expression: {
|
||||
__symbolic: 'select',
|
||||
expression: {
|
||||
__symbolic: 'reference',
|
||||
module: './static-method',
|
||||
name: 'MyModule',
|
||||
line: 5,
|
||||
character: 17
|
||||
},
|
||||
expression: {__symbolic: 'reference', module: './static-method', name: 'MyModule'},
|
||||
member: 'with'
|
||||
},
|
||||
arguments: ['a']
|
||||
@ -570,25 +489,13 @@ describe('Collector', () => {
|
||||
expect(classData).toBeDefined();
|
||||
expect(classData.decorators).toEqual([{
|
||||
__symbolic: 'call',
|
||||
expression: {
|
||||
__symbolic: 'reference',
|
||||
module: 'angular2/core',
|
||||
name: 'Component',
|
||||
line: 4,
|
||||
character: 5
|
||||
},
|
||||
expression: {__symbolic: 'reference', module: 'angular2/core', name: 'Component'},
|
||||
arguments: [{
|
||||
providers: [{
|
||||
provide: 'a',
|
||||
useValue: {
|
||||
__symbolic: 'select',
|
||||
expression: {
|
||||
__symbolic: 'reference',
|
||||
module: './static-field',
|
||||
name: 'MyModule',
|
||||
line: 5,
|
||||
character: 45
|
||||
},
|
||||
expression: {__symbolic: 'reference', module: './static-field', name: 'MyModule'},
|
||||
member: 'VALUE'
|
||||
}
|
||||
}]
|
||||
@ -671,20 +578,8 @@ describe('Collector', () => {
|
||||
const metadata = collector.getMetadata(source) !;
|
||||
expect(metadata.metadata).toEqual({
|
||||
MyClass: Object({__symbolic: 'class'}),
|
||||
OtherModule: {
|
||||
__symbolic: 'reference',
|
||||
module: './static-field-reference',
|
||||
name: 'Foo',
|
||||
line: 4,
|
||||
character: 12
|
||||
},
|
||||
MyOtherModule: {
|
||||
__symbolic: 'reference',
|
||||
module: './static-field',
|
||||
name: 'MyModule',
|
||||
line: 4,
|
||||
character: 25
|
||||
}
|
||||
OtherModule: {__symbolic: 'reference', module: './static-field-reference', name: 'Foo'},
|
||||
MyOtherModule: {__symbolic: 'reference', module: './static-field', name: 'MyModule'}
|
||||
});
|
||||
});
|
||||
|
||||
@ -703,13 +598,7 @@ describe('Collector', () => {
|
||||
__symbolic: 'class',
|
||||
decorators: [{
|
||||
__symbolic: 'call',
|
||||
expression: {
|
||||
__symbolic: 'reference',
|
||||
module: 'angular2/core',
|
||||
name: 'Component',
|
||||
line: 11,
|
||||
character: 5
|
||||
},
|
||||
expression: {__symbolic: 'reference', module: 'angular2/core', name: 'Component'},
|
||||
arguments: [{providers: [{__symbolic: 'reference', name: 'REQUIRED_VALIDATOR'}]}]
|
||||
}]
|
||||
}
|
||||
@ -731,13 +620,7 @@ describe('Collector', () => {
|
||||
__symbolic: 'class',
|
||||
decorators: [{
|
||||
__symbolic: 'call',
|
||||
expression: {
|
||||
__symbolic: 'reference',
|
||||
module: 'angular2/core',
|
||||
name: 'Component',
|
||||
line: 11,
|
||||
character: 5
|
||||
},
|
||||
expression: {__symbolic: 'reference', module: 'angular2/core', name: 'Component'},
|
||||
arguments: [{providers: [{__symbolic: 'reference', name: 'REQUIRED_VALIDATOR'}]}]
|
||||
}]
|
||||
}
|
||||
@ -770,13 +653,7 @@ describe('Collector', () => {
|
||||
__symbolic: 'constructor',
|
||||
parameterDecorators: [[{
|
||||
__symbolic: 'call',
|
||||
expression: {
|
||||
__symbolic: 'reference',
|
||||
module: 'angular2/core',
|
||||
name: 'Inject',
|
||||
line: 6,
|
||||
character: 19
|
||||
},
|
||||
expression: {__symbolic: 'reference', module: 'angular2/core', name: 'Inject'},
|
||||
arguments: ['a']
|
||||
}]],
|
||||
parameters: [{__symbolic: 'reference', name: 'any'}]
|
||||
@ -810,20 +687,13 @@ describe('Collector', () => {
|
||||
__symbolic: 'reference',
|
||||
module: './external',
|
||||
name: 'external',
|
||||
line: 0,
|
||||
character: 68,
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should simplify a redundant template', () => {
|
||||
e('`${external}`', 'import {external} from "./external";').toEqual({
|
||||
__symbolic: 'reference',
|
||||
module: './external',
|
||||
name: 'external',
|
||||
line: 0,
|
||||
character: 59
|
||||
});
|
||||
e('`${external}`', 'import {external} from "./external";')
|
||||
.toEqual({__symbolic: 'reference', module: './external', name: 'external'});
|
||||
});
|
||||
|
||||
it('should be able to collect complex template with imported references', () => {
|
||||
@ -840,18 +710,11 @@ describe('Collector', () => {
|
||||
__symbolic: 'binop',
|
||||
operator: '+',
|
||||
left: 'foo:',
|
||||
right: {
|
||||
__symbolic: 'reference',
|
||||
module: './external',
|
||||
name: 'foo',
|
||||
line: 0,
|
||||
character: 63
|
||||
}
|
||||
right: {__symbolic: 'reference', module: './external', name: 'foo'}
|
||||
},
|
||||
right: ', bar:'
|
||||
},
|
||||
right:
|
||||
{__symbolic: 'reference', module: './external', name: 'bar', line: 0, character: 75}
|
||||
right: {__symbolic: 'reference', module: './external', name: 'bar'}
|
||||
},
|
||||
right: ', end'
|
||||
});
|
||||
@ -878,11 +741,11 @@ describe('Collector', () => {
|
||||
__ctor__: [{
|
||||
__symbolic: 'constructor',
|
||||
parameters: [
|
||||
{__symbolic: 'reference', module: './foo', name: 'Foo', line: 3, character: 24},
|
||||
{__symbolic: 'reference', module: './foo', name: 'Foo', line: 3, character: 24},
|
||||
{__symbolic: 'reference', module: './foo', name: 'Foo', line: 3, character: 24},
|
||||
{__symbolic: 'reference', module: './foo', name: 'Foo', line: 3, character: 24},
|
||||
{__symbolic: 'reference', module: './foo', name: 'Foo', line: 3, character: 24}
|
||||
{__symbolic: 'reference', module: './foo', name: 'Foo'},
|
||||
{__symbolic: 'reference', module: './foo', name: 'Foo'},
|
||||
{__symbolic: 'reference', module: './foo', name: 'Foo'},
|
||||
{__symbolic: 'reference', module: './foo', name: 'Foo'},
|
||||
{__symbolic: 'reference', module: './foo', name: 'Foo'}
|
||||
]
|
||||
}]
|
||||
});
|
||||
@ -962,9 +825,7 @@ describe('Collector', () => {
|
||||
extends: {
|
||||
__symbolic: 'reference',
|
||||
module: './class-inheritance-parent',
|
||||
name: 'ParentClassFromOtherFile',
|
||||
line: 9,
|
||||
character: 45,
|
||||
name: 'ParentClassFromOtherFile'
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -1523,10 +1384,6 @@ const FILES: Directory = {
|
||||
declare function someFunction(): void;
|
||||
export { someFunction as SomeFunction };
|
||||
`,
|
||||
'named-module.d.ts': `
|
||||
/// <amd-module name="some-named-module" />
|
||||
export type SomeType = 'a';
|
||||
`,
|
||||
'local-symbol-ref.ts': `
|
||||
import {Component, Validators} from 'angular2/core';
|
||||
|
||||
|
@ -149,14 +149,12 @@ describe('Evaluator', () => {
|
||||
const newExpression = program.getSourceFile('newExpression.ts');
|
||||
expect(evaluator.evaluateNode(findVarInitializer(newExpression, 'someValue'))).toEqual({
|
||||
__symbolic: 'new',
|
||||
expression:
|
||||
{__symbolic: 'reference', name: 'Value', module: './classes', line: 4, character: 33},
|
||||
expression: {__symbolic: 'reference', name: 'Value', module: './classes'},
|
||||
arguments: ['name', 12]
|
||||
});
|
||||
expect(evaluator.evaluateNode(findVarInitializer(newExpression, 'complex'))).toEqual({
|
||||
__symbolic: 'new',
|
||||
expression:
|
||||
{__symbolic: 'reference', name: 'Value', module: './classes', line: 5, character: 42},
|
||||
expression: {__symbolic: 'reference', name: 'Value', module: './classes'},
|
||||
arguments: ['name', 12]
|
||||
});
|
||||
});
|
||||
@ -175,7 +173,8 @@ describe('Evaluator', () => {
|
||||
const errors = program.getSourceFile('errors.ts');
|
||||
const fDecl = findVar(errors, 'f') !;
|
||||
expect(evaluator.evaluateNode(fDecl.initializer !))
|
||||
.toEqual({__symbolic: 'error', message: 'Lambda not supported', line: 1, character: 12});
|
||||
.toEqual(
|
||||
{__symbolic: 'error', message: 'Function call not supported', line: 1, character: 12});
|
||||
const eDecl = findVar(errors, 'e') !;
|
||||
expect(evaluator.evaluateNode(eDecl.type !)).toEqual({
|
||||
__symbolic: 'error',
|
||||
|
@ -102,7 +102,6 @@ export class MockNode implements ts.Node {
|
||||
|
||||
export class MockIdentifier extends MockNode implements ts.Identifier {
|
||||
public text: string;
|
||||
public escapedText: ts.__String;
|
||||
// tslint:disable
|
||||
public _primaryExpressionBrand: any;
|
||||
public _memberExpressionBrand: any;
|
||||
@ -138,14 +137,12 @@ export class MockVariableDeclaration extends MockNode implements ts.VariableDecl
|
||||
}
|
||||
|
||||
export class MockSymbol implements ts.Symbol {
|
||||
public escapedName: ts.__String;
|
||||
constructor(
|
||||
public name: string, private node: ts.Declaration = MockVariableDeclaration.of(name),
|
||||
public flags: ts.SymbolFlags = 0) {}
|
||||
|
||||
getFlags(): ts.SymbolFlags { return this.flags; }
|
||||
getName(): string { return this.name; }
|
||||
getEscapedName(): ts.__String { return this.escapedName; }
|
||||
getDeclarations(): ts.Declaration[] { return [this.node]; }
|
||||
getDocumentationComment(): ts.SymbolDisplayPart[] { return []; }
|
||||
// TODO(vicb): removed in TS 2.2
|
||||
|
@ -184,7 +184,8 @@ describe('ngc transformer command-line', () => {
|
||||
|
||||
const exitCode = main(['-p', basePath], errorSpy);
|
||||
expect(errorSpy).toHaveBeenCalledTimes(1);
|
||||
expect(errorSpy.calls.mostRecent().args[0]).toContain('mymodule.ts.MyComp.html');
|
||||
expect(errorSpy.calls.mostRecent().args[0])
|
||||
.toContain('Error at ' + path.join(basePath, 'mymodule.ts.MyComp.html'));
|
||||
expect(errorSpy.calls.mostRecent().args[0])
|
||||
.toContain(`Property 'unknownProp' does not exist on type 'MyComp'`);
|
||||
|
||||
@ -214,7 +215,8 @@ describe('ngc transformer command-line', () => {
|
||||
|
||||
const exitCode = main(['-p', basePath], errorSpy);
|
||||
expect(errorSpy).toHaveBeenCalledTimes(1);
|
||||
expect(errorSpy.calls.mostRecent().args[0]).toContain('my.component.html(1,5):');
|
||||
expect(errorSpy.calls.mostRecent().args[0])
|
||||
.toContain('Error at ' + path.join(basePath, 'my.component.html(1,5):'));
|
||||
expect(errorSpy.calls.mostRecent().args[0])
|
||||
.toContain(`Property 'unknownProp' does not exist on type 'MyComp'`);
|
||||
|
||||
@ -1564,49 +1566,4 @@ describe('ngc transformer command-line', () => {
|
||||
expect(main(['-p', path.join(basePath, 'src/tsconfig.json')])).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatted messages', () => {
|
||||
it('should emit a formatted error message for a structural error', () => {
|
||||
write('src/tsconfig.json', `{
|
||||
"extends": "../tsconfig-base.json",
|
||||
"files": ["test-module.ts"]
|
||||
}`);
|
||||
write('src/lib/indirect2.ts', `
|
||||
declare var f: any;
|
||||
|
||||
export const t2 = f\`<p>hello</p>\`;
|
||||
`);
|
||||
write('src/lib/indirect1.ts', `
|
||||
import {t2} from './indirect2';
|
||||
export const t1 = t2 + ' ';
|
||||
`);
|
||||
write('src/lib/test.component.ts', `
|
||||
import {Component} from '@angular/core';
|
||||
import {t1} from './indirect1';
|
||||
|
||||
@Component({
|
||||
template: t1,
|
||||
styleUrls: ['./test.component.css']
|
||||
})
|
||||
export class TestComponent {}
|
||||
`);
|
||||
write('src/test-module.ts', `
|
||||
import {NgModule} from '@angular/core';
|
||||
import {TestComponent} from './lib/test.component';
|
||||
|
||||
@NgModule({declarations: [TestComponent]})
|
||||
export class TestModule {}
|
||||
`);
|
||||
const messages: string[] = [];
|
||||
const exitCode =
|
||||
main(['-p', path.join(basePath, 'src/tsconfig.json')], message => messages.push(message));
|
||||
expect(exitCode).toBe(1, 'Compile was expected to fail');
|
||||
expect(messages[0])
|
||||
.toEqual(`lib/test.component.ts(6,21): Error during template compile of 'TestComponent'
|
||||
Tagged template expressions are not supported in metadata in 't1'
|
||||
't1' references 't2' at lib/indirect1.ts(3,27)
|
||||
't2' contains the error at lib/indirect2.ts(4,27).
|
||||
`);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@ -119,7 +119,7 @@ describe('perform watch', () => {
|
||||
const errorFileContent = `
|
||||
import {NgModule} from '@angular/core';
|
||||
|
||||
@NgModule((() => (1===1 ? null as any : null as any)) as any)
|
||||
@NgModule(() => (1===1 ? null as any : null as any))
|
||||
export class MyModule {}
|
||||
`;
|
||||
const indexTsPath = path.resolve(testSupport.basePath, 'src', 'index.ts');
|
||||
@ -143,7 +143,7 @@ describe('perform watch', () => {
|
||||
|
||||
const errDiags = host.diagnostics.filter(d => d.category === ts.DiagnosticCategory.Error);
|
||||
expect(errDiags.length).toBe(1);
|
||||
expect(errDiags[0].messageText).toContain('Function expressions are not supported');
|
||||
expect(errDiags[0].messageText).toContain('Function calls are not supported.');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
@ -325,7 +325,7 @@ describe('ng program', () => {
|
||||
'src/main.ts': `
|
||||
import {NgModule} from '@angular/core';
|
||||
|
||||
@NgModule((() => {if (1==1) return null as any;}) as any)
|
||||
@NgModule(() => {if (1==1) return null as any;})
|
||||
export class SomeClassWithInvalidMetadata {}
|
||||
`,
|
||||
});
|
||||
@ -930,7 +930,7 @@ describe('ng program', () => {
|
||||
|
||||
const structuralErrors = program.getNgStructuralDiagnostics();
|
||||
expect(structuralErrors.length).toBe(1);
|
||||
expect(structuralErrors[0].messageText).toContain('Function expressions are not supported');
|
||||
expect(structuralErrors[0].messageText).toContain('Function calls are not supported.');
|
||||
});
|
||||
|
||||
it('should not throw on structural errors but collect them (loadNgStructureAsync)', (done) => {
|
||||
@ -943,7 +943,7 @@ describe('ng program', () => {
|
||||
program.loadNgStructureAsync().then(() => {
|
||||
const structuralErrors = program.getNgStructuralDiagnostics();
|
||||
expect(structuralErrors.length).toBe(1);
|
||||
expect(structuralErrors[0].messageText).toContain('Function expressions are not supported');
|
||||
expect(structuralErrors[0].messageText).toContain('Function calls are not supported.');
|
||||
done();
|
||||
});
|
||||
});
|
||||
@ -982,8 +982,7 @@ describe('ng program', () => {
|
||||
const program = ng.createProgram({rootNames: allRootNames, options, host});
|
||||
const structuralErrors = program.getNgStructuralDiagnostics();
|
||||
expect(structuralErrors.length).toBe(1);
|
||||
expect(structuralErrors[0].messageText)
|
||||
.toContain('Function expressions are not supported');
|
||||
expect(structuralErrors[0].messageText).toContain('Function calls are not supported.');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@ -1,60 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {syntaxError} from '../util';
|
||||
|
||||
export interface Position {
|
||||
fileName: string;
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
|
||||
export interface FormattedMessageChain {
|
||||
message: string;
|
||||
position?: Position;
|
||||
next?: FormattedMessageChain;
|
||||
}
|
||||
|
||||
export type FormattedError = Error & {
|
||||
chain: FormattedMessageChain;
|
||||
position?: Position;
|
||||
};
|
||||
|
||||
const FORMATTED_MESSAGE = 'ngFormattedMessage';
|
||||
|
||||
function indentStr(level: number): string {
|
||||
if (level <= 0) return '';
|
||||
if (level < 6) return ['', ' ', ' ', ' ', ' ', ' '][level];
|
||||
const half = indentStr(Math.floor(level / 2));
|
||||
return half + half + (level % 2 === 1 ? ' ' : '');
|
||||
}
|
||||
|
||||
function formatChain(chain: FormattedMessageChain | undefined, indent: number = 0): string {
|
||||
if (!chain) return '';
|
||||
const position = chain.position ?
|
||||
`${chain.position.fileName}(${chain.position.line+1},${chain.position.column+1})` :
|
||||
'';
|
||||
const prefix = position && indent === 0 ? `${position}: ` : '';
|
||||
const postfix = position && indent !== 0 ? ` at ${position}` : '';
|
||||
const message = `${prefix}${chain.message}${postfix}`;
|
||||
|
||||
return `${indentStr(indent)}${message}${(chain.next && ('\n' + formatChain(chain.next, indent + 2))) || ''}`;
|
||||
}
|
||||
|
||||
export function formattedError(chain: FormattedMessageChain): FormattedError {
|
||||
const message = formatChain(chain) + '.';
|
||||
const error = syntaxError(message) as FormattedError;
|
||||
(error as any)[FORMATTED_MESSAGE] = true;
|
||||
error.chain = chain;
|
||||
error.position = chain.position;
|
||||
return error;
|
||||
}
|
||||
|
||||
export function isFormattedError(error: Error): error is FormattedError {
|
||||
return !!(error as any)[FORMATTED_MESSAGE];
|
||||
}
|
@ -13,7 +13,6 @@ import * as o from '../output/output_ast';
|
||||
import {SummaryResolver} from '../summary_resolver';
|
||||
import {syntaxError} from '../util';
|
||||
|
||||
import {FormattedMessageChain, formattedError} from './formatted_error';
|
||||
import {StaticSymbol} from './static_symbol';
|
||||
import {StaticSymbolResolver} from './static_symbol_resolver';
|
||||
|
||||
@ -99,16 +98,11 @@ export class StaticReflector implements CompileReflector {
|
||||
|
||||
findSymbolDeclaration(symbol: StaticSymbol): StaticSymbol {
|
||||
const resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
|
||||
if (resolvedSymbol) {
|
||||
let resolvedMetadata = resolvedSymbol.metadata;
|
||||
if (resolvedMetadata && resolvedMetadata.__symbolic === 'resolved') {
|
||||
resolvedMetadata = resolvedMetadata.symbol;
|
||||
}
|
||||
if (resolvedMetadata instanceof StaticSymbol) {
|
||||
return this.findSymbolDeclaration(resolvedSymbol.metadata);
|
||||
}
|
||||
if (resolvedSymbol && resolvedSymbol.metadata instanceof StaticSymbol) {
|
||||
return this.findSymbolDeclaration(resolvedSymbol.metadata);
|
||||
} else {
|
||||
return symbol;
|
||||
}
|
||||
return symbol;
|
||||
}
|
||||
|
||||
public annotations(type: StaticSymbol): any[] {
|
||||
@ -136,12 +130,9 @@ export class StaticReflector implements CompileReflector {
|
||||
(requiredType) => ownAnnotations.some(ann => requiredType.isTypeOf(ann)));
|
||||
if (!typeHasRequiredAnnotation) {
|
||||
this.reportError(
|
||||
formatMetadataError(
|
||||
metadataError(
|
||||
`Class ${type.name} in ${type.filePath} extends from a ${CompileSummaryKind[summary.type.summaryKind!]} in another compilation unit without duplicating the decorator`,
|
||||
/* summary */ undefined,
|
||||
`Please add a ${requiredAnnotationTypes.map((type) => type.ngMetadataName).join(' or ')} decorator to the class`),
|
||||
type),
|
||||
syntaxError(
|
||||
`Class ${type.name} in ${type.filePath} extends from a ${CompileSummaryKind[summary.type.summaryKind!]} in another compilation unit without duplicating the decorator. ` +
|
||||
`Please add a ${requiredAnnotationTypes.map((type) => type.ngMetadataName).join(' or ')} decorator to the class.`),
|
||||
type);
|
||||
}
|
||||
}
|
||||
@ -343,6 +334,14 @@ export class StaticReflector implements CompileReflector {
|
||||
return this.symbolResolver.getStaticSymbol(declarationFile, name, members);
|
||||
}
|
||||
|
||||
private reportError(error: Error, context: StaticSymbol, path?: string) {
|
||||
if (this.errorRecorder) {
|
||||
this.errorRecorder(error, (context && context.filePath) || path);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simplify but discard any errors
|
||||
*/
|
||||
@ -359,7 +358,6 @@ export class StaticReflector implements CompileReflector {
|
||||
const self = this;
|
||||
let scope = BindingScope.empty;
|
||||
const calling = new Map<StaticSymbol, boolean>();
|
||||
const rootContext = context;
|
||||
|
||||
function simplifyInContext(
|
||||
context: StaticSymbol, value: any, depth: number, references: number): any {
|
||||
@ -368,64 +366,17 @@ export class StaticReflector implements CompileReflector {
|
||||
return resolvedSymbol ? resolvedSymbol.metadata : null;
|
||||
}
|
||||
|
||||
function simplifyEagerly(value: any): any {
|
||||
return simplifyInContext(context, value, depth, 0);
|
||||
}
|
||||
|
||||
function simplifyLazily(value: any): any {
|
||||
return simplifyInContext(context, value, depth, references + 1);
|
||||
}
|
||||
|
||||
function simplifyNested(nestedContext: StaticSymbol, value: any): any {
|
||||
if (nestedContext === context) {
|
||||
// If the context hasn't changed let the exception propagate unmodified.
|
||||
return simplifyInContext(nestedContext, value, depth + 1, references);
|
||||
}
|
||||
try {
|
||||
return simplifyInContext(nestedContext, value, depth + 1, references);
|
||||
} catch (e) {
|
||||
if (isMetadataError(e)) {
|
||||
// Propagate the message text up but add a message to the chain that explains how we got
|
||||
// here.
|
||||
// e.chain implies e.symbol
|
||||
const summaryMsg = e.chain ? 'references \'' + e.symbol !.name + '\'' : errorSummary(e);
|
||||
const summary = `'${nestedContext.name}' ${summaryMsg}`;
|
||||
const chain = {message: summary, position: e.position, next: e.chain};
|
||||
// TODO(chuckj): retrieve the position information indirectly from the collectors node
|
||||
// map if the metadata is from a .ts file.
|
||||
self.error(
|
||||
{
|
||||
message: e.message,
|
||||
advise: e.advise,
|
||||
context: e.context, chain,
|
||||
symbol: nestedContext
|
||||
},
|
||||
context);
|
||||
} else {
|
||||
// It is probably an internal error.
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function simplifyCall(
|
||||
functionSymbol: StaticSymbol, targetFunction: any, args: any[], targetExpression: any) {
|
||||
function simplifyCall(functionSymbol: StaticSymbol, targetFunction: any, args: any[]) {
|
||||
if (targetFunction && targetFunction['__symbolic'] == 'function') {
|
||||
if (calling.get(functionSymbol)) {
|
||||
self.error(
|
||||
{
|
||||
message: 'Recursion is not supported',
|
||||
summary: `called '${functionSymbol.name}' recursively`,
|
||||
value: targetFunction
|
||||
},
|
||||
functionSymbol);
|
||||
throw new Error('Recursion not supported');
|
||||
}
|
||||
try {
|
||||
const value = targetFunction['value'];
|
||||
if (value && (depth != 0 || value.__symbolic != 'error')) {
|
||||
const parameters: string[] = targetFunction['parameters'];
|
||||
const defaults: any[] = targetFunction.defaults;
|
||||
args = args.map(arg => simplifyNested(context, arg))
|
||||
args = args.map(arg => simplifyInContext(context, arg, depth + 1, references))
|
||||
.map(arg => shouldIgnore(arg) ? undefined : arg);
|
||||
if (defaults && defaults.length > args.length) {
|
||||
args.push(...defaults.slice(args.length).map((value: any) => simplify(value)));
|
||||
@ -439,7 +390,7 @@ export class StaticReflector implements CompileReflector {
|
||||
let result: any;
|
||||
try {
|
||||
scope = functionScope.done();
|
||||
result = simplifyNested(functionSymbol, value);
|
||||
result = simplifyInContext(functionSymbol, value, depth + 1, references);
|
||||
} finally {
|
||||
scope = oldScope;
|
||||
}
|
||||
@ -456,22 +407,8 @@ export class StaticReflector implements CompileReflector {
|
||||
// non-angular decorator, and we should just ignore it.
|
||||
return IGNORE;
|
||||
}
|
||||
let position: Position|undefined = undefined;
|
||||
if (targetExpression && targetExpression.__symbolic == 'resolved') {
|
||||
const line = targetExpression.line;
|
||||
const character = targetExpression.character;
|
||||
const fileName = targetExpression.fileName;
|
||||
if (fileName != null && line != null && character != null) {
|
||||
position = {fileName, line, column: character};
|
||||
}
|
||||
}
|
||||
self.error(
|
||||
{
|
||||
message: FUNCTION_CALL_NOT_SUPPORTED,
|
||||
context: functionSymbol,
|
||||
value: targetFunction, position
|
||||
},
|
||||
context);
|
||||
return simplify(
|
||||
{__symbolic: 'error', message: 'Function call not supported', context: functionSymbol});
|
||||
}
|
||||
|
||||
function simplify(expression: any): any {
|
||||
@ -485,7 +422,7 @@ export class StaticReflector implements CompileReflector {
|
||||
if (item && item.__symbolic === 'spread') {
|
||||
// We call with references as 0 because we require the actual value and cannot
|
||||
// tolerate a reference here.
|
||||
const spreadArray = simplifyEagerly(item.expression);
|
||||
const spreadArray = simplifyInContext(context, item.expression, depth, 0);
|
||||
if (Array.isArray(spreadArray)) {
|
||||
for (const spreadItem of spreadArray) {
|
||||
result.push(spreadItem);
|
||||
@ -511,7 +448,7 @@ export class StaticReflector implements CompileReflector {
|
||||
const staticSymbol = expression;
|
||||
const declarationValue = resolveReferenceValue(staticSymbol);
|
||||
if (declarationValue != null) {
|
||||
return simplifyNested(staticSymbol, declarationValue);
|
||||
return simplifyInContext(staticSymbol, declarationValue, depth + 1, references);
|
||||
} else {
|
||||
return staticSymbol;
|
||||
}
|
||||
@ -588,8 +525,8 @@ export class StaticReflector implements CompileReflector {
|
||||
}
|
||||
return null;
|
||||
case 'index':
|
||||
let indexTarget = simplifyEagerly(expression['expression']);
|
||||
let index = simplifyEagerly(expression['index']);
|
||||
let indexTarget = simplifyInContext(context, expression['expression'], depth, 0);
|
||||
let index = simplifyInContext(context, expression['index'], depth, 0);
|
||||
if (indexTarget && isPrimitive(index)) return indexTarget[index];
|
||||
return null;
|
||||
case 'select':
|
||||
@ -602,41 +539,26 @@ export class StaticReflector implements CompileReflector {
|
||||
self.getStaticSymbol(selectTarget.filePath, selectTarget.name, members);
|
||||
const declarationValue = resolveReferenceValue(selectContext);
|
||||
if (declarationValue != null) {
|
||||
return simplifyNested(selectContext, declarationValue);
|
||||
return simplifyInContext(
|
||||
selectContext, declarationValue, depth + 1, references);
|
||||
} else {
|
||||
return selectContext;
|
||||
}
|
||||
}
|
||||
if (selectTarget && isPrimitive(member))
|
||||
return simplifyNested(selectContext, selectTarget[member]);
|
||||
return simplifyInContext(
|
||||
selectContext, selectTarget[member], depth + 1, references);
|
||||
return null;
|
||||
case 'reference':
|
||||
// Note: This only has to deal with variable references, as symbol references have
|
||||
// been converted into 'resolved'
|
||||
// in the StaticSymbolResolver.
|
||||
// Note: This only has to deal with variable references,
|
||||
// as symbol references have been converted into StaticSymbols already
|
||||
// in the StaticSymbolResolver!
|
||||
const name: string = expression['name'];
|
||||
const localValue = scope.resolve(name);
|
||||
if (localValue != BindingScope.missing) {
|
||||
return localValue;
|
||||
}
|
||||
break;
|
||||
case 'resolved':
|
||||
try {
|
||||
return simplify(expression.symbol);
|
||||
} catch (e) {
|
||||
// If an error is reported evaluating the symbol record the position of the
|
||||
// reference in the error so it can
|
||||
// be reported in the error message generated from the exception.
|
||||
if (isMetadataError(e) && expression.fileName != null &&
|
||||
expression.line != null && expression.character != null) {
|
||||
e.position = {
|
||||
fileName: expression.fileName,
|
||||
line: expression.line,
|
||||
column: expression.character
|
||||
};
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
case 'class':
|
||||
return context;
|
||||
case 'function':
|
||||
@ -658,34 +580,29 @@ export class StaticReflector implements CompileReflector {
|
||||
const argExpressions: any[] = expression['arguments'] || [];
|
||||
let converter = self.conversionMap.get(staticSymbol);
|
||||
if (converter) {
|
||||
const args = argExpressions.map(arg => simplifyNested(context, arg))
|
||||
.map(arg => shouldIgnore(arg) ? undefined : arg);
|
||||
const args =
|
||||
argExpressions
|
||||
.map(arg => simplifyInContext(context, arg, depth + 1, references))
|
||||
.map(arg => shouldIgnore(arg) ? undefined : arg);
|
||||
return converter(context, args);
|
||||
} else {
|
||||
// Determine if the function is one we can simplify.
|
||||
const targetFunction = resolveReferenceValue(staticSymbol);
|
||||
return simplifyCall(
|
||||
staticSymbol, targetFunction, argExpressions, expression['expression']);
|
||||
return simplifyCall(staticSymbol, targetFunction, argExpressions);
|
||||
}
|
||||
}
|
||||
return IGNORE;
|
||||
case 'error':
|
||||
let message = expression.message;
|
||||
if (expression['line'] != null) {
|
||||
self.error(
|
||||
{
|
||||
message,
|
||||
context: expression.context,
|
||||
value: expression,
|
||||
position: {
|
||||
fileName: expression['fileName'],
|
||||
line: expression['line'],
|
||||
column: expression['character']
|
||||
}
|
||||
},
|
||||
let message = produceErrorMessage(expression);
|
||||
if (expression['line']) {
|
||||
message =
|
||||
`${message} (position ${expression['line']+1}:${expression['character']+1} in the original .ts file)`;
|
||||
self.reportError(
|
||||
positionalError(
|
||||
message, context.filePath, expression['line'], expression['character']),
|
||||
context);
|
||||
} else {
|
||||
self.error({message, context: expression.context}, context);
|
||||
self.reportError(new Error(message), context);
|
||||
}
|
||||
return IGNORE;
|
||||
case 'ignore':
|
||||
@ -703,7 +620,7 @@ export class StaticReflector implements CompileReflector {
|
||||
return simplify(value);
|
||||
}
|
||||
}
|
||||
return simplifyLazily(value);
|
||||
return simplifyInContext(context, value, depth, references + 1);
|
||||
}
|
||||
return simplify(value);
|
||||
});
|
||||
@ -711,19 +628,29 @@ export class StaticReflector implements CompileReflector {
|
||||
return IGNORE;
|
||||
}
|
||||
|
||||
return simplify(value);
|
||||
}
|
||||
|
||||
let result: any;
|
||||
try {
|
||||
result = simplifyInContext(context, value, 0, 0);
|
||||
} catch (e) {
|
||||
if (this.errorRecorder) {
|
||||
this.reportError(e, context);
|
||||
} else {
|
||||
throw formatMetadataError(e, context);
|
||||
try {
|
||||
return simplify(value);
|
||||
} catch (e) {
|
||||
const members = context.members.length ? `.${context.members.join('.')}` : '';
|
||||
const message =
|
||||
`${e.message}, resolving symbol ${context.name}${members} in ${context.filePath}`;
|
||||
if (e.fileName) {
|
||||
throw positionalError(message, e.fileName, e.line, e.column);
|
||||
}
|
||||
throw syntaxError(message);
|
||||
}
|
||||
}
|
||||
|
||||
const recordedSimplifyInContext = (context: StaticSymbol, value: any) => {
|
||||
try {
|
||||
return simplifyInContext(context, value, 0, 0);
|
||||
} catch (e) {
|
||||
this.reportError(e, context);
|
||||
}
|
||||
};
|
||||
|
||||
const result = this.errorRecorder ? recordedSimplifyInContext(context, value) :
|
||||
simplifyInContext(context, value, 0, 0);
|
||||
if (shouldIgnore(result)) {
|
||||
return undefined;
|
||||
}
|
||||
@ -735,166 +662,40 @@ export class StaticReflector implements CompileReflector {
|
||||
return resolvedSymbol && resolvedSymbol.metadata ? resolvedSymbol.metadata :
|
||||
{__symbolic: 'class'};
|
||||
}
|
||||
|
||||
private reportError(error: Error, context: StaticSymbol, path?: string) {
|
||||
if (this.errorRecorder) {
|
||||
this.errorRecorder(
|
||||
formatMetadataError(error, context), (context && context.filePath) || path);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private error(
|
||||
{message, summary, advise, position, context, value, symbol, chain}: {
|
||||
message: string,
|
||||
summary?: string,
|
||||
advise?: string,
|
||||
position?: Position,
|
||||
context?: any,
|
||||
value?: any,
|
||||
symbol?: StaticSymbol,
|
||||
chain?: MetadataMessageChain
|
||||
},
|
||||
reportingContext: StaticSymbol) {
|
||||
this.reportError(
|
||||
metadataError(message, summary, advise, position, symbol, context, chain),
|
||||
reportingContext);
|
||||
}
|
||||
}
|
||||
|
||||
interface Position {
|
||||
fileName: string;
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
|
||||
interface MetadataMessageChain {
|
||||
message: string;
|
||||
summary?: string;
|
||||
position?: Position;
|
||||
context?: any;
|
||||
symbol?: StaticSymbol;
|
||||
next?: MetadataMessageChain;
|
||||
}
|
||||
|
||||
type MetadataError = Error & {
|
||||
position?: Position;
|
||||
advise?: string;
|
||||
summary?: string;
|
||||
context?: any;
|
||||
symbol?: StaticSymbol;
|
||||
chain?: MetadataMessageChain;
|
||||
};
|
||||
|
||||
const METADATA_ERROR = 'ngMetadataError';
|
||||
|
||||
function metadataError(
|
||||
message: string, summary?: string, advise?: string, position?: Position, symbol?: StaticSymbol,
|
||||
context?: any, chain?: MetadataMessageChain): MetadataError {
|
||||
const error = syntaxError(message) as MetadataError;
|
||||
(error as any)[METADATA_ERROR] = true;
|
||||
if (advise) error.advise = advise;
|
||||
if (position) error.position = position;
|
||||
if (summary) error.summary = summary;
|
||||
if (context) error.context = context;
|
||||
if (chain) error.chain = chain;
|
||||
if (symbol) error.symbol = symbol;
|
||||
return error;
|
||||
}
|
||||
|
||||
function isMetadataError(error: Error): error is MetadataError {
|
||||
return !!(error as any)[METADATA_ERROR];
|
||||
}
|
||||
|
||||
const REFERENCE_TO_NONEXPORTED_CLASS = 'Reference to non-exported class';
|
||||
const VARIABLE_NOT_INITIALIZED = 'Variable not initialized';
|
||||
const DESTRUCTURE_NOT_SUPPORTED = 'Destructuring not supported';
|
||||
const COULD_NOT_RESOLVE_TYPE = 'Could not resolve type';
|
||||
const FUNCTION_CALL_NOT_SUPPORTED = 'Function call not supported';
|
||||
const REFERENCE_TO_LOCAL_SYMBOL = 'Reference to a local symbol';
|
||||
const LAMBDA_NOT_SUPPORTED = 'Lambda not supported';
|
||||
|
||||
function expandedMessage(message: string, context: any): string {
|
||||
switch (message) {
|
||||
case REFERENCE_TO_NONEXPORTED_CLASS:
|
||||
if (context && context.className) {
|
||||
return `References to a non-exported class are not supported in decorators but ${context.className} was referenced.`;
|
||||
}
|
||||
break;
|
||||
case VARIABLE_NOT_INITIALIZED:
|
||||
return 'Only initialized variables and constants can be referenced in decorators because the value of this variable is needed by the template compiler';
|
||||
case DESTRUCTURE_NOT_SUPPORTED:
|
||||
return 'Referencing an exported destructured variable or constant is not supported in decorators and this value is needed by the template compiler';
|
||||
case COULD_NOT_RESOLVE_TYPE:
|
||||
if (context && context.typeName) {
|
||||
return `Could not resolve type ${context.typeName}`;
|
||||
}
|
||||
break;
|
||||
case FUNCTION_CALL_NOT_SUPPORTED:
|
||||
if (context && context.name) {
|
||||
return `Function calls are not supported in decorators but '${context.name}' was called`;
|
||||
}
|
||||
return 'Function calls are not supported in decorators';
|
||||
case REFERENCE_TO_LOCAL_SYMBOL:
|
||||
if (context && context.name) {
|
||||
return `Reference to a local (non-exported) symbols are not supported in decorators but '${context.name}' was referenced`;
|
||||
}
|
||||
break;
|
||||
case LAMBDA_NOT_SUPPORTED:
|
||||
return `Function expressions are not supported in decorators`;
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
function messageAdvise(message: string, context: any): string|undefined {
|
||||
switch (message) {
|
||||
case REFERENCE_TO_NONEXPORTED_CLASS:
|
||||
if (context && context.className) {
|
||||
return `Consider exporting '${context.className}'`;
|
||||
}
|
||||
break;
|
||||
case DESTRUCTURE_NOT_SUPPORTED:
|
||||
return 'Consider simplifying to avoid destructuring';
|
||||
case REFERENCE_TO_LOCAL_SYMBOL:
|
||||
if (context && context.name) {
|
||||
return `Consider exporting '${context.name}'`;
|
||||
}
|
||||
break;
|
||||
case LAMBDA_NOT_SUPPORTED:
|
||||
return `Consider changing the function expression into an exported function`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function errorSummary(error: MetadataError): string {
|
||||
if (error.summary) {
|
||||
return error.summary;
|
||||
}
|
||||
function expandedMessage(error: any): string {
|
||||
switch (error.message) {
|
||||
case REFERENCE_TO_NONEXPORTED_CLASS:
|
||||
case 'Reference to non-exported class':
|
||||
if (error.context && error.context.className) {
|
||||
return `references non-exported class ${error.context.className}`;
|
||||
return `Reference to a non-exported class ${error.context.className}. Consider exporting the class`;
|
||||
}
|
||||
break;
|
||||
case VARIABLE_NOT_INITIALIZED:
|
||||
return 'is not initialized';
|
||||
case DESTRUCTURE_NOT_SUPPORTED:
|
||||
return 'is a destructured variable';
|
||||
case COULD_NOT_RESOLVE_TYPE:
|
||||
return 'could not be resolved';
|
||||
case FUNCTION_CALL_NOT_SUPPORTED:
|
||||
if (error.context && error.context.name) {
|
||||
return `calls '${error.context.name}'`;
|
||||
case 'Variable not initialized':
|
||||
return 'Only initialized variables and constants can be referenced because the value of this variable is needed by the template compiler';
|
||||
case 'Destructuring not supported':
|
||||
return 'Referencing an exported destructured variable or constant is not supported by the template compiler. Consider simplifying this to avoid destructuring';
|
||||
case 'Could not resolve type':
|
||||
if (error.context && error.context.typeName) {
|
||||
return `Could not resolve type ${error.context.typeName}`;
|
||||
}
|
||||
return `calls a function`;
|
||||
case REFERENCE_TO_LOCAL_SYMBOL:
|
||||
break;
|
||||
case 'Function call not supported':
|
||||
let prefix =
|
||||
error.context && error.context.name ? `Calling function '${error.context.name}', f` : 'F';
|
||||
return prefix +
|
||||
'unction calls are not supported. Consider replacing the function or lambda with a reference to an exported function';
|
||||
case 'Reference to a local symbol':
|
||||
if (error.context && error.context.name) {
|
||||
return `references local variable ${error.context.name}`;
|
||||
return `Reference to a local (non-exported) symbol '${error.context.name}'. Consider exporting the symbol`;
|
||||
}
|
||||
return `references a local variable`;
|
||||
break;
|
||||
}
|
||||
return 'contains the error';
|
||||
return error.message;
|
||||
}
|
||||
|
||||
function produceErrorMessage(error: any): string {
|
||||
return `Error encountered resolving symbol values statically. ${expandedMessage(error)}`;
|
||||
}
|
||||
|
||||
function mapStringMap(input: {[key: string]: any}, transform: (value: any, key: string) => any):
|
||||
@ -950,30 +751,10 @@ class PopulatedScope extends BindingScope {
|
||||
}
|
||||
}
|
||||
|
||||
function formatMetadataMessageChain(
|
||||
chain: MetadataMessageChain, advise: string | undefined): FormattedMessageChain {
|
||||
const expanded = expandedMessage(chain.message, chain.context);
|
||||
const nesting = chain.symbol ? ` in '${chain.symbol.name}'` : '';
|
||||
const message = `${expanded}${nesting}`;
|
||||
const position = chain.position;
|
||||
const next: FormattedMessageChain|undefined = chain.next ?
|
||||
formatMetadataMessageChain(chain.next, advise) :
|
||||
advise ? {message: advise} : undefined;
|
||||
return {message, position, next};
|
||||
}
|
||||
|
||||
function formatMetadataError(e: Error, context: StaticSymbol): Error {
|
||||
if (isMetadataError(e)) {
|
||||
// Produce a formatted version of the and leaving enough information in the original error
|
||||
// to recover the formatting information to eventually produce a diagnostic error message.
|
||||
const position = e.position;
|
||||
const chain: MetadataMessageChain = {
|
||||
message: `Error during template compile of '${context.name}'`,
|
||||
position: position,
|
||||
next: {message: e.message, next: e.chain, context: e.context, symbol: e.symbol}
|
||||
};
|
||||
const advise = e.advise || messageAdvise(e.message, e.context);
|
||||
return formattedError(formatMetadataMessageChain(chain, advise));
|
||||
}
|
||||
return e;
|
||||
}
|
||||
function positionalError(message: string, fileName: string, line: number, column: number): Error {
|
||||
const result = syntaxError(message);
|
||||
(result as any).fileName = fileName;
|
||||
(result as any).line = line;
|
||||
(result as any).column = column;
|
||||
return result;
|
||||
}
|
@ -146,9 +146,9 @@ export class StaticSymbolResolver {
|
||||
if (isGeneratedFile(staticSymbol.filePath)) {
|
||||
return null;
|
||||
}
|
||||
let resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(staticSymbol));
|
||||
let resolvedSymbol = this.resolveSymbol(staticSymbol);
|
||||
while (resolvedSymbol && resolvedSymbol.metadata instanceof StaticSymbol) {
|
||||
resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(resolvedSymbol.metadata));
|
||||
resolvedSymbol = this.resolveSymbol(resolvedSymbol.metadata);
|
||||
}
|
||||
return (resolvedSymbol && resolvedSymbol.metadata && resolvedSymbol.metadata.arity) || null;
|
||||
}
|
||||
@ -204,7 +204,7 @@ export class StaticSymbolResolver {
|
||||
if (!baseResolvedSymbol) {
|
||||
return null;
|
||||
}
|
||||
let baseMetadata = unwrapResolvedMetadata(baseResolvedSymbol.metadata);
|
||||
const baseMetadata = baseResolvedSymbol.metadata;
|
||||
if (baseMetadata instanceof StaticSymbol) {
|
||||
return new ResolvedStaticSymbol(
|
||||
staticSymbol, this.getStaticSymbol(baseMetadata.filePath, baseMetadata.name, members));
|
||||
@ -374,19 +374,6 @@ export class StaticSymbolResolver {
|
||||
return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
|
||||
}
|
||||
|
||||
let _originalFileMemo: string|undefined;
|
||||
const getOriginalName: () => string = () => {
|
||||
if (!_originalFileMemo) {
|
||||
// Guess what hte original file name is from the reference. If it has a `.d.ts` extension
|
||||
// replace it with `.ts`. If it already has `.ts` just leave it in place. If it doesn't have
|
||||
// .ts or .d.ts, append `.ts'. Also, if it is in `node_modules`, trim the `node_module`
|
||||
// location as it is not important to finding the file.
|
||||
_originalFileMemo =
|
||||
topLevelPath.replace(/((\.ts)|(\.d\.ts)|)$/, '.ts').replace(/^.*node_modules[/\\]/, '');
|
||||
}
|
||||
return _originalFileMemo;
|
||||
};
|
||||
|
||||
const self = this;
|
||||
|
||||
class ReferenceTransformer extends ValueTransformer {
|
||||
@ -410,19 +397,10 @@ export class StaticSymbolResolver {
|
||||
if (!filePath) {
|
||||
return {
|
||||
__symbolic: 'error',
|
||||
message: `Could not resolve ${module} relative to ${sourceSymbol.filePath}.`,
|
||||
line: map.line,
|
||||
character: map.character,
|
||||
fileName: getOriginalName()
|
||||
message: `Could not resolve ${module} relative to ${sourceSymbol.filePath}.`
|
||||
};
|
||||
}
|
||||
return {
|
||||
__symbolic: 'resolved',
|
||||
symbol: self.getStaticSymbol(filePath, name),
|
||||
line: map.line,
|
||||
character: map.character,
|
||||
fileName: getOriginalName()
|
||||
};
|
||||
return self.getStaticSymbol(filePath, name);
|
||||
} else if (functionParams.indexOf(name) >= 0) {
|
||||
// reference to a function parameter
|
||||
return {__symbolic: 'reference', name: name};
|
||||
@ -433,17 +411,14 @@ export class StaticSymbolResolver {
|
||||
// ambient value
|
||||
null;
|
||||
}
|
||||
} else if (symbolic === 'error') {
|
||||
return {...map, fileName: getOriginalName()};
|
||||
} else {
|
||||
return super.visitStringMap(map, functionParams);
|
||||
}
|
||||
}
|
||||
}
|
||||
const transformedMeta = visitValue(metadata, new ReferenceTransformer(), []);
|
||||
let unwrappedTransformedMeta = unwrapResolvedMetadata(transformedMeta);
|
||||
if (unwrappedTransformedMeta instanceof StaticSymbol) {
|
||||
return this.createExport(sourceSymbol, unwrappedTransformedMeta);
|
||||
if (transformedMeta instanceof StaticSymbol) {
|
||||
return this.createExport(sourceSymbol, transformedMeta);
|
||||
}
|
||||
return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
|
||||
}
|
||||
@ -530,10 +505,3 @@ export class StaticSymbolResolver {
|
||||
export function unescapeIdentifier(identifier: string): string {
|
||||
return identifier.startsWith('___') ? identifier.substr(1) : identifier;
|
||||
}
|
||||
|
||||
export function unwrapResolvedMetadata(metadata: any): any {
|
||||
if (metadata && metadata.__symbolic === 'resolved') {
|
||||
return metadata.symbol;
|
||||
}
|
||||
return metadata;
|
||||
}
|
@ -11,7 +11,7 @@ import {Summary, SummaryResolver} from '../summary_resolver';
|
||||
import {OutputContext, ValueTransformer, ValueVisitor, visitValue} from '../util';
|
||||
|
||||
import {StaticSymbol, StaticSymbolCache} from './static_symbol';
|
||||
import {ResolvedStaticSymbol, StaticSymbolResolver, unwrapResolvedMetadata} from './static_symbol_resolver';
|
||||
import {ResolvedStaticSymbol, StaticSymbolResolver} from './static_symbol_resolver';
|
||||
import {isLoweredSymbol, ngfactoryFilePath, summaryForJitFileName, summaryForJitName} from './util';
|
||||
|
||||
export function serializeSummaries(
|
||||
@ -453,10 +453,10 @@ function isCall(metadata: any): boolean {
|
||||
}
|
||||
|
||||
function isFunctionCall(metadata: any): boolean {
|
||||
return isCall(metadata) && unwrapResolvedMetadata(metadata.expression) instanceof StaticSymbol;
|
||||
return isCall(metadata) && metadata.expression instanceof StaticSymbol;
|
||||
}
|
||||
|
||||
function isMethodCallOnVariable(metadata: any): boolean {
|
||||
return isCall(metadata) && metadata.expression && metadata.expression.__symbolic === 'select' &&
|
||||
unwrapResolvedMetadata(metadata.expression.expression) instanceof StaticSymbol;
|
||||
metadata.expression.expression instanceof StaticSymbol;
|
||||
}
|
||||
|
@ -35,7 +35,6 @@ export * from './aot/compiler';
|
||||
export * from './aot/generated_file';
|
||||
export * from './aot/compiler_options';
|
||||
export * from './aot/compiler_host';
|
||||
export * from './aot/formatted_error';
|
||||
export * from './aot/static_reflector';
|
||||
export * from './aot/static_symbol';
|
||||
export * from './aot/static_symbol_resolver';
|
||||
|
@ -42,7 +42,6 @@ export class JitCompiler {
|
||||
private _compiledDirectiveWrapperCache = new Map<Type, Type>();
|
||||
private _compiledNgModuleCache = new Map<Type, object>();
|
||||
private _sharedStylesheetCount = 0;
|
||||
private _addedAotSummaries = new Set<() => any[]>();
|
||||
|
||||
constructor(
|
||||
private _metadataResolver: CompileMetadataResolver, private _templateParser: TemplateParser,
|
||||
@ -75,25 +74,10 @@ export class JitCompiler {
|
||||
|
||||
loadAotSummaries(summaries: () => any[]) {
|
||||
this.clearCache();
|
||||
this._addAotSummaries(summaries);
|
||||
}
|
||||
|
||||
private _addAotSummaries(fn: () => any[]) {
|
||||
if (this._addedAotSummaries.has(fn)) {
|
||||
return;
|
||||
}
|
||||
this._addedAotSummaries.add(fn);
|
||||
const summaries = fn();
|
||||
for (let i = 0; i < summaries.length; i++) {
|
||||
const entry = summaries[i];
|
||||
if (typeof entry === 'function') {
|
||||
this._addAotSummaries(entry);
|
||||
} else {
|
||||
const summary = entry as CompileTypeSummary;
|
||||
this._summaryResolver.addSummary(
|
||||
{symbol: summary.type.reference, metadata: null, type: summary});
|
||||
}
|
||||
}
|
||||
flattenSummaries(summaries).forEach((summary) => {
|
||||
this._summaryResolver.addSummary(
|
||||
{symbol: summary.type.reference, metadata: null, type: summary});
|
||||
});
|
||||
}
|
||||
|
||||
hasAotSummary(ref: Type) { return !!this._summaryResolver.resolveSummary(ref); }
|
||||
@ -216,7 +200,6 @@ export class JitCompiler {
|
||||
}
|
||||
|
||||
clearCache(): void {
|
||||
// Note: don't clear the _addedAotSummaries, as they don't change!
|
||||
this._metadataResolver.clearCache();
|
||||
this._compiledTemplateCache.clear();
|
||||
this._compiledHostTemplateCache.clear();
|
||||
@ -352,6 +335,25 @@ function assertComponent(meta: CompileDirectiveMetadata) {
|
||||
}
|
||||
}
|
||||
|
||||
function flattenSummaries(
|
||||
fn: () => any[], out: CompileTypeSummary[] = [],
|
||||
seen = new Set<() => any[]>()): CompileTypeSummary[] {
|
||||
if (seen.has(fn)) {
|
||||
return out;
|
||||
}
|
||||
seen.add(fn);
|
||||
const summaries = fn();
|
||||
for (let i = 0; i < summaries.length; i++) {
|
||||
const entry = summaries[i];
|
||||
if (typeof entry === 'function') {
|
||||
flattenSummaries(entry, out, seen);
|
||||
} else {
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function createOutputContext(): OutputContext {
|
||||
const importExpr = (symbol: any) =>
|
||||
ir.importExpr({name: identifierName(symbol), moduleName: null, runtime: symbol});
|
||||
|
@ -768,9 +768,9 @@ describe('compiler (unbundled Angular)', () => {
|
||||
childClassDecorator: '',
|
||||
childModuleDecorator: '@NgModule({providers: [Extends]})',
|
||||
}))
|
||||
.toThrowError(`Error during template compile of 'Extends'
|
||||
Class Extends in /app/main.ts extends from a Injectable in another compilation unit without duplicating the decorator
|
||||
Please add a Injectable or Pipe or Directive or Component or NgModule decorator to the class.`);
|
||||
.toThrowError(
|
||||
'Class Extends in /app/main.ts extends from a Injectable in another compilation unit without duplicating the decorator. ' +
|
||||
'Please add a Injectable or Pipe or Directive or Component or NgModule decorator to the class.');
|
||||
});
|
||||
});
|
||||
|
||||
@ -792,9 +792,9 @@ describe('compiler (unbundled Angular)', () => {
|
||||
childClassDecorator: '',
|
||||
childModuleDecorator: '@NgModule({declarations: [Extends]})',
|
||||
}))
|
||||
.toThrowError(`Error during template compile of 'Extends'
|
||||
Class Extends in /app/main.ts extends from a Directive in another compilation unit without duplicating the decorator
|
||||
Please add a Directive or Component decorator to the class.`);
|
||||
.toThrowError(
|
||||
'Class Extends in /app/main.ts extends from a Directive in another compilation unit without duplicating the decorator. ' +
|
||||
'Please add a Directive or Component decorator to the class.');
|
||||
});
|
||||
});
|
||||
|
||||
@ -816,9 +816,9 @@ describe('compiler (unbundled Angular)', () => {
|
||||
childClassDecorator: '',
|
||||
childModuleDecorator: '@NgModule({declarations: [Extends]})',
|
||||
}))
|
||||
.toThrowError(`Error during template compile of 'Extends'
|
||||
Class Extends in /app/main.ts extends from a Directive in another compilation unit without duplicating the decorator
|
||||
Please add a Directive or Component decorator to the class.`);
|
||||
.toThrowError(
|
||||
'Class Extends in /app/main.ts extends from a Directive in another compilation unit without duplicating the decorator. ' +
|
||||
'Please add a Directive or Component decorator to the class.');
|
||||
});
|
||||
});
|
||||
|
||||
@ -840,9 +840,9 @@ describe('compiler (unbundled Angular)', () => {
|
||||
childClassDecorator: '',
|
||||
childModuleDecorator: '@NgModule({declarations: [Extends]})',
|
||||
}))
|
||||
.toThrowError(`Error during template compile of 'Extends'
|
||||
Class Extends in /app/main.ts extends from a Pipe in another compilation unit without duplicating the decorator
|
||||
Please add a Pipe decorator to the class.`);
|
||||
.toThrowError(
|
||||
'Class Extends in /app/main.ts extends from a Pipe in another compilation unit without duplicating the decorator. ' +
|
||||
'Please add a Pipe decorator to the class.');
|
||||
});
|
||||
});
|
||||
|
||||
@ -864,9 +864,9 @@ describe('compiler (unbundled Angular)', () => {
|
||||
childClassDecorator: '',
|
||||
childModuleDecorator: '',
|
||||
}))
|
||||
.toThrowError(`Error during template compile of 'Extends'
|
||||
Class Extends in /app/main.ts extends from a NgModule in another compilation unit without duplicating the decorator
|
||||
Please add a NgModule decorator to the class.`);
|
||||
.toThrowError(
|
||||
'Class Extends in /app/main.ts extends from a NgModule in another compilation unit without duplicating the decorator. ' +
|
||||
'Please add a NgModule decorator to the class.');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
@ -107,11 +107,8 @@ describe('StaticReflector', () => {
|
||||
it('should provide context for errors reported by the collector', () => {
|
||||
const SomeClass = reflector.findDeclaration('src/error-reporting', 'SomeClass');
|
||||
expect(() => reflector.annotations(SomeClass))
|
||||
.toThrow(new Error(`Error during template compile of 'SomeClass'
|
||||
A reasonable error message in 'Link1'
|
||||
'Link1' references 'Link2'
|
||||
'Link2' references 'ErrorSym'
|
||||
'ErrorSym' contains the error at /tmp/src/error-references.ts(13,34).`));
|
||||
.toThrow(new Error(
|
||||
'Error encountered resolving symbol values statically. A reasonable error message (position 13:34 in the original .ts file), resolving symbol ErrorSym in /tmp/src/error-references.d.ts, resolving symbol Link2 in /tmp/src/error-references.d.ts, resolving symbol Link1 in /tmp/src/error-references.d.ts, resolving symbol SomeClass in /tmp/src/error-reporting.d.ts, resolving symbol SomeClass in /tmp/src/error-reporting.d.ts'));
|
||||
});
|
||||
|
||||
it('should simplify primitive into itself', () => {
|
||||
@ -333,12 +330,10 @@ describe('StaticReflector', () => {
|
||||
it('should error on direct recursive calls', () => {
|
||||
expect(
|
||||
() => simplify(
|
||||
reflector.getStaticSymbol('/tmp/src/function-reference.ts', 'MyComp'),
|
||||
reflector.getStaticSymbol('/tmp/src/function-reference.ts', ''),
|
||||
reflector.getStaticSymbol('/tmp/src/function-reference.ts', 'recursion')))
|
||||
.toThrow(new Error(`Error during template compile of 'MyComp'
|
||||
Recursion is not supported in 'recursion'
|
||||
'recursion' references 'recursive'
|
||||
'recursive' called 'recursive' recursively.`));
|
||||
.toThrow(new Error(
|
||||
'Recursion not supported, resolving symbol recursive in /tmp/src/function-recursive.d.ts, resolving symbol recursion in /tmp/src/function-reference.ts, resolving symbol in /tmp/src/function-reference.ts'));
|
||||
});
|
||||
|
||||
it('should throw a SyntaxError without stack trace when the required resource cannot be resolved',
|
||||
@ -350,8 +345,8 @@ describe('StaticReflector', () => {
|
||||
message:
|
||||
'Could not resolve ./does-not-exist.component relative to /tmp/src/function-reference.ts'
|
||||
})))
|
||||
.toThrowError(`Error during template compile of 'AppModule'
|
||||
Could not resolve ./does-not-exist.component relative to /tmp/src/function-reference.ts.`);
|
||||
.toThrowError(
|
||||
'Error encountered resolving symbol values statically. Could not resolve ./does-not-exist.component relative to /tmp/src/function-reference.ts, resolving symbol AppModule in /tmp/src/function-reference.ts');
|
||||
});
|
||||
|
||||
it('should record data about the error in the exception', () => {
|
||||
@ -366,7 +361,7 @@ describe('StaticReflector', () => {
|
||||
simplify(
|
||||
reflector.getStaticSymbol('/tmp/src/invalid-metadata.ts', ''), classData.decorators[0]);
|
||||
} catch (e) {
|
||||
expect(e.position).toBeDefined();
|
||||
expect(e.fileName).toBe('/tmp/src/invalid-metadata.ts');
|
||||
threw = true;
|
||||
}
|
||||
expect(threw).toBe(true);
|
||||
@ -375,13 +370,10 @@ describe('StaticReflector', () => {
|
||||
it('should error on indirect recursive calls', () => {
|
||||
expect(
|
||||
() => simplify(
|
||||
reflector.getStaticSymbol('/tmp/src/function-reference.ts', 'MyComp'),
|
||||
reflector.getStaticSymbol('/tmp/src/function-reference.ts', ''),
|
||||
reflector.getStaticSymbol('/tmp/src/function-reference.ts', 'indirectRecursion')))
|
||||
.toThrow(new Error(`Error during template compile of 'MyComp'
|
||||
Recursion is not supported in 'indirectRecursion'
|
||||
'indirectRecursion' references 'indirectRecursion1'
|
||||
'indirectRecursion1' references 'indirectRecursion2'
|
||||
'indirectRecursion2' called 'indirectRecursion1' recursively.`));
|
||||
.toThrow(new Error(
|
||||
'Recursion not supported, resolving symbol indirectRecursion2 in /tmp/src/function-recursive.d.ts, resolving symbol indirectRecursion1 in /tmp/src/function-recursive.d.ts, resolving symbol indirectRecursion in /tmp/src/function-reference.ts, resolving symbol in /tmp/src/function-reference.ts'));
|
||||
});
|
||||
|
||||
it('should simplify a spread expression', () => {
|
||||
@ -409,8 +401,7 @@ describe('StaticReflector', () => {
|
||||
() => reflector.annotations(
|
||||
reflector.getStaticSymbol('/tmp/src/invalid-calls.ts', 'MyComponent')))
|
||||
.toThrow(new Error(
|
||||
`/tmp/src/invalid-calls.ts(8,29): Error during template compile of 'MyComponent'
|
||||
Function calls are not supported in decorators but 'someFunction' was called.`));
|
||||
`Error encountered resolving symbol values statically. Calling function 'someFunction', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol MyComponent in /tmp/src/invalid-calls.ts, resolving symbol MyComponent in /tmp/src/invalid-calls.ts`));
|
||||
});
|
||||
|
||||
it('should be able to get metadata for a class containing a static method call', () => {
|
||||
@ -971,7 +962,7 @@ describe('StaticReflector', () => {
|
||||
});
|
||||
|
||||
// Regression #18170
|
||||
it('should eagerly evaluate enums selects', () => {
|
||||
it('should agressively evaluate enums selects', () => {
|
||||
const data = Object.create(DEFAULT_TEST_DATA);
|
||||
const file = '/tmp/src/my_component.ts';
|
||||
data[file] = `
|
||||
@ -1087,228 +1078,6 @@ describe('StaticReflector', () => {
|
||||
expect(symbolResolver.getKnownModuleName(symbol.filePath)).toBe('a');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatted error reporting', () => {
|
||||
describe('function calls', () => {
|
||||
const fileName = '/tmp/src/invalid/components.ts';
|
||||
beforeEach(() => {
|
||||
const localData = {
|
||||
'/tmp/src/invalid/function-call.ts': `
|
||||
import {functionToCall} from 'some-module';
|
||||
export const CALL_FUNCTION = functionToCall();
|
||||
`,
|
||||
'/tmp/src/invalid/indirect.ts': `
|
||||
import {CALL_FUNCTION} from './function-call';
|
||||
|
||||
export const INDIRECT_CALL_FUNCTION = CALL_FUNCTION + 1;
|
||||
`,
|
||||
'/tmp/src/invalid/two-levels-indirect.ts': `
|
||||
import {INDIRECT_CALL_FUNCTION} from './indirect';
|
||||
|
||||
export const TWO_LEVELS_INDIRECT_CALL_FUNCTION = INDIRECT_CALL_FUNCTION + 1;
|
||||
`,
|
||||
'/tmp/src/invalid/components.ts': `
|
||||
import {functionToCall} from 'some-module';
|
||||
import {Component} from '@angular/core';
|
||||
import {CALL_FUNCTION} from './function-call';
|
||||
import {INDIRECT_CALL_FUNCTION} from './indirect';
|
||||
import {TWO_LEVELS_INDIRECT_CALL_FUNCTION} from './two-levels-indirect';
|
||||
|
||||
@Component({
|
||||
value: functionToCall()
|
||||
})
|
||||
export class CallImportedFunction {}
|
||||
|
||||
@Component({
|
||||
value: CALL_FUNCTION
|
||||
})
|
||||
export class ReferenceCalledFunction {}
|
||||
|
||||
@Component({
|
||||
value: INDIRECT_CALL_FUNCTION
|
||||
})
|
||||
export class IndirectReferenceCalledFunction {}
|
||||
|
||||
@Component({
|
||||
value: TWO_LEVELS_INDIRECT_CALL_FUNCTION
|
||||
})
|
||||
export class TwoLevelsIndirectReferenceCalledFunction {}
|
||||
`
|
||||
};
|
||||
init({...DEFAULT_TEST_DATA, ...localData});
|
||||
});
|
||||
|
||||
it('should report a formatted error for a direct function call', () => {
|
||||
expect(() => {
|
||||
return reflector.annotations(reflector.getStaticSymbol(fileName, 'CallImportedFunction'));
|
||||
})
|
||||
.toThrowError(
|
||||
`/tmp/src/invalid/components.ts(9,18): Error during template compile of 'CallImportedFunction'
|
||||
Function calls are not supported in decorators but 'functionToCall' was called.`);
|
||||
});
|
||||
|
||||
it('should report a formatted error for a refernce to a function call', () => {
|
||||
expect(() => {
|
||||
return reflector.annotations(
|
||||
reflector.getStaticSymbol(fileName, 'ReferenceCalledFunction'));
|
||||
})
|
||||
.toThrowError(
|
||||
`/tmp/src/invalid/components.ts(14,18): Error during template compile of 'ReferenceCalledFunction'
|
||||
Function calls are not supported in decorators but 'functionToCall' was called in 'CALL_FUNCTION'
|
||||
'CALL_FUNCTION' calls 'functionToCall' at /tmp/src/invalid/function-call.ts(3,38).`);
|
||||
});
|
||||
|
||||
it('should report a formatted error for an indirect reference to a function call', () => {
|
||||
expect(() => {
|
||||
return reflector.annotations(
|
||||
reflector.getStaticSymbol(fileName, 'IndirectReferenceCalledFunction'));
|
||||
})
|
||||
.toThrowError(
|
||||
`/tmp/src/invalid/components.ts(19,18): Error during template compile of 'IndirectReferenceCalledFunction'
|
||||
Function calls are not supported in decorators but 'functionToCall' was called in 'INDIRECT_CALL_FUNCTION'
|
||||
'INDIRECT_CALL_FUNCTION' references 'CALL_FUNCTION' at /tmp/src/invalid/indirect.ts(4,47)
|
||||
'CALL_FUNCTION' calls 'functionToCall' at /tmp/src/invalid/function-call.ts(3,38).`);
|
||||
});
|
||||
|
||||
it('should report a formatted error for a double-indirect refernce to a function call', () => {
|
||||
expect(() => {
|
||||
return reflector.annotations(
|
||||
reflector.getStaticSymbol(fileName, 'TwoLevelsIndirectReferenceCalledFunction'));
|
||||
})
|
||||
.toThrowError(
|
||||
`/tmp/src/invalid/components.ts(24,18): Error during template compile of 'TwoLevelsIndirectReferenceCalledFunction'
|
||||
Function calls are not supported in decorators but 'functionToCall' was called in 'TWO_LEVELS_INDIRECT_CALL_FUNCTION'
|
||||
'TWO_LEVELS_INDIRECT_CALL_FUNCTION' references 'INDIRECT_CALL_FUNCTION' at /tmp/src/invalid/two-levels-indirect.ts(4,58)
|
||||
'INDIRECT_CALL_FUNCTION' references 'CALL_FUNCTION' at /tmp/src/invalid/indirect.ts(4,47)
|
||||
'CALL_FUNCTION' calls 'functionToCall' at /tmp/src/invalid/function-call.ts(3,38).`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('macro functions', () => {
|
||||
const fileName = '/tmp/src/invalid/components.ts';
|
||||
beforeEach(() => {
|
||||
const localData = {
|
||||
'/tmp/src/invalid/function-call.ts': `
|
||||
import {functionToCall} from 'some-module';
|
||||
export const CALL_FUNCTION = functionToCall();
|
||||
`,
|
||||
'/tmp/src/invalid/indirect.ts': `
|
||||
import {CALL_FUNCTION} from './function-call';
|
||||
|
||||
export const INDIRECT_CALL_FUNCTION = CALL_FUNCTION + 1;
|
||||
`,
|
||||
'/tmp/src/invalid/macros.ts': `
|
||||
export function someMacro(value: any) {
|
||||
return [ { provide: 'key', value: value } ];
|
||||
}
|
||||
`,
|
||||
'/tmp/src/invalid/components.ts': `
|
||||
import {Component} from '@angular/core';
|
||||
import {functionToCall} from 'some-module';
|
||||
import {someMacro} from './macros';
|
||||
import {CALL_FUNCTION} from './function-call';
|
||||
import {INDIRECT_CALL_FUNCTION} from './indirect';
|
||||
|
||||
@Component({
|
||||
template: someMacro(functionToCall())
|
||||
})
|
||||
export class DirectCall {}
|
||||
|
||||
@Component({
|
||||
template: someMacro(CALL_FUNCTION)
|
||||
})
|
||||
export class IndirectCall {}
|
||||
|
||||
@Component({
|
||||
template: someMacro(INDIRECT_CALL_FUNCTION)
|
||||
})
|
||||
export class DoubleIndirectCall {}
|
||||
`
|
||||
};
|
||||
init({...DEFAULT_TEST_DATA, ...localData});
|
||||
});
|
||||
|
||||
it('should report a formatted error for a direct function call', () => {
|
||||
expect(() => {
|
||||
return reflector.annotations(reflector.getStaticSymbol(fileName, 'DirectCall'));
|
||||
})
|
||||
.toThrowError(
|
||||
`/tmp/src/invalid/components.ts(9,31): Error during template compile of 'DirectCall'
|
||||
Function calls are not supported in decorators but 'functionToCall' was called.`);
|
||||
});
|
||||
|
||||
it('should report a formatted error for a reference to a function call', () => {
|
||||
expect(() => {
|
||||
return reflector.annotations(reflector.getStaticSymbol(fileName, 'IndirectCall'));
|
||||
})
|
||||
.toThrowError(
|
||||
`/tmp/src/invalid/components.ts(14,31): Error during template compile of 'IndirectCall'
|
||||
Function calls are not supported in decorators but 'functionToCall' was called in 'CALL_FUNCTION'
|
||||
'CALL_FUNCTION' calls 'functionToCall' at /tmp/src/invalid/function-call.ts(3,38).`);
|
||||
});
|
||||
|
||||
it('should report a formatted error for an indirect refernece to a function call', () => {
|
||||
expect(() => {
|
||||
return reflector.annotations(reflector.getStaticSymbol(fileName, 'DoubleIndirectCall'));
|
||||
})
|
||||
.toThrowError(
|
||||
`/tmp/src/invalid/components.ts(19,31): Error during template compile of 'DoubleIndirectCall'
|
||||
Function calls are not supported in decorators but 'functionToCall' was called in 'INDIRECT_CALL_FUNCTION'
|
||||
'INDIRECT_CALL_FUNCTION' references 'CALL_FUNCTION' at /tmp/src/invalid/indirect.ts(4,47)
|
||||
'CALL_FUNCTION' calls 'functionToCall' at /tmp/src/invalid/function-call.ts(3,38).`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('and give advice', () => {
|
||||
// If in a reference expression, advice the user to replace with a reference.
|
||||
const fileName = '/tmp/src/invalid/components.ts';
|
||||
|
||||
function collectError(symbol: string): string {
|
||||
try {
|
||||
reflector.annotations(reflector.getStaticSymbol(fileName, symbol));
|
||||
} catch (e) {
|
||||
return e.message;
|
||||
}
|
||||
fail('Expected an exception to be thrown');
|
||||
return '';
|
||||
}
|
||||
|
||||
function initWith(content: string) {
|
||||
init({
|
||||
...DEFAULT_TEST_DATA,
|
||||
[fileName]: `import {Component} from '@angular/core';\n${content}`
|
||||
});
|
||||
}
|
||||
|
||||
it('should advise exorting a local', () => {
|
||||
initWith(`const f: string; @Component({value: f}) export class MyComp {}`);
|
||||
expect(collectError('MyComp')).toContain(`Consider exporting 'f'`);
|
||||
});
|
||||
|
||||
it('should advise export a class', () => {
|
||||
initWith('class Foo {} @Component({value: Foo}) export class MyComp {}');
|
||||
expect(collectError('MyComp')).toContain(`Consider exporting 'Foo'`);
|
||||
});
|
||||
|
||||
it('should advise avoiding destructuring', () => {
|
||||
initWith(
|
||||
'export const {foo, bar} = {foo: 1, bar: 2}; @Component({value: foo}) export class MyComp {}');
|
||||
expect(collectError('MyComp')).toContain(`Consider simplifying to avoid destructuring`);
|
||||
});
|
||||
|
||||
it('should advise converting an arrow function into an exported function', () => {
|
||||
initWith('@Component({value: () => true}) export class MyComp {}');
|
||||
expect(collectError('MyComp'))
|
||||
.toContain(`Consider changing the function expression into an exported function`);
|
||||
});
|
||||
|
||||
it('should advise converting a function expression into an exported function', () => {
|
||||
initWith('@Component({value: function () { return true; }}) export class MyComp {}');
|
||||
expect(collectError('MyComp'))
|
||||
.toContain(`Consider changing the function expression into an exported function`);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const DEFAULT_TEST_DATA: {[key: string]: any} = {
|
||||
@ -1698,5 +1467,5 @@ const DEFAULT_TEST_DATA: {[key: string]: any} = {
|
||||
export class Dep {
|
||||
@Input f: Forward;
|
||||
}
|
||||
`,
|
||||
`
|
||||
};
|
||||
|
@ -234,25 +234,15 @@ describe('StaticSymbolResolver', () => {
|
||||
});
|
||||
expect(symbolResolver.resolveSymbol(symbolCache.get('/test.ts', 'a')).metadata)
|
||||
.toEqual(symbolCache.get('/test2.ts', 'b'));
|
||||
expect(symbolResolver.resolveSymbol(symbolCache.get('/test.ts', 'x')).metadata).toEqual([{
|
||||
__symbolic: 'resolved',
|
||||
symbol: symbolCache.get('/test2.ts', 'y'),
|
||||
line: 3,
|
||||
character: 24,
|
||||
fileName: '/test.ts'
|
||||
}]);
|
||||
expect(symbolResolver.resolveSymbol(symbolCache.get('/test.ts', 'x')).metadata).toEqual([
|
||||
symbolCache.get('/test2.ts', 'y')
|
||||
]);
|
||||
expect(symbolResolver.resolveSymbol(symbolCache.get('/test.ts', 'simpleFn')).metadata).toEqual({
|
||||
__symbolic: 'function',
|
||||
parameters: ['fnArg'],
|
||||
value: [
|
||||
symbolCache.get('/test.ts', 'a'), {
|
||||
__symbolic: 'resolved',
|
||||
symbol: symbolCache.get('/test2.ts', 'y'),
|
||||
line: 6,
|
||||
character: 21,
|
||||
fileName: '/test.ts'
|
||||
},
|
||||
{__symbolic: 'reference', name: 'fnArg'}
|
||||
symbolCache.get('/test.ts', 'a'), symbolCache.get('/test2.ts', 'y'),
|
||||
Object({__symbolic: 'reference', name: 'fnArg'})
|
||||
]
|
||||
});
|
||||
});
|
||||
|
@ -430,41 +430,5 @@ export function main() {
|
||||
importAs: symbolCache.get('someFile.ngfactory.d.ts', 'lib_1')
|
||||
}]);
|
||||
});
|
||||
|
||||
describe('with resolved symbols', () => {
|
||||
it('should be able to serialize a call', () => {
|
||||
init();
|
||||
const serialized = serializeSummaries(
|
||||
'someFile.ts', createMockOutputContext(), summaryResolver, symbolResolver, [{
|
||||
symbol: symbolCache.get('/tmp/test.ts', 'main'),
|
||||
metadata: {
|
||||
__symbolic: 'call',
|
||||
expression:
|
||||
{__symbolic: 'resolved', symbol: symbolCache.get('/tmp/test2.ts', 'ref')}
|
||||
}
|
||||
}],
|
||||
[]);
|
||||
expect(serialized.json).not.toContain('error');
|
||||
});
|
||||
|
||||
it('should be able to serialize a call to a method', () => {
|
||||
init();
|
||||
const serialized = serializeSummaries(
|
||||
'someFile.ts', createMockOutputContext(), summaryResolver, symbolResolver, [{
|
||||
symbol: symbolCache.get('/tmp/test.ts', 'main'),
|
||||
metadata: {
|
||||
__symbolic: 'call',
|
||||
expression: {
|
||||
__symbolic: 'select',
|
||||
expression:
|
||||
{__symbolic: 'resolved', symbol: symbolCache.get('/tmp/test2.ts', 'ref')},
|
||||
name: 'foo'
|
||||
}
|
||||
}
|
||||
}],
|
||||
[]);
|
||||
expect(serialized.json).not.toContain('error');
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
@ -20,5 +20,5 @@ export {DirectRenderer as ɵDirectRenderer, RenderDebugInfo as ɵRenderDebugInfo
|
||||
export {global as ɵglobal, looseIdentical as ɵlooseIdentical, stringify as ɵstringify} from './util';
|
||||
export {makeDecorator as ɵmakeDecorator} from './util/decorators';
|
||||
export {isObservable as ɵisObservable, isPromise as ɵisPromise} from './util/lang';
|
||||
export {clearOverrides as ɵclearOverrides, overrideComponentView as ɵoverrideComponentView, overrideProvider as ɵoverrideProvider} from './view/index';
|
||||
export {clearProviderOverrides as ɵclearProviderOverrides, overrideProvider as ɵoverrideProvider} from './view/index';
|
||||
export {NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR as ɵNOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR} from './view/provider';
|
||||
|
@ -7,12 +7,11 @@
|
||||
*/
|
||||
|
||||
import {Injector} from '../di/injector';
|
||||
import {ComponentFactory} from '../linker/component_factory';
|
||||
import {NgModuleFactory, NgModuleRef} from '../linker/ng_module_factory';
|
||||
import {Type} from '../type';
|
||||
|
||||
import {initServicesIfNeeded} from './services';
|
||||
import {NgModuleDefinitionFactory, ProviderOverride, Services, ViewDefinition} from './types';
|
||||
import {NgModuleDefinitionFactory, ProviderOverride, Services} from './types';
|
||||
import {resolveDefinition} from './util';
|
||||
|
||||
export function overrideProvider(override: ProviderOverride) {
|
||||
@ -20,14 +19,9 @@ export function overrideProvider(override: ProviderOverride) {
|
||||
return Services.overrideProvider(override);
|
||||
}
|
||||
|
||||
export function overrideComponentView(comp: Type<any>, componentFactory: ComponentFactory<any>) {
|
||||
export function clearProviderOverrides() {
|
||||
initServicesIfNeeded();
|
||||
return Services.overrideComponentView(comp, componentFactory);
|
||||
}
|
||||
|
||||
export function clearOverrides() {
|
||||
initServicesIfNeeded();
|
||||
return Services.clearOverrides();
|
||||
return Services.clearProviderOverrides();
|
||||
}
|
||||
|
||||
// Attention: this function is called as top level function.
|
||||
|
@ -7,7 +7,7 @@
|
||||
*/
|
||||
|
||||
export {anchorDef, elementDef} from './element';
|
||||
export {clearOverrides, createNgModuleFactory, overrideComponentView, overrideProvider} from './entrypoint';
|
||||
export {clearProviderOverrides, createNgModuleFactory, overrideProvider} from './entrypoint';
|
||||
export {ngContentDef} from './ng_content';
|
||||
export {moduleDef, moduleProvideDef} from './ng_module';
|
||||
export {directiveDef, pipeDef, providerDef} from './provider';
|
||||
|
@ -14,7 +14,7 @@ import {ViewContainerRef} from '../linker/view_container_ref';
|
||||
import {Renderer as RendererV1, Renderer2} from '../render/api';
|
||||
|
||||
import {createChangeDetectorRef, createInjector, createRendererV1} from './refs';
|
||||
import {BindingDef, BindingFlags, DepDef, DepFlags, NodeDef, NodeFlags, OutputDef, OutputType, ProviderData, QueryValueType, Services, ViewData, ViewFlags, ViewState, asElementData, asProviderData, shouldCallLifecycleInitHook} from './types';
|
||||
import {BindingDef, BindingFlags, DepDef, DepFlags, NodeDef, NodeFlags, OutputDef, OutputType, ProviderData, QueryValueType, Services, ViewData, ViewFlags, ViewState, asElementData, asProviderData} from './types';
|
||||
import {calcBindingFlags, checkBinding, dispatchEvent, isComponentView, splitDepsDsl, splitMatchedQueriesDsl, tokenKey, viewParentEl} from './util';
|
||||
|
||||
const RendererV1TokenKey = tokenKey(RendererV1);
|
||||
@ -198,8 +198,7 @@ export function checkAndUpdateDirectiveInline(
|
||||
if (changes) {
|
||||
directive.ngOnChanges(changes);
|
||||
}
|
||||
if ((def.flags & NodeFlags.OnInit) &&
|
||||
shouldCallLifecycleInitHook(view, ViewState.InitState_CallingOnInit, def.nodeIndex)) {
|
||||
if ((view.state & ViewState.FirstCheck) && (def.flags & NodeFlags.OnInit)) {
|
||||
directive.ngOnInit();
|
||||
}
|
||||
if (def.flags & NodeFlags.DoCheck) {
|
||||
@ -223,8 +222,7 @@ export function checkAndUpdateDirectiveDynamic(
|
||||
if (changes) {
|
||||
directive.ngOnChanges(changes);
|
||||
}
|
||||
if ((def.flags & NodeFlags.OnInit) &&
|
||||
shouldCallLifecycleInitHook(view, ViewState.InitState_CallingOnInit, def.nodeIndex)) {
|
||||
if ((view.state & ViewState.FirstCheck) && (def.flags & NodeFlags.OnInit)) {
|
||||
directive.ngOnInit();
|
||||
}
|
||||
if (def.flags & NodeFlags.DoCheck) {
|
||||
@ -449,61 +447,17 @@ function updateProp(
|
||||
return changes;
|
||||
}
|
||||
|
||||
// This function calls the ngAfterContentCheck, ngAfterContentInit,
|
||||
// ngAfterViewCheck, and ngAfterViewInit lifecycle hooks (depending on the node
|
||||
// flags in lifecycle). Unlike ngDoCheck, ngOnChanges and ngOnInit, which are
|
||||
// called during a pre-order traversal of the view tree (that is calling the
|
||||
// parent hooks before the child hooks) these events are sent in using a
|
||||
// post-order traversal of the tree (children before parents). This changes the
|
||||
// meaning of initIndex in the view state. For ngOnInit, initIndex tracks the
|
||||
// expected nodeIndex which a ngOnInit should be called. When sending
|
||||
// ngAfterContentInit and ngAfterViewInit it is the expected count of
|
||||
// ngAfterContentInit or ngAfterViewInit methods that have been called. This
|
||||
// ensure that dispite being called recursively or after picking up after an
|
||||
// exception, the ngAfterContentInit or ngAfterViewInit will be called on the
|
||||
// correct nodes. Consider for example, the following (where E is an element
|
||||
// and D is a directive)
|
||||
// Tree: pre-order index post-order index
|
||||
// E1 0 6
|
||||
// E2 1 1
|
||||
// D3 2 0
|
||||
// E4 3 5
|
||||
// E5 4 4
|
||||
// E6 5 2
|
||||
// E7 6 3
|
||||
// As can be seen, the post-order index has an unclear relationship to the
|
||||
// pre-order index (postOrderIndex === preOrderIndex - parentCount +
|
||||
// childCount). Since number of calls to ngAfterContentInit and ngAfterViewInit
|
||||
// are stable (will be the same for the same view regardless of exceptions or
|
||||
// recursion) we just need to count them which will roughly correspond to the
|
||||
// post-order index (it skips elements and directives that do not have
|
||||
// lifecycle hooks).
|
||||
//
|
||||
// For example, if an exception is raised in the E6.onAfterViewInit() the
|
||||
// initIndex is left at 3 (by shouldCallLifecycleInitHook() which set it to
|
||||
// initIndex + 1). When checkAndUpdateView() is called again D3, E2 and E6 will
|
||||
// not have their ngAfterViewInit() called but, starting with E7, the rest of
|
||||
// the view will begin getting ngAfterViewInit() called until a check and
|
||||
// pass is complete.
|
||||
//
|
||||
// This algorthim also handles recursion. Consider if E4's ngAfterViewInit()
|
||||
// indirectly calls E1's ChangeDetectorRef.detectChanges(). The expected
|
||||
// initIndex is set to 6, the recusive checkAndUpdateView() starts walk again.
|
||||
// D3, E2, E6, E7, E5 and E4 are skipped, ngAfterViewInit() is called on E1.
|
||||
// When the recursion returns the initIndex will be 7 so E1 is skipped as it
|
||||
// has already been called in the recursively called checkAnUpdateView().
|
||||
export function callLifecycleHooksChildrenFirst(view: ViewData, lifecycles: NodeFlags) {
|
||||
if (!(view.def.nodeFlags & lifecycles)) {
|
||||
return;
|
||||
}
|
||||
const nodes = view.def.nodes;
|
||||
let initIndex = 0;
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const nodeDef = nodes[i];
|
||||
let parent = nodeDef.parent;
|
||||
if (!parent && nodeDef.flags & lifecycles) {
|
||||
// matching root node (e.g. a pipe)
|
||||
callProviderLifecycles(view, i, nodeDef.flags & lifecycles, initIndex++);
|
||||
callProviderLifecycles(view, i, nodeDef.flags & lifecycles);
|
||||
}
|
||||
if ((nodeDef.childFlags & lifecycles) === 0) {
|
||||
// no child matches one of the lifecycles
|
||||
@ -513,28 +467,25 @@ export function callLifecycleHooksChildrenFirst(view: ViewData, lifecycles: Node
|
||||
i === parent.nodeIndex + parent.childCount) {
|
||||
// last child of an element
|
||||
if (parent.directChildFlags & lifecycles) {
|
||||
initIndex = callElementProvidersLifecycles(view, parent, lifecycles, initIndex);
|
||||
callElementProvidersLifecycles(view, parent, lifecycles);
|
||||
}
|
||||
parent = parent.parent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function callElementProvidersLifecycles(
|
||||
view: ViewData, elDef: NodeDef, lifecycles: NodeFlags, initIndex: number): number {
|
||||
function callElementProvidersLifecycles(view: ViewData, elDef: NodeDef, lifecycles: NodeFlags) {
|
||||
for (let i = elDef.nodeIndex + 1; i <= elDef.nodeIndex + elDef.childCount; i++) {
|
||||
const nodeDef = view.def.nodes[i];
|
||||
if (nodeDef.flags & lifecycles) {
|
||||
callProviderLifecycles(view, i, nodeDef.flags & lifecycles, initIndex++);
|
||||
callProviderLifecycles(view, i, nodeDef.flags & lifecycles);
|
||||
}
|
||||
// only visit direct children
|
||||
i += nodeDef.childCount;
|
||||
}
|
||||
return initIndex;
|
||||
}
|
||||
|
||||
function callProviderLifecycles(
|
||||
view: ViewData, index: number, lifecycles: NodeFlags, initIndex: number) {
|
||||
function callProviderLifecycles(view: ViewData, index: number, lifecycles: NodeFlags) {
|
||||
const providerData = asProviderData(view, index);
|
||||
if (!providerData) {
|
||||
return;
|
||||
@ -544,15 +495,13 @@ function callProviderLifecycles(
|
||||
return;
|
||||
}
|
||||
Services.setCurrentNode(view, index);
|
||||
if (lifecycles & NodeFlags.AfterContentInit &&
|
||||
shouldCallLifecycleInitHook(view, ViewState.InitState_CallingAfterContentInit, initIndex)) {
|
||||
if (lifecycles & NodeFlags.AfterContentInit) {
|
||||
provider.ngAfterContentInit();
|
||||
}
|
||||
if (lifecycles & NodeFlags.AfterContentChecked) {
|
||||
provider.ngAfterContentChecked();
|
||||
}
|
||||
if (lifecycles & NodeFlags.AfterViewInit &&
|
||||
shouldCallLifecycleInitHook(view, ViewState.InitState_CallingAfterViewInit, initIndex)) {
|
||||
if (lifecycles & NodeFlags.AfterViewInit) {
|
||||
provider.ngAfterViewInit();
|
||||
}
|
||||
if (lifecycles & NodeFlags.AfterViewChecked) {
|
||||
|
@ -10,7 +10,6 @@ import {isDevMode} from '../application_ref';
|
||||
import {DebugElement, DebugNode, EventListener, getDebugNode, indexDebugNode, removeDebugNodeFromIndex} from '../debug/debug_node';
|
||||
import {Injector} from '../di';
|
||||
import {ErrorHandler} from '../error_handler';
|
||||
import {ComponentFactory} from '../linker/component_factory';
|
||||
import {NgModuleRef} from '../linker/ng_module_factory';
|
||||
import {Renderer2, RendererFactory2, RendererStyleFlags2, RendererType2} from '../render/api';
|
||||
import {Sanitizer} from '../security';
|
||||
@ -19,9 +18,9 @@ import {Type} from '../type';
|
||||
import {isViewDebugError, viewDestroyedError, viewWrappedDebugError} from './errors';
|
||||
import {resolveDep} from './provider';
|
||||
import {dirtyParentQueries, getQueryValue} from './query';
|
||||
import {createInjector, createNgModuleRef, getComponentViewDefinitionFactory} from './refs';
|
||||
import {createInjector, createNgModuleRef} from './refs';
|
||||
import {ArgumentType, BindingFlags, CheckType, DebugContext, DepDef, ElementData, NgModuleDefinition, NgModuleProviderDef, NodeDef, NodeFlags, NodeLogger, ProviderOverride, RootData, Services, ViewData, ViewDefinition, ViewState, asElementData, asPureExpressionData} from './types';
|
||||
import {NOOP, isComponentView, renderNode, resolveDefinition, splitDepsDsl, viewParentEl} from './util';
|
||||
import {NOOP, isComponentView, renderNode, splitDepsDsl, viewParentEl} from './util';
|
||||
import {checkAndUpdateNode, checkAndUpdateView, checkNoChangesNode, checkNoChangesView, createComponentView, createEmbeddedView, createRootView, destroyView} from './view';
|
||||
|
||||
|
||||
@ -39,8 +38,7 @@ export function initServicesIfNeeded() {
|
||||
Services.createComponentView = services.createComponentView;
|
||||
Services.createNgModuleRef = services.createNgModuleRef;
|
||||
Services.overrideProvider = services.overrideProvider;
|
||||
Services.overrideComponentView = services.overrideComponentView;
|
||||
Services.clearOverrides = services.clearOverrides;
|
||||
Services.clearProviderOverrides = services.clearProviderOverrides;
|
||||
Services.checkAndUpdateView = services.checkAndUpdateView;
|
||||
Services.checkNoChangesView = services.checkNoChangesView;
|
||||
Services.destroyView = services.destroyView;
|
||||
@ -60,8 +58,7 @@ function createProdServices() {
|
||||
createComponentView: createComponentView,
|
||||
createNgModuleRef: createNgModuleRef,
|
||||
overrideProvider: NOOP,
|
||||
overrideComponentView: NOOP,
|
||||
clearOverrides: NOOP,
|
||||
clearProviderOverrides: NOOP,
|
||||
checkAndUpdateView: checkAndUpdateView,
|
||||
checkNoChangesView: checkNoChangesView,
|
||||
destroyView: destroyView,
|
||||
@ -87,8 +84,7 @@ function createDebugServices() {
|
||||
createComponentView: debugCreateComponentView,
|
||||
createNgModuleRef: debugCreateNgModuleRef,
|
||||
overrideProvider: debugOverrideProvider,
|
||||
overrideComponentView: debugOverrideComponentView,
|
||||
clearOverrides: debugClearOverrides,
|
||||
clearProviderOverrides: debugClearProviderOverrides,
|
||||
checkAndUpdateView: debugCheckAndUpdateView,
|
||||
checkNoChangesView: debugCheckNoChangesView,
|
||||
destroyView: debugDestroyView,
|
||||
@ -143,15 +139,10 @@ function debugCreateEmbeddedView(
|
||||
|
||||
function debugCreateComponentView(
|
||||
parentView: ViewData, nodeDef: NodeDef, viewDef: ViewDefinition, hostElement: any): ViewData {
|
||||
const overrideComponentView =
|
||||
viewDefOverrides.get(nodeDef.element !.componentProvider !.provider !.token);
|
||||
if (overrideComponentView) {
|
||||
viewDef = overrideComponentView;
|
||||
} else {
|
||||
viewDef = applyProviderOverridesToView(viewDef);
|
||||
}
|
||||
const defWithOverride = applyProviderOverridesToView(viewDef);
|
||||
return callWithDebugContext(
|
||||
DebugAction.create, createComponentView, null, [parentView, nodeDef, viewDef, hostElement]);
|
||||
DebugAction.create, createComponentView, null,
|
||||
[parentView, nodeDef, defWithOverride, hostElement]);
|
||||
}
|
||||
|
||||
function debugCreateNgModuleRef(
|
||||
@ -162,21 +153,13 @@ function debugCreateNgModuleRef(
|
||||
}
|
||||
|
||||
const providerOverrides = new Map<any, ProviderOverride>();
|
||||
const viewDefOverrides = new Map<any, ViewDefinition>();
|
||||
|
||||
function debugOverrideProvider(override: ProviderOverride) {
|
||||
providerOverrides.set(override.token, override);
|
||||
}
|
||||
|
||||
function debugOverrideComponentView(comp: any, compFactory: ComponentFactory<any>) {
|
||||
const hostViewDef = resolveDefinition(getComponentViewDefinitionFactory(compFactory));
|
||||
const compViewDef = resolveDefinition(hostViewDef.nodes[0].element !.componentView !);
|
||||
viewDefOverrides.set(comp, compViewDef);
|
||||
}
|
||||
|
||||
function debugClearOverrides() {
|
||||
function debugClearProviderOverrides() {
|
||||
providerOverrides.clear();
|
||||
viewDefOverrides.clear();
|
||||
}
|
||||
|
||||
// Notes about the algorithm:
|
||||
|
@ -8,7 +8,6 @@
|
||||
|
||||
import {Injector} from '../di';
|
||||
import {ErrorHandler} from '../error_handler';
|
||||
import {ComponentFactory} from '../linker/component_factory';
|
||||
import {NgModuleRef} from '../linker/ng_module_factory';
|
||||
import {QueryList} from '../linker/query_list';
|
||||
import {TemplateRef} from '../linker/template_ref';
|
||||
@ -17,7 +16,6 @@ import {Renderer2, RendererFactory2, RendererType2} from '../render/api';
|
||||
import {Sanitizer, SecurityContext} from '../security';
|
||||
import {Type} from '../type';
|
||||
|
||||
|
||||
// -------------------------------------
|
||||
// Defs
|
||||
// -------------------------------------
|
||||
@ -354,7 +352,6 @@ export interface ViewData {
|
||||
state: ViewState;
|
||||
oldValues: any[];
|
||||
disposables: DisposableFn[]|null;
|
||||
initIndex: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -370,52 +367,8 @@ export const enum ViewState {
|
||||
CheckProjectedViews = 1 << 6,
|
||||
Destroyed = 1 << 7,
|
||||
|
||||
// InitState Uses 3 bits
|
||||
InitState_Mask = 7 << 8,
|
||||
InitState_BeforeInit = 0 << 8,
|
||||
InitState_CallingOnInit = 1 << 8,
|
||||
InitState_CallingAfterContentInit = 2 << 8,
|
||||
InitState_CallingAfterViewInit = 3 << 8,
|
||||
InitState_AfterInit = 4 << 8,
|
||||
|
||||
CatDetectChanges = Attached | ChecksEnabled,
|
||||
CatInit = BeforeFirstCheck | CatDetectChanges | InitState_BeforeInit
|
||||
}
|
||||
|
||||
// Called before each cycle of a view's check to detect whether this is in the
|
||||
// initState for which we need to call ngOnInit, ngAfterContentInit or ngAfterViewInit
|
||||
// lifecycle methods. Returns true if this check cycle should call lifecycle
|
||||
// methods.
|
||||
export function shiftInitState(
|
||||
view: ViewData, priorInitState: ViewState, newInitState: ViewState): boolean {
|
||||
// Only update the InitState if we are currently in the prior state.
|
||||
// For example, only move into CallingInit if we are in BeforeInit. Only
|
||||
// move into CallingContentInit if we are in CallingInit. Normally this will
|
||||
// always be true because of how checkCycle is called in checkAndUpdateView.
|
||||
// However, if checkAndUpdateView is called recursively or if an exception is
|
||||
// thrown while checkAndUpdateView is running, checkAndUpdateView starts over
|
||||
// from the beginning. This ensures the state is monotonically increasing,
|
||||
// terminating in the AfterInit state, which ensures the Init methods are called
|
||||
// at least once and only once.
|
||||
const state = view.state;
|
||||
const initState = state & ViewState.InitState_Mask;
|
||||
if (initState === priorInitState) {
|
||||
view.state = (state & ~ViewState.InitState_Mask) | newInitState;
|
||||
view.initIndex = -1;
|
||||
return true;
|
||||
}
|
||||
return initState === newInitState;
|
||||
}
|
||||
|
||||
// Returns true if the lifecycle init method should be called for the node with
|
||||
// the given init index.
|
||||
export function shouldCallLifecycleInitHook(
|
||||
view: ViewData, initState: ViewState, index: number): boolean {
|
||||
if ((view.state & ViewState.InitState_Mask) === initState && view.initIndex <= index) {
|
||||
view.initIndex = index + 1;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
CatInit = BeforeFirstCheck | CatDetectChanges
|
||||
}
|
||||
|
||||
export interface DisposableFn { (): void; }
|
||||
@ -569,8 +522,7 @@ export interface Services {
|
||||
moduleType: Type<any>, parent: Injector, bootstrapComponents: Type<any>[],
|
||||
def: NgModuleDefinition): NgModuleRef<any>;
|
||||
overrideProvider(override: ProviderOverride): void;
|
||||
overrideComponentView(compType: Type<any>, compFactory: ComponentFactory<any>): void;
|
||||
clearOverrides(): void;
|
||||
clearProviderOverrides(): void;
|
||||
checkAndUpdateView(view: ViewData): void;
|
||||
checkNoChangesView(view: ViewData): void;
|
||||
destroyView(view: ViewData): void;
|
||||
@ -595,8 +547,7 @@ export const Services: Services = {
|
||||
createComponentView: undefined !,
|
||||
createNgModuleRef: undefined !,
|
||||
overrideProvider: undefined !,
|
||||
overrideComponentView: undefined !,
|
||||
clearOverrides: undefined !,
|
||||
clearProviderOverrides: undefined !,
|
||||
checkAndUpdateView: undefined !,
|
||||
checkNoChangesView: undefined !,
|
||||
destroyView: undefined !,
|
||||
|
@ -16,7 +16,7 @@ import {checkAndUpdatePureExpressionDynamic, checkAndUpdatePureExpressionInline,
|
||||
import {checkAndUpdateQuery, createQuery} from './query';
|
||||
import {createTemplateData, createViewContainerData} from './refs';
|
||||
import {checkAndUpdateTextDynamic, checkAndUpdateTextInline, createText} from './text';
|
||||
import {ArgumentType, CheckType, ElementData, NodeData, NodeDef, NodeFlags, ProviderData, RootData, Services, ViewData, ViewDefinition, ViewFlags, ViewHandleEventFn, ViewState, ViewUpdateFn, asElementData, asQueryList, asTextData, shiftInitState} from './types';
|
||||
import {ArgumentType, CheckType, ElementData, NodeData, NodeDef, NodeFlags, ProviderData, RootData, Services, ViewData, ViewDefinition, ViewFlags, ViewHandleEventFn, ViewState, ViewUpdateFn, asElementData, asQueryList, asTextData} from './types';
|
||||
import {NOOP, checkBindingNoChanges, isComponentView, markParentViewsForCheckProjectedViews, resolveDefinition, tokenKey} from './util';
|
||||
import {detachProjectedView} from './view_attach';
|
||||
|
||||
@ -236,8 +236,7 @@ function createView(
|
||||
context: null,
|
||||
component: null, nodes,
|
||||
state: ViewState.CatInit, root, renderer,
|
||||
oldValues: new Array(def.bindingCount), disposables,
|
||||
initIndex: -1
|
||||
oldValues: new Array(def.bindingCount), disposables
|
||||
};
|
||||
return view;
|
||||
}
|
||||
@ -354,32 +353,29 @@ export function checkAndUpdateView(view: ViewData) {
|
||||
} else {
|
||||
view.state &= ~ViewState.FirstCheck;
|
||||
}
|
||||
shiftInitState(view, ViewState.InitState_BeforeInit, ViewState.InitState_CallingOnInit);
|
||||
markProjectedViewsForCheck(view);
|
||||
Services.updateDirectives(view, CheckType.CheckAndUpdate);
|
||||
execEmbeddedViewsAction(view, ViewAction.CheckAndUpdate);
|
||||
execQueriesAction(
|
||||
view, NodeFlags.TypeContentQuery, NodeFlags.DynamicQuery, CheckType.CheckAndUpdate);
|
||||
let callInit = shiftInitState(
|
||||
view, ViewState.InitState_CallingOnInit, ViewState.InitState_CallingAfterContentInit);
|
||||
|
||||
callLifecycleHooksChildrenFirst(
|
||||
view, NodeFlags.AfterContentChecked | (callInit ? NodeFlags.AfterContentInit : 0));
|
||||
view, NodeFlags.AfterContentChecked |
|
||||
(view.state & ViewState.FirstCheck ? NodeFlags.AfterContentInit : 0));
|
||||
|
||||
Services.updateRenderer(view, CheckType.CheckAndUpdate);
|
||||
|
||||
execComponentViewsAction(view, ViewAction.CheckAndUpdate);
|
||||
execQueriesAction(
|
||||
view, NodeFlags.TypeViewQuery, NodeFlags.DynamicQuery, CheckType.CheckAndUpdate);
|
||||
callInit = shiftInitState(
|
||||
view, ViewState.InitState_CallingAfterContentInit, ViewState.InitState_CallingAfterViewInit);
|
||||
callLifecycleHooksChildrenFirst(
|
||||
view, NodeFlags.AfterViewChecked | (callInit ? NodeFlags.AfterViewInit : 0));
|
||||
view, NodeFlags.AfterViewChecked |
|
||||
(view.state & ViewState.FirstCheck ? NodeFlags.AfterViewInit : 0));
|
||||
|
||||
if (view.def.flags & ViewFlags.OnPush) {
|
||||
view.state &= ~ViewState.ChecksEnabled;
|
||||
}
|
||||
view.state &= ~(ViewState.CheckProjectedViews | ViewState.CheckProjectedView);
|
||||
shiftInitState(view, ViewState.InitState_CallingAfterViewInit, ViewState.InitState_AfterInit);
|
||||
}
|
||||
|
||||
export function checkAndUpdateNode(
|
||||
|
@ -80,38 +80,6 @@ export function main() {
|
||||
flushMicrotasks();
|
||||
expect(cmp.status).toEqual('done');
|
||||
}));
|
||||
|
||||
it('should always run .start callbacks before .done callbacks even for noop animations',
|
||||
fakeAsync(() => {
|
||||
@Component({
|
||||
selector: 'cmp',
|
||||
template: `
|
||||
<div [@myAnimation]="exp" (@myAnimation.start)="cb('start')" (@myAnimation.done)="cb('done')"></div>
|
||||
`,
|
||||
animations: [
|
||||
trigger(
|
||||
'myAnimation',
|
||||
[
|
||||
transition('* => go', []),
|
||||
]),
|
||||
]
|
||||
})
|
||||
class Cmp {
|
||||
exp: any = false;
|
||||
log: string[] = [];
|
||||
cb(status: string) { this.log.push(status); }
|
||||
}
|
||||
|
||||
TestBed.configureTestingModule({declarations: [Cmp]});
|
||||
const fixture = TestBed.createComponent(Cmp);
|
||||
const cmp = fixture.componentInstance;
|
||||
cmp.exp = 'go';
|
||||
fixture.detectChanges();
|
||||
expect(cmp.log).toEqual([]);
|
||||
|
||||
flushMicrotasks();
|
||||
expect(cmp.log).toEqual(['start', 'done']);
|
||||
}));
|
||||
});
|
||||
|
||||
describe('component fixture integration', () => {
|
||||
|
@ -61,10 +61,8 @@ export function main() {
|
||||
const injector = Injector.create([{provide: IterableDiffers, useValue: parent}]);
|
||||
const childInjector = Injector.create([IterableDiffers.extend([factory2])], injector);
|
||||
|
||||
expect(injector.get<IterableDiffers>(IterableDiffers).factories).toEqual([factory1]);
|
||||
expect(childInjector.get<IterableDiffers>(IterableDiffers).factories).toEqual([
|
||||
factory2, factory1
|
||||
]);
|
||||
expect(injector.get(IterableDiffers).factories).toEqual([factory1]);
|
||||
expect(childInjector.get(IterableDiffers).factories).toEqual([factory2, factory1]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@ -98,7 +98,7 @@ export function main() {
|
||||
|
||||
it('should resolve dependencies based on type information', () => {
|
||||
const injector = Injector.create([Engine.PROVIDER, Car.PROVIDER]);
|
||||
const car = injector.get<Car>(Car);
|
||||
const car = injector.get(Car);
|
||||
|
||||
expect(car).toBeAnInstanceOf(Car);
|
||||
expect(car.engine).toBeAnInstanceOf(Engine);
|
||||
@ -138,7 +138,7 @@ export function main() {
|
||||
const injector = Injector.create(
|
||||
[Engine.PROVIDER, {provide: Car, useFactory: sportsCarFactory, deps: [Engine]}]);
|
||||
|
||||
const car = injector.get<Car>(Car);
|
||||
const car = injector.get(Car);
|
||||
expect(car).toBeAnInstanceOf(SportsCar);
|
||||
expect(car.engine).toBeAnInstanceOf(Engine);
|
||||
});
|
||||
@ -208,7 +208,7 @@ export function main() {
|
||||
{provide: Car, useFactory: (e: Engine) => new SportsCar(e), deps: [Engine]}
|
||||
]);
|
||||
|
||||
const car = injector.get<Car>(Car);
|
||||
const car = injector.get(Car);
|
||||
expect(car).toBeAnInstanceOf(SportsCar);
|
||||
expect(car.engine).toBeAnInstanceOf(Engine);
|
||||
});
|
||||
@ -216,7 +216,7 @@ export function main() {
|
||||
it('should support optional dependencies', () => {
|
||||
const injector = Injector.create([CarWithOptionalEngine.PROVIDER]);
|
||||
|
||||
const car = injector.get<CarWithOptionalEngine>(CarWithOptionalEngine);
|
||||
const car = injector.get(CarWithOptionalEngine);
|
||||
expect(car.engine).toEqual(null);
|
||||
});
|
||||
|
||||
@ -364,7 +364,7 @@ export function main() {
|
||||
const parent = Injector.create([Car.PROVIDER, Engine.PROVIDER]);
|
||||
const child = Injector.create([TurboEngine.PROVIDER], parent);
|
||||
|
||||
const carFromChild = child.get<Car>(Car);
|
||||
const carFromChild = child.get(Car);
|
||||
expect(carFromChild.engine).toBeAnInstanceOf(Engine);
|
||||
});
|
||||
|
||||
@ -391,7 +391,7 @@ export function main() {
|
||||
it('should instantiate an object in the context of the injector', () => {
|
||||
const inj = Injector.create([Engine.PROVIDER]);
|
||||
const childInj = Injector.create([Car.PROVIDER], inj);
|
||||
const car = childInj.get<Car>(Car);
|
||||
const car = childInj.get(Car);
|
||||
expect(car).toBeAnInstanceOf(Car);
|
||||
expect(car.engine).toBe(inj.get(Engine));
|
||||
});
|
||||
@ -430,7 +430,7 @@ export function main() {
|
||||
],
|
||||
parent);
|
||||
|
||||
expect(child.get<Car>(Car).engine).toBeAnInstanceOf(Engine);
|
||||
expect(child.get(Car).engine).toBeAnInstanceOf(Engine);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@ -1152,6 +1152,7 @@ export function main() {
|
||||
]);
|
||||
}));
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('enforce no new changes', () => {
|
||||
@ -1462,151 +1463,6 @@ export function main() {
|
||||
expect(divEl.nativeElement).toHaveCssClass('foo');
|
||||
});
|
||||
});
|
||||
|
||||
describe('lifecycle asserts', () => {
|
||||
let logged: string[];
|
||||
|
||||
function log(value: string) { logged.push(value); }
|
||||
function clearLog() { logged = []; }
|
||||
|
||||
function expectOnceAndOnlyOnce(log: string) {
|
||||
expect(logged.indexOf(log) >= 0)
|
||||
.toBeTruthy(`'${log}' not logged. Log was ${JSON.stringify(logged)}`);
|
||||
expect(logged.lastIndexOf(log) === logged.indexOf(log))
|
||||
.toBeTruthy(`'${log}' logged more than once. Log was ${JSON.stringify(logged)}`);
|
||||
}
|
||||
|
||||
beforeEach(() => { clearLog(); });
|
||||
|
||||
enum LifetimeMethods {
|
||||
None = 0,
|
||||
ngOnInit = 1 << 0,
|
||||
ngOnChanges = 1 << 1,
|
||||
ngAfterViewInit = 1 << 2,
|
||||
ngAfterContentInit = 1 << 3,
|
||||
ngDoCheck = 1 << 4,
|
||||
InitMethods = ngOnInit | ngAfterViewInit | ngAfterContentInit,
|
||||
InitMethodsAndChanges = InitMethods | ngOnChanges,
|
||||
All = InitMethodsAndChanges | ngDoCheck,
|
||||
}
|
||||
|
||||
function forEachMethod(methods: LifetimeMethods, cb: (method: LifetimeMethods) => void) {
|
||||
if (methods & LifetimeMethods.ngOnInit) cb(LifetimeMethods.ngOnInit);
|
||||
if (methods & LifetimeMethods.ngOnChanges) cb(LifetimeMethods.ngOnChanges);
|
||||
if (methods & LifetimeMethods.ngAfterContentInit) cb(LifetimeMethods.ngAfterContentInit);
|
||||
if (methods & LifetimeMethods.ngAfterViewInit) cb(LifetimeMethods.ngAfterViewInit);
|
||||
if (methods & LifetimeMethods.ngDoCheck) cb(LifetimeMethods.ngDoCheck);
|
||||
}
|
||||
|
||||
interface Options {
|
||||
childRecursion: LifetimeMethods;
|
||||
childThrows: LifetimeMethods;
|
||||
}
|
||||
|
||||
describe('calling init', () => {
|
||||
function initialize(options: Options) {
|
||||
@Component({selector: 'my-child', template: ''})
|
||||
class MyChild {
|
||||
private thrown = LifetimeMethods.None;
|
||||
|
||||
@Input() inp: boolean;
|
||||
@Output() outp = new EventEmitter<any>();
|
||||
|
||||
constructor() {}
|
||||
|
||||
ngDoCheck() { this.check(LifetimeMethods.ngDoCheck); }
|
||||
ngOnInit() { this.check(LifetimeMethods.ngOnInit); }
|
||||
ngOnChanges() { this.check(LifetimeMethods.ngOnChanges); }
|
||||
ngAfterViewInit() { this.check(LifetimeMethods.ngAfterViewInit); }
|
||||
ngAfterContentInit() { this.check(LifetimeMethods.ngAfterContentInit); }
|
||||
|
||||
private check(method: LifetimeMethods) {
|
||||
log(`MyChild::${LifetimeMethods[method]}()`);
|
||||
|
||||
if ((options.childRecursion & method) !== 0) {
|
||||
if (logged.length < 20) {
|
||||
this.outp.emit(null);
|
||||
} else {
|
||||
fail(`Unexpected MyChild::${LifetimeMethods[method]} recursion`);
|
||||
}
|
||||
}
|
||||
if ((options.childThrows & method) !== 0) {
|
||||
if ((this.thrown & method) === 0) {
|
||||
this.thrown |= method;
|
||||
log(`<THROW from MyChild::${LifetimeMethods[method]}>()`);
|
||||
throw new Error(`Throw from MyChild::${LifetimeMethods[method]}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: `<my-child [inp]='true' (outp)='onOutp()'></my-child>`
|
||||
})
|
||||
class MyComponent {
|
||||
constructor(private changeDetectionRef: ChangeDetectorRef) {}
|
||||
ngDoCheck() { this.check(LifetimeMethods.ngDoCheck); }
|
||||
ngOnInit() { this.check(LifetimeMethods.ngOnInit); }
|
||||
ngAfterViewInit() { this.check(LifetimeMethods.ngAfterViewInit); }
|
||||
ngAfterContentInit() { this.check(LifetimeMethods.ngAfterContentInit); }
|
||||
onOutp() {
|
||||
log('<RECURSION START>');
|
||||
this.changeDetectionRef.detectChanges();
|
||||
log('<RECURSION DONE>');
|
||||
}
|
||||
|
||||
private check(method: LifetimeMethods) {
|
||||
log(`MyComponent::${LifetimeMethods[method]}()`);
|
||||
}
|
||||
}
|
||||
|
||||
TestBed.configureTestingModule({declarations: [MyChild, MyComponent]});
|
||||
|
||||
return createCompFixture(`<my-component></my-component>`);
|
||||
}
|
||||
|
||||
function ensureOneInit(options: Options) {
|
||||
const ctx = initialize(options);
|
||||
|
||||
|
||||
const throws = options.childThrows != LifetimeMethods.None;
|
||||
if (throws) {
|
||||
log(`<CYCLE 0 START>`);
|
||||
expect(() => {
|
||||
// Expect child to throw.
|
||||
ctx.detectChanges();
|
||||
}).toThrow();
|
||||
log(`<CYCLE 0 END>`);
|
||||
log(`<CYCLE 1 START>`);
|
||||
}
|
||||
ctx.detectChanges();
|
||||
if (throws) log(`<CYCLE 1 DONE>`);
|
||||
expectOnceAndOnlyOnce('MyComponent::ngOnInit()');
|
||||
expectOnceAndOnlyOnce('MyChild::ngOnInit()');
|
||||
expectOnceAndOnlyOnce('MyComponent::ngAfterViewInit()');
|
||||
expectOnceAndOnlyOnce('MyComponent::ngAfterContentInit()');
|
||||
expectOnceAndOnlyOnce('MyChild::ngAfterViewInit()');
|
||||
expectOnceAndOnlyOnce('MyChild::ngAfterContentInit()');
|
||||
}
|
||||
|
||||
forEachMethod(LifetimeMethods.InitMethodsAndChanges, method => {
|
||||
it(`should ensure that init hooks are called once an only once with recursion in ${LifetimeMethods[method]} `,
|
||||
() => {
|
||||
// Ensure all the init methods are called once.
|
||||
ensureOneInit({childRecursion: method, childThrows: LifetimeMethods.None});
|
||||
});
|
||||
});
|
||||
forEachMethod(LifetimeMethods.All, method => {
|
||||
it(`should ensure that init hooks are called once an only once with a throw in ${LifetimeMethods[method]} `,
|
||||
() => {
|
||||
// Ensure all the init methods are called once.
|
||||
// the first cycle throws but the next cycle should complete the inits.
|
||||
ensureOneInit({childRecursion: LifetimeMethods.None, childThrows: method});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -11,12 +11,10 @@ import {CompileMetadataResolver} from '@angular/compiler/src/metadata_resolver';
|
||||
import {MockResourceLoader} from '@angular/compiler/testing/src/resource_loader_mock';
|
||||
import {Component, Directive, Injectable, NgModule, Pipe, Type} from '@angular/core';
|
||||
import {TestBed, async, getTestBed} from '@angular/core/testing';
|
||||
import {expect} from '@angular/platform-browser/testing/src/matchers';
|
||||
|
||||
export function main() {
|
||||
describe('Jit Summaries', () => {
|
||||
let instances: Map<any, Base>;
|
||||
let summaries: () => any[];
|
||||
|
||||
class SomeDep {}
|
||||
|
||||
@ -71,7 +69,7 @@ export function main() {
|
||||
TestBed.configureCompiler({providers: [{provide: ResourceLoader, useValue: resourceLoader}]});
|
||||
TestBed.configureTestingModule({imports: [SomeModule], providers: [SomeDep]});
|
||||
|
||||
let summariesPromise = TestBed.compileComponents().then(() => {
|
||||
TestBed.compileComponents().then(() => {
|
||||
const metadataResolver = TestBed.get(CompileMetadataResolver) as CompileMetadataResolver;
|
||||
const summaries = [
|
||||
metadataResolver.getNgModuleSummary(SomeModule),
|
||||
@ -85,12 +83,10 @@ export function main() {
|
||||
metadataResolver.getInjectableSummary(SomeService)
|
||||
];
|
||||
clearMetadata();
|
||||
TestBed.resetTestingModule();
|
||||
return () => summaries;
|
||||
resetTestEnvironmentWithSummaries(() => summaries);
|
||||
});
|
||||
|
||||
resourceLoader.flush();
|
||||
return summariesPromise;
|
||||
}
|
||||
|
||||
function setMetadata(resourceLoader: MockResourceLoader) {
|
||||
@ -127,14 +123,12 @@ export function main() {
|
||||
|
||||
beforeEach(async(() => {
|
||||
instances = new Map<any, any>();
|
||||
createSummaries().then(s => summaries = s);
|
||||
createSummaries();
|
||||
}));
|
||||
|
||||
afterEach(() => { resetTestEnvironmentWithSummaries(); });
|
||||
|
||||
it('should use directive metadata from summaries', () => {
|
||||
resetTestEnvironmentWithSummaries(summaries);
|
||||
|
||||
@Component({template: '<div someDir></div>'})
|
||||
class TestComp {
|
||||
}
|
||||
@ -146,8 +140,6 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should use pipe metadata from summaries', () => {
|
||||
resetTestEnvironmentWithSummaries(summaries);
|
||||
|
||||
@Component({template: '{{1 | somePipe}}'})
|
||||
class TestComp {
|
||||
}
|
||||
@ -158,8 +150,6 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should use Service metadata from summaries', () => {
|
||||
resetTestEnvironmentWithSummaries(summaries);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [SomeService, SomeDep],
|
||||
});
|
||||
@ -168,8 +158,6 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should use NgModule metadata from summaries', () => {
|
||||
resetTestEnvironmentWithSummaries(summaries);
|
||||
|
||||
TestBed
|
||||
.configureTestingModule(
|
||||
{providers: [SomeDep], declarations: [TestComp3], imports: [SomeModule]})
|
||||
@ -182,16 +170,12 @@ export function main() {
|
||||
});
|
||||
|
||||
it('should allow to create private components from imported NgModule summaries', () => {
|
||||
resetTestEnvironmentWithSummaries(summaries);
|
||||
|
||||
TestBed.configureTestingModule({providers: [SomeDep], imports: [SomeModule]})
|
||||
.createComponent(SomePrivateComponent);
|
||||
expectInstanceCreated(SomePrivateComponent);
|
||||
});
|
||||
|
||||
it('should throw when trying to mock a type with a summary', () => {
|
||||
resetTestEnvironmentWithSummaries(summaries);
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
expect(() => TestBed.overrideComponent(SomePrivateComponent, {add: {}}).compileComponents())
|
||||
.toThrowError(
|
||||
@ -206,47 +190,5 @@ export function main() {
|
||||
expect(() => TestBed.overrideModule(SomeModule, {add: {}}).compileComponents())
|
||||
.toThrowError('SomeModule was AOT compiled, so its metadata cannot be changed.');
|
||||
});
|
||||
|
||||
it('should allow to add summaries via configureTestingModule', () => {
|
||||
resetTestEnvironmentWithSummaries();
|
||||
|
||||
@Component({template: '<div someDir></div>'})
|
||||
class TestComp {
|
||||
}
|
||||
|
||||
TestBed
|
||||
.configureTestingModule({
|
||||
providers: [SomeDep],
|
||||
declarations: [TestComp, SomeDirective],
|
||||
aotSummaries: summaries
|
||||
})
|
||||
.createComponent(TestComp);
|
||||
expectInstanceCreated(SomeDirective);
|
||||
});
|
||||
|
||||
it('should allow to override a provider', () => {
|
||||
resetTestEnvironmentWithSummaries(summaries);
|
||||
|
||||
const overwrittenValue = {};
|
||||
|
||||
const fixture =
|
||||
TestBed.overrideProvider(SomeDep, {useFactory: () => overwrittenValue, deps: []})
|
||||
.configureTestingModule({providers: [SomeDep], imports: [SomeModule]})
|
||||
.createComponent<SomePublicComponent>(SomePublicComponent);
|
||||
|
||||
expect(fixture.componentInstance.dep).toBe(overwrittenValue);
|
||||
});
|
||||
|
||||
it('should allow to override a template', () => {
|
||||
resetTestEnvironmentWithSummaries(summaries);
|
||||
|
||||
TestBed.overrideTemplateUsingTestingModule(SomePublicComponent, 'overwritten');
|
||||
|
||||
const fixture = TestBed.configureTestingModule({providers: [SomeDep], imports: [SomeModule]})
|
||||
.createComponent(SomePublicComponent);
|
||||
expectInstanceCreated(SomePublicComponent);
|
||||
|
||||
expect(fixture.nativeElement).toHaveText('overwritten');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
@ -6,7 +6,7 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {ApplicationInitStatus, CompilerOptions, Component, Directive, InjectionToken, Injector, ModuleWithComponentFactories, NgModule, NgModuleFactory, NgModuleRef, NgZone, Optional, Pipe, PlatformRef, Provider, SchemaMetadata, SkipSelf, StaticProvider, Type, ɵDepFlags as DepFlags, ɵNodeFlags as NodeFlags, ɵclearOverrides as clearOverrides, ɵgetComponentViewDefinitionFactory as getComponentViewDefinitionFactory, ɵoverrideComponentView as overrideComponentView, ɵoverrideProvider as overrideProvider, ɵstringify as stringify} from '@angular/core';
|
||||
import {ApplicationInitStatus, CompilerOptions, Component, Directive, InjectionToken, Injector, ModuleWithComponentFactories, NgModule, NgModuleFactory, NgModuleRef, NgZone, Optional, Pipe, PlatformRef, Provider, SchemaMetadata, SkipSelf, Type, ɵDepFlags as DepFlags, ɵNodeFlags as NodeFlags, ɵclearProviderOverrides as clearProviderOverrides, ɵoverrideProvider as overrideProvider, ɵstringify as stringify} from '@angular/core';
|
||||
|
||||
import {AsyncTestCompleter} from './async_test_completer';
|
||||
import {ComponentFixture} from './component_fixture';
|
||||
@ -45,7 +45,6 @@ export type TestModuleMetadata = {
|
||||
declarations?: any[],
|
||||
imports?: any[],
|
||||
schemas?: Array<SchemaMetadata|any[]>,
|
||||
aotSummaries?: () => any[],
|
||||
};
|
||||
|
||||
/**
|
||||
@ -142,29 +141,15 @@ export class TestBed implements Injector {
|
||||
return TestBed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides the template of the given component, compiling the template
|
||||
* in the context of the TestingModule.
|
||||
*
|
||||
* Note: This works for JIT and AOTed components as well.
|
||||
*/
|
||||
static overrideTemplateUsingTestingModule(component: Type<any>, template: string):
|
||||
typeof TestBed {
|
||||
getTestBed().overrideTemplateUsingTestingModule(component, template);
|
||||
return TestBed;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Overwrites all providers for the given token with the given provider definition.
|
||||
*
|
||||
* Note: This works for JIT and AOTed components as well.
|
||||
*/
|
||||
static overrideProvider(token: any, provider: {
|
||||
useFactory: Function,
|
||||
deps: any[],
|
||||
}): typeof TestBed;
|
||||
static overrideProvider(token: any, provider: {useValue: any;}): typeof TestBed;
|
||||
}): void;
|
||||
static overrideProvider(token: any, provider: {useValue: any;}): void;
|
||||
static overrideProvider(token: any, provider: {
|
||||
useFactory?: Function,
|
||||
useValue?: any,
|
||||
@ -220,9 +205,7 @@ export class TestBed implements Injector {
|
||||
private _schemas: Array<SchemaMetadata|any[]> = [];
|
||||
private _activeFixtures: ComponentFixture<any>[] = [];
|
||||
|
||||
private _testEnvAotSummaries: () => any[] = () => [];
|
||||
private _aotSummaries: Array<() => any[]> = [];
|
||||
private _templateOverrides: Array<{component: Type<any>, templateOf: Type<any>}> = [];
|
||||
private _aotSummaries: () => any[] = () => [];
|
||||
|
||||
platform: PlatformRef = null !;
|
||||
|
||||
@ -249,7 +232,7 @@ export class TestBed implements Injector {
|
||||
this.platform = platform;
|
||||
this.ngModule = ngModule;
|
||||
if (aotSummaries) {
|
||||
this._testEnvAotSummaries = aotSummaries;
|
||||
this._aotSummaries = aotSummaries;
|
||||
}
|
||||
}
|
||||
|
||||
@ -262,13 +245,11 @@ export class TestBed implements Injector {
|
||||
this.resetTestingModule();
|
||||
this.platform = null !;
|
||||
this.ngModule = null !;
|
||||
this._testEnvAotSummaries = () => [];
|
||||
this._aotSummaries = () => [];
|
||||
}
|
||||
|
||||
resetTestingModule() {
|
||||
clearOverrides();
|
||||
this._aotSummaries = [];
|
||||
this._templateOverrides = [];
|
||||
clearProviderOverrides();
|
||||
this._compiler = null !;
|
||||
this._moduleOverrides = [];
|
||||
this._componentOverrides = [];
|
||||
@ -312,9 +293,6 @@ export class TestBed implements Injector {
|
||||
if (moduleDef.schemas) {
|
||||
this._schemas.push(...moduleDef.schemas);
|
||||
}
|
||||
if (moduleDef.aotSummaries) {
|
||||
this._aotSummaries.push(moduleDef.aotSummaries);
|
||||
}
|
||||
}
|
||||
|
||||
compileComponents(): Promise<any> {
|
||||
@ -349,11 +327,6 @@ export class TestBed implements Injector {
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const {component, templateOf} of this._templateOverrides) {
|
||||
const compFactory = this._compiler.getComponentFactory(templateOf);
|
||||
overrideComponentView(component, compFactory);
|
||||
}
|
||||
|
||||
const ngZone = new NgZone({enableLongStackTrace: true});
|
||||
const ngZoneInjector =
|
||||
Injector.create([{provide: NgZone, useValue: ngZone}], this.platform.injector);
|
||||
@ -366,8 +339,7 @@ export class TestBed implements Injector {
|
||||
|
||||
private _createCompilerAndModule(): Type<any> {
|
||||
const providers = this._providers.concat([{provide: TestBed, useValue: this}]);
|
||||
const declarations =
|
||||
[...this._declarations, ...this._templateOverrides.map(entry => entry.templateOf)];
|
||||
const declarations = this._declarations;
|
||||
const imports = [this.ngModule, this._imports];
|
||||
const schemas = this._schemas;
|
||||
|
||||
@ -378,9 +350,7 @@ export class TestBed implements Injector {
|
||||
const compilerFactory: TestingCompilerFactory =
|
||||
this.platform.injector.get(TestingCompilerFactory);
|
||||
this._compiler = compilerFactory.createTestingCompiler(this._compilerOptions);
|
||||
for (const summary of [this._testEnvAotSummaries, ...this._aotSummaries]) {
|
||||
this._compiler.loadAotSummaries(summary);
|
||||
}
|
||||
this._compiler.loadAotSummaries(this._aotSummaries);
|
||||
this._moduleOverrides.forEach((entry) => this._compiler.overrideModule(entry[0], entry[1]));
|
||||
this._componentOverrides.forEach(
|
||||
(entry) => this._compiler.overrideComponent(entry[0], entry[1]));
|
||||
@ -500,16 +470,6 @@ export class TestBed implements Injector {
|
||||
overrideProvider({token, flags, deps, value, deprecatedBehavior: deprecated});
|
||||
}
|
||||
|
||||
overrideTemplateUsingTestingModule(component: Type<any>, template: string) {
|
||||
this._assertNotInstantiated('overrideTemplateUsingTestingModule', 'override template');
|
||||
|
||||
@Component({selector: 'empty', template})
|
||||
class OverrideComponent {
|
||||
}
|
||||
|
||||
this._templateOverrides.push({component, templateOf: OverrideComponent});
|
||||
}
|
||||
|
||||
createComponent<T>(component: Type<T>): ComponentFixture<T> {
|
||||
this._initIfNeeded();
|
||||
const componentFactory = this._compiler.getComponentFactory(component);
|
||||
|
@ -135,7 +135,7 @@ ng1AppModule.component('ng1Hero', {
|
||||
// This AngularJS service will be "upgraded" to be used in Angular
|
||||
ng1AppModule.factory(
|
||||
'titleCase',
|
||||
(() => (value: string) => value.replace(/((^|\s)[a-z])/g, (_, c) => c.toUpperCase())) as any);
|
||||
() => (value: string) => value.replace(/((^|\s)[a-z])/g, (_, c) => c.toUpperCase()));
|
||||
// #enddocregion
|
||||
|
||||
// #docregion downgrade-ng2-heroes-service
|
||||
@ -154,20 +154,18 @@ ng1AppModule.component('exampleApp', {
|
||||
// We inject the "downgraded" HeroesService into this AngularJS component
|
||||
// (We don't need the `HeroesService` type for AngularJS DI - it just helps with TypeScript
|
||||
// compilation)
|
||||
controller:
|
||||
[
|
||||
'heroesService',
|
||||
function(heroesService: HeroesService) { this.heroesService = heroesService; }
|
||||
],
|
||||
// This template make use of the downgraded `ng2-heroes` component
|
||||
// Note that because its element is compiled by AngularJS we must use kebab-case attributes
|
||||
// for inputs and outputs
|
||||
template: `<link rel="stylesheet" href="./styles.css">
|
||||
controller: [
|
||||
'heroesService', function(heroesService: HeroesService) { this.heroesService = heroesService; }
|
||||
],
|
||||
// This template make use of the downgraded `ng2-heroes` component
|
||||
// Note that because its element is compiled by AngularJS we must use kebab-case attributes for
|
||||
// inputs and outputs
|
||||
template: `<link rel="stylesheet" href="./styles.css">
|
||||
<ng2-heroes [heroes]="$ctrl.heroesService.heroes" (add-hero)="$ctrl.heroesService.addHero()" (remove-hero)="$ctrl.heroesService.removeHero($event)">
|
||||
<h1>Heroes</h1>
|
||||
<p class="extra">There are {{ $ctrl.heroesService.heroes.length }} heroes.</p>
|
||||
</ng2-heroes>`
|
||||
} as any);
|
||||
});
|
||||
// #enddocregion
|
||||
// #enddocregion
|
||||
|
||||
|
@ -10,7 +10,7 @@ import {NgAnalyzedModules, StaticSymbol} from '@angular/compiler';
|
||||
import {DiagnosticTemplateInfo, getTemplateExpressionDiagnostics} from '@angular/compiler-cli/src/language_services';
|
||||
|
||||
import {AstResult} from './common';
|
||||
import {Declarations, Diagnostic, DiagnosticKind, DiagnosticMessageChain, Diagnostics, Span, TemplateSource} from './types';
|
||||
import {Declarations, Diagnostic, DiagnosticKind, Diagnostics, Span, TemplateSource} from './types';
|
||||
import {offsetSpan, spanOf} from './utils';
|
||||
|
||||
export interface AstProvider {
|
||||
@ -56,7 +56,7 @@ export function getDeclarationDiagnostics(
|
||||
|
||||
let directives: Set<StaticSymbol>|undefined = undefined;
|
||||
for (const declaration of declarations) {
|
||||
const report = (message: string | DiagnosticMessageChain, span?: Span) => {
|
||||
const report = (message: string, span?: Span) => {
|
||||
results.push(<Diagnostic>{
|
||||
kind: DiagnosticKind.Error,
|
||||
span: span || declaration.declarationSpan, message
|
||||
@ -71,12 +71,9 @@ export function getDeclarationDiagnostics(
|
||||
report(
|
||||
`Component '${declaration.type.name}' is not included in a module and will not be available inside a template. Consider adding it to a NgModule declaration`);
|
||||
}
|
||||
const {template, templateUrl} = declaration.metadata.template !;
|
||||
if (template === null && !templateUrl) {
|
||||
report(`Component '${declaration.type.name}' must have a template or templateUrl`);
|
||||
} else if (template && templateUrl) {
|
||||
report(
|
||||
`Component '${declaration.type.name}' must not have both template and templateUrl`);
|
||||
if (!declaration.metadata.template !.template &&
|
||||
!declaration.metadata.template !.templateUrl) {
|
||||
report(`Component ${declaration.type.name} must have a template or templateUrl`);
|
||||
}
|
||||
} else {
|
||||
if (!directives) {
|
||||
|
@ -9,7 +9,7 @@
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {createLanguageService} from './language_service';
|
||||
import {Completion, Diagnostic, DiagnosticMessageChain, LanguageService, LanguageServiceHost} from './types';
|
||||
import {Completion, Diagnostic, LanguageService, LanguageServiceHost} from './types';
|
||||
import {TypeScriptServiceHost} from './typescript_host';
|
||||
|
||||
const projectHostMap = new WeakMap<any, TypeScriptServiceHost>();
|
||||
@ -179,31 +179,7 @@ export function create(info: any /* ts.server.PluginCreateInfo */): ts.LanguageS
|
||||
}
|
||||
|
||||
function completionToEntry(c: Completion): ts.CompletionEntry {
|
||||
return {
|
||||
// TODO: remove any and fix type error.
|
||||
kind: c.kind as any,
|
||||
name: c.name,
|
||||
sortText: c.sort,
|
||||
kindModifiers: ''
|
||||
};
|
||||
}
|
||||
|
||||
function diagnosticChainToDiagnosticChain(chain: DiagnosticMessageChain):
|
||||
ts.DiagnosticMessageChain {
|
||||
return {
|
||||
messageText: chain.message,
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
code: 0,
|
||||
next: chain.next ? diagnosticChainToDiagnosticChain(chain.next) : undefined
|
||||
};
|
||||
}
|
||||
|
||||
function diagnosticMessageToDiagnosticMessageText(message: string | DiagnosticMessageChain):
|
||||
string|ts.DiagnosticMessageChain {
|
||||
if (typeof message === 'string') {
|
||||
return message;
|
||||
}
|
||||
return diagnosticChainToDiagnosticChain(message);
|
||||
return {kind: c.kind, name: c.name, sortText: c.sort, kindModifiers: ''};
|
||||
}
|
||||
|
||||
function diagnosticToDiagnostic(d: Diagnostic, file: ts.SourceFile): ts.Diagnostic {
|
||||
@ -211,7 +187,7 @@ export function create(info: any /* ts.server.PluginCreateInfo */): ts.LanguageS
|
||||
file,
|
||||
start: d.span.start,
|
||||
length: d.span.end - d.span.start,
|
||||
messageText: diagnosticMessageToDiagnosticMessageText(d.message),
|
||||
messageText: d.message,
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
code: 0,
|
||||
source: 'ng'
|
||||
@ -318,10 +294,9 @@ export function create(info: any /* ts.server.PluginCreateInfo */): ts.LanguageS
|
||||
fileName: loc.fileName,
|
||||
textSpan: {start: loc.span.start, length: loc.span.end - loc.span.start},
|
||||
name: '',
|
||||
// TODO: remove any and fix type error.
|
||||
kind: 'definition' as any,
|
||||
kind: 'definition',
|
||||
containerName: loc.fileName,
|
||||
containerKind: 'file' as any,
|
||||
containerKind: 'file'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -81,7 +81,7 @@ export type TemplateSources = TemplateSource[] | undefined;
|
||||
/**
|
||||
* Error information found getting declaration information
|
||||
*
|
||||
* A host type; see `LanguageServiceHost`.
|
||||
* A host type; see `LanagueServiceHost`.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
@ -92,10 +92,9 @@ export interface DeclarationError {
|
||||
readonly span: Span;
|
||||
|
||||
/**
|
||||
* The message to display describing the error or a chain
|
||||
* of messages.
|
||||
* The message to display describing the error.
|
||||
*/
|
||||
readonly message: string|DiagnosticMessageChain;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -256,28 +255,6 @@ export enum DiagnosticKind {
|
||||
Warning,
|
||||
}
|
||||
|
||||
/**
|
||||
* A template diagnostics message chain. This is similar to the TypeScript
|
||||
* DiagnosticMessageChain. The messages are intended to be formatted as separate
|
||||
* sentence fragments and indented.
|
||||
*
|
||||
* For compatiblity previous implementation, the values are expected to override
|
||||
* toString() to return a formatted message.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
export interface DiagnosticMessageChain {
|
||||
/**
|
||||
* The text of the diagnostic message to display.
|
||||
*/
|
||||
message: string;
|
||||
|
||||
/**
|
||||
* The next message in the chain.
|
||||
*/
|
||||
next?: DiagnosticMessageChain;
|
||||
}
|
||||
|
||||
/**
|
||||
* An template diagnostic message to display.
|
||||
*
|
||||
@ -295,9 +272,9 @@ export interface Diagnostic {
|
||||
span: Span;
|
||||
|
||||
/**
|
||||
* The text of the diagnostic message to display or a chain of messages.
|
||||
* The text of the diagnostic message to display.
|
||||
*/
|
||||
message: string|DiagnosticMessageChain;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -6,7 +6,7 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {AotSummaryResolver, CompileMetadataResolver, CompilerConfig, DEFAULT_INTERPOLATION_CONFIG, DirectiveNormalizer, DirectiveResolver, DomElementSchemaRegistry, FormattedError, FormattedMessageChain, HtmlParser, InterpolationConfig, JitSummaryResolver, NgAnalyzedModules, NgModuleResolver, ParseTreeResult, PipeResolver, ResourceLoader, StaticReflector, StaticSymbol, StaticSymbolCache, StaticSymbolResolver, SummaryResolver, analyzeNgModules, createOfflineCompileUrlResolver, isFormattedError} from '@angular/compiler';
|
||||
import {AotSummaryResolver, CompileMetadataResolver, CompilerConfig, DEFAULT_INTERPOLATION_CONFIG, DirectiveNormalizer, DirectiveResolver, DomElementSchemaRegistry, HtmlParser, InterpolationConfig, JitSummaryResolver, NgAnalyzedModules, NgModuleResolver, ParseTreeResult, PipeResolver, ResourceLoader, StaticReflector, StaticSymbol, StaticSymbolCache, StaticSymbolResolver, SummaryResolver, analyzeNgModules, createOfflineCompileUrlResolver} from '@angular/compiler';
|
||||
import {CompilerOptions, getClassMembersFromDeclaration, getPipesTable, getSymbolQuery} from '@angular/compiler-cli/src/language_services';
|
||||
import {ViewEncapsulation, ɵConsole as Console} from '@angular/core';
|
||||
import * as fs from 'fs';
|
||||
@ -15,11 +15,10 @@ import * as ts from 'typescript';
|
||||
|
||||
import {createLanguageService} from './language_service';
|
||||
import {ReflectorHost} from './reflector_host';
|
||||
import {BuiltinType, Declaration, DeclarationError, DeclarationKind, Declarations, Definition, DiagnosticMessageChain, LanguageService, LanguageServiceHost, PipeInfo, Pipes, Signature, Span, Symbol, SymbolDeclaration, SymbolQuery, SymbolTable, TemplateSource, TemplateSources} from './types';
|
||||
import {BuiltinType, Declaration, DeclarationError, DeclarationKind, Declarations, Definition, LanguageService, LanguageServiceHost, PipeInfo, Pipes, Signature, Span, Symbol, SymbolDeclaration, SymbolQuery, SymbolTable, TemplateSource, TemplateSources} from './types';
|
||||
import {isTypescriptVersion} from './utils';
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Create a `LanguageServiceHost`
|
||||
*/
|
||||
@ -147,19 +146,11 @@ export class TypeScriptServiceHost implements LanguageServiceHost {
|
||||
private ensureAnalyzedModules(): NgAnalyzedModules {
|
||||
let analyzedModules = this.analyzedModules;
|
||||
if (!analyzedModules) {
|
||||
if (this.host.getScriptFileNames().length === 0) {
|
||||
analyzedModules = {
|
||||
files: [],
|
||||
ngModuleByPipeOrDirective: new Map(),
|
||||
ngModules: [],
|
||||
};
|
||||
} else {
|
||||
const analyzeHost = {isSourceFile(filePath: string) { return true; }};
|
||||
const programFiles = this.program.getSourceFiles().map(sf => sf.fileName);
|
||||
analyzedModules =
|
||||
analyzeNgModules(programFiles, analyzeHost, this.staticSymbolResolver, this.resolver);
|
||||
}
|
||||
this.analyzedModules = analyzedModules;
|
||||
const analyzeHost = {isSourceFile(filePath: string) { return true; }};
|
||||
const programFiles = this.program.getSourceFiles().map(sf => sf.fileName);
|
||||
|
||||
analyzedModules = this.analyzedModules =
|
||||
analyzeNgModules(programFiles, analyzeHost, this.staticSymbolResolver, this.resolver);
|
||||
}
|
||||
return analyzedModules;
|
||||
}
|
||||
@ -366,11 +357,7 @@ export class TypeScriptServiceHost implements LanguageServiceHost {
|
||||
if (!result) {
|
||||
if (!this.context) {
|
||||
// Make up a context by finding the first script and using that as the base dir.
|
||||
const scriptFileNames = this.host.getScriptFileNames();
|
||||
if (0 === scriptFileNames.length) {
|
||||
throw new Error('Internal error: no script file names found');
|
||||
}
|
||||
this.context = scriptFileNames[0];
|
||||
this.context = this.host.getScriptFileNames()[0];
|
||||
}
|
||||
|
||||
// Use the file context's directory as the base directory.
|
||||
@ -389,9 +376,6 @@ export class TypeScriptServiceHost implements LanguageServiceHost {
|
||||
if (compilerOptions && compilerOptions.baseUrl) {
|
||||
options.baseUrl = compilerOptions.baseUrl;
|
||||
}
|
||||
if (compilerOptions && compilerOptions.paths) {
|
||||
options.paths = compilerOptions.paths;
|
||||
}
|
||||
result = this._reflectorHost =
|
||||
new ReflectorHost(() => this.tsService.getProgram(), this.host, options);
|
||||
}
|
||||
@ -507,13 +491,7 @@ export class TypeScriptServiceHost implements LanguageServiceHost {
|
||||
private getCollectedErrors(defaultSpan: Span, sourceFile: ts.SourceFile): DeclarationError[] {
|
||||
const errors = (this.collectedErrors && this.collectedErrors.get(sourceFile.fileName));
|
||||
return (errors && errors.map((e: any) => {
|
||||
const line = e.line || (e.position && e.position.line);
|
||||
const column = e.column || (e.position && e.position.column);
|
||||
const span = spanAt(sourceFile, line, column) || defaultSpan;
|
||||
if (isFormattedError(e)) {
|
||||
return errorToDiagnosticWithChain(e, span);
|
||||
}
|
||||
return {message: e.message, span};
|
||||
return {message: e.message, span: spanAt(sourceFile, e.line, e.column) || defaultSpan};
|
||||
})) ||
|
||||
[];
|
||||
}
|
||||
@ -618,20 +596,3 @@ function spanAt(sourceFile: ts.SourceFile, line: number, column: number): Span|u
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function chainedMessage(chain: DiagnosticMessageChain, indent = ''): string {
|
||||
return indent + chain.message + (chain.next ? chainedMessage(chain.next, indent + ' ') : '');
|
||||
}
|
||||
|
||||
class DiagnosticMessageChainImpl implements DiagnosticMessageChain {
|
||||
constructor(public message: string, public next?: DiagnosticMessageChain) {}
|
||||
toString(): string { return chainedMessage(this); }
|
||||
}
|
||||
|
||||
function convertChain(chain: FormattedMessageChain): DiagnosticMessageChain {
|
||||
return {message: chain.message, next: chain.next ? convertChain(chain.next) : undefined};
|
||||
}
|
||||
|
||||
function errorToDiagnosticWithChain(error: FormattedError, span: Span): DeclarationError {
|
||||
return {message: error.chain ? convertChain(error.chain) : error.message, span};
|
||||
}
|
@ -160,33 +160,6 @@ export class MyComponent {
|
||||
|
||||
});
|
||||
|
||||
it('should respect paths configuration', () => {
|
||||
mockHost.overrideOptions(options => {
|
||||
options.baseUrl = '/app';
|
||||
options.paths = {'bar/*': ['foo/bar/*']};
|
||||
return options;
|
||||
});
|
||||
mockHost.addScript('/app/foo/bar/shared.ts', `
|
||||
export interface Node {
|
||||
children: Node[];
|
||||
}
|
||||
`);
|
||||
mockHost.addScript('/app/my.component.ts', `
|
||||
import { Component } from '@angular/core';
|
||||
import { Node } from 'bar/shared';
|
||||
|
||||
@Component({
|
||||
selector: 'my-component',
|
||||
template: '{{tree.~{tree} }}'
|
||||
})
|
||||
export class MyComponent {
|
||||
tree: Node;
|
||||
}
|
||||
`);
|
||||
ngHost.updateAnalyzedModules();
|
||||
contains('/app/my.component.ts', 'tree', 'children');
|
||||
});
|
||||
|
||||
function addCode(code: string, cb: (fileName: string, content?: string) => void) {
|
||||
const fileName = '/app/app.component.ts';
|
||||
const originalContent = mockHost.getFileContent(fileName);
|
||||
|
@ -13,7 +13,7 @@ import {Diagnostics} from '../src/types';
|
||||
import {TypeScriptServiceHost} from '../src/typescript_host';
|
||||
|
||||
import {toh} from './test_data';
|
||||
import {MockTypescriptHost, diagnosticMessageContains, findDiagnostic, includeDiagnostic, noDiagnostics} from './test_utils';
|
||||
import {MockTypescriptHost, includeDiagnostic, noDiagnostics} from './test_utils';
|
||||
|
||||
describe('diagnostics', () => {
|
||||
let documentRegistry = ts.createDocumentRegistry();
|
||||
@ -123,8 +123,7 @@ describe('diagnostics', () => {
|
||||
addCode(code, (fileName, content) => {
|
||||
const diagnostics = ngService.getDiagnostics(fileName);
|
||||
includeDiagnostic(
|
||||
diagnostics !, 'Function expressions are not supported in decorators', '() => \'foo\'',
|
||||
content);
|
||||
diagnostics !, 'Function calls are not supported.', '() => \'foo\'', content);
|
||||
});
|
||||
});
|
||||
|
||||
@ -169,28 +168,13 @@ describe('diagnostics', () => {
|
||||
const code =
|
||||
` @Component({template: '<p> Using an invalid pipe {{data | dat}} </p>'}) export class MyComponent { data = 'some data'; }`;
|
||||
addCode(code, fileName => {
|
||||
const diagnostic = findDiagnostic(ngService.getDiagnostics(fileName) !, 'pipe') !;
|
||||
const diagnostic =
|
||||
ngService.getDiagnostics(fileName) !.filter(d => d.message.indexOf('pipe') > 0)[0];
|
||||
expect(diagnostic).not.toBeUndefined();
|
||||
expect(diagnostic.span.end - diagnostic.span.start).toBeLessThan(11);
|
||||
});
|
||||
});
|
||||
|
||||
// Issue #19406
|
||||
it('should allow empty template', () => {
|
||||
const appComponent = `
|
||||
import { Component } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
template : '',
|
||||
})
|
||||
export class AppComponent {}
|
||||
`;
|
||||
const fileName = '/app/app.component.ts';
|
||||
mockHost.override(fileName, appComponent);
|
||||
const diagnostics = ngService.getDiagnostics(fileName);
|
||||
expect(diagnostics).toEqual([]);
|
||||
});
|
||||
|
||||
// Issue #15460
|
||||
it('should be able to find members defined on an ancestor type', () => {
|
||||
const app_component = `
|
||||
@ -232,8 +216,8 @@ describe('diagnostics', () => {
|
||||
`,
|
||||
fileName => {
|
||||
const diagnostics = ngService.getDiagnostics(fileName) !;
|
||||
const expected = findDiagnostic(diagnostics, 'Invalid providers for');
|
||||
const notExpected = findDiagnostic(diagnostics, 'Cannot read property');
|
||||
const expected = diagnostics.find(d => d.message.startsWith('Invalid providers for'));
|
||||
const notExpected = diagnostics.find(d => d.message.startsWith('Cannot read property'));
|
||||
expect(expected).toBeDefined();
|
||||
expect(notExpected).toBeUndefined();
|
||||
});
|
||||
@ -371,12 +355,12 @@ describe('diagnostics', () => {
|
||||
expect(diagnostics.length).toBe(1);
|
||||
if (diagnostics.length > 1) {
|
||||
for (const diagnostic of diagnostics) {
|
||||
if (diagnosticMessageContains(diagnostic.message, 'MyComponent')) continue;
|
||||
if (diagnostic.message.indexOf('MyComponent') >= 0) continue;
|
||||
fail(`(${diagnostic.span.start}:${diagnostic.span.end}): ${diagnostic.message}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
expect(diagnosticMessageContains(diagnostics[0].message, 'MyComponent')).toBeTruthy();
|
||||
expect(diagnostics[0].message.indexOf('MyComponent') >= 0).toBeTruthy();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
@ -10,7 +10,7 @@ import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {Diagnostic, DiagnosticMessageChain, Diagnostics, Span} from '../src/types';
|
||||
import {Diagnostic, Diagnostics, Span} from '../src/types';
|
||||
|
||||
export type MockData = string | MockDirectory;
|
||||
|
||||
@ -317,25 +317,6 @@ export function noDiagnostics(diagnostics: Diagnostics) {
|
||||
}
|
||||
}
|
||||
|
||||
export function diagnosticMessageContains(
|
||||
message: string | DiagnosticMessageChain, messageFragment: string): boolean {
|
||||
if (typeof message == 'string') {
|
||||
return message.indexOf(messageFragment) >= 0;
|
||||
}
|
||||
if (message.message.indexOf(messageFragment) >= 0) {
|
||||
return true;
|
||||
}
|
||||
if (message.next) {
|
||||
return diagnosticMessageContains(message.next, messageFragment);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function findDiagnostic(diagnostics: Diagnostic[], messageFragment: string): Diagnostic|
|
||||
undefined {
|
||||
return diagnostics.find(d => diagnosticMessageContains(d.message, messageFragment));
|
||||
}
|
||||
|
||||
export function includeDiagnostic(
|
||||
diagnostics: Diagnostics, message: string, text?: string, len?: string): void;
|
||||
export function includeDiagnostic(
|
||||
@ -343,18 +324,14 @@ export function includeDiagnostic(
|
||||
export function includeDiagnostic(diagnostics: Diagnostics, message: string, p1?: any, p2?: any) {
|
||||
expect(diagnostics).toBeDefined();
|
||||
if (diagnostics) {
|
||||
const diagnostic = findDiagnostic(diagnostics, message);
|
||||
expect(diagnostic).toBeDefined(`no diagnostic contains '${message}`);
|
||||
const diagnostic = diagnostics.find(d => d.message.indexOf(message) >= 0) as Diagnostic;
|
||||
expect(diagnostic).toBeDefined();
|
||||
if (diagnostic && p1 != null) {
|
||||
const at = typeof p1 === 'number' ? p1 : p2.indexOf(p1);
|
||||
const len = typeof p2 === 'number' ? p2 : p1.length;
|
||||
expect(diagnostic.span.start)
|
||||
.toEqual(
|
||||
at,
|
||||
`expected message '${message}' was reported at ${diagnostic.span.start} but should be ${at}`);
|
||||
expect(diagnostic.span.start).toEqual(at);
|
||||
if (len != null) {
|
||||
expect(diagnostic.span.end - diagnostic.span.start)
|
||||
.toEqual(len, `expected '${message}'s span length to be ${len}`);
|
||||
expect(diagnostic.span.end - diagnostic.span.start).toEqual(len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -39,11 +39,4 @@ describe('completions', () => {
|
||||
ngHost = new TypeScriptServiceHost(host, service);
|
||||
expect(ngHost.getAnalyzedModules()).toBeDefined();
|
||||
});
|
||||
|
||||
it('should not throw if there is no script names', () => {
|
||||
host = new MockTypescriptHost([], toh);
|
||||
service = ts.createLanguageService(host);
|
||||
ngHost = new TypeScriptServiceHost(host, service);
|
||||
expect(() => ngHost.getAnalyzedModules()).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
@ -150,13 +150,8 @@ export const COMPILER_PROVIDERS = <StaticProvider[]>[
|
||||
{ provide: NgModuleResolver, deps: [CompileReflector]},
|
||||
];
|
||||
|
||||
/**
|
||||
* @experimental
|
||||
*/
|
||||
export class JitCompilerFactory implements CompilerFactory {
|
||||
private _defaultOptions: CompilerOptions[];
|
||||
|
||||
/* @internal */
|
||||
constructor(defaultOptions: CompilerOptions[]) {
|
||||
const compilerOptions: CompilerOptions = {
|
||||
useJit: true,
|
||||
|
@ -15,7 +15,6 @@ import {CachedResourceLoader} from './resource_loader/resource_loader_cache';
|
||||
|
||||
export * from './private_export';
|
||||
export {VERSION} from './version';
|
||||
export {JitCompilerFactory} from './compiler_factory';
|
||||
|
||||
/**
|
||||
* @experimental
|
||||
|
@ -712,60 +712,6 @@ export function main() {
|
||||
});
|
||||
});
|
||||
|
||||
describe('overrideTemplateUsingTestingModule', () => {
|
||||
it('should compile the template in the context of the testing module', () => {
|
||||
@Component({selector: 'comp', template: 'a'})
|
||||
class MyComponent {
|
||||
prop = 'some prop';
|
||||
}
|
||||
|
||||
let testDir: TestDir|undefined;
|
||||
|
||||
@Directive({selector: '[test]'})
|
||||
class TestDir {
|
||||
constructor() { testDir = this; }
|
||||
|
||||
@Input('test')
|
||||
test: string;
|
||||
}
|
||||
|
||||
TestBed.overrideTemplateUsingTestingModule(
|
||||
MyComponent, '<div [test]="prop">Hello world!</div>');
|
||||
|
||||
const fixture = TestBed.configureTestingModule({declarations: [MyComponent, TestDir]})
|
||||
.createComponent(MyComponent);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement).toHaveText('Hello world!');
|
||||
expect(testDir).toBeAnInstanceOf(TestDir);
|
||||
expect(testDir !.test).toBe('some prop');
|
||||
});
|
||||
|
||||
it('should throw if the TestBed is already created', () => {
|
||||
@Component({selector: 'comp', template: 'a'})
|
||||
class MyComponent {
|
||||
}
|
||||
|
||||
TestBed.get(Injector);
|
||||
|
||||
expect(() => TestBed.overrideTemplateUsingTestingModule(MyComponent, 'b'))
|
||||
.toThrowError(
|
||||
/Cannot override template when the test module has already been instantiated/);
|
||||
});
|
||||
|
||||
it('should reset overrides when the testing module is resetted', () => {
|
||||
@Component({selector: 'comp', template: 'a'})
|
||||
class MyComponent {
|
||||
}
|
||||
|
||||
TestBed.overrideTemplateUsingTestingModule(MyComponent, 'b');
|
||||
|
||||
const fixture = TestBed.resetTestingModule()
|
||||
.configureTestingModule({declarations: [MyComponent]})
|
||||
.createComponent(MyComponent);
|
||||
expect(fixture.nativeElement).toHaveText('a');
|
||||
});
|
||||
});
|
||||
|
||||
describe('setting up the compiler', () => {
|
||||
|
||||
describe('providers', () => {
|
||||
|
@ -592,7 +592,7 @@ export function main() {
|
||||
platform.bootstrapModule(ExampleModule).then(ref => {
|
||||
const mock = ref.injector.get(MockBackend);
|
||||
const http = ref.injector.get(Http);
|
||||
ref.injector.get<NgZone>(NgZone).run(() => {
|
||||
ref.injector.get(NgZone).run(() => {
|
||||
NgZone.assertInAngularZone();
|
||||
mock.connections.subscribe((mc: MockConnection) => {
|
||||
NgZone.assertInAngularZone();
|
||||
@ -612,11 +612,11 @@ export function main() {
|
||||
platform.bootstrapModule(ExampleModule).then(ref => {
|
||||
const mock = ref.injector.get(MockBackend);
|
||||
const http = ref.injector.get(Http);
|
||||
expect(ref.injector.get<NgZone>(NgZone).hasPendingMacrotasks).toBeFalsy();
|
||||
ref.injector.get<NgZone>(NgZone).run(() => {
|
||||
expect(ref.injector.get(NgZone).hasPendingMacrotasks).toBeFalsy();
|
||||
ref.injector.get(NgZone).run(() => {
|
||||
NgZone.assertInAngularZone();
|
||||
mock.connections.subscribe((mc: MockConnection) => {
|
||||
expect(ref.injector.get<NgZone>(NgZone).hasPendingMacrotasks).toBeTruthy();
|
||||
expect(ref.injector.get(NgZone).hasPendingMacrotasks).toBeTruthy();
|
||||
mc.mockRespond(new Response(new ResponseOptions({body: 'success!', status: 200})));
|
||||
});
|
||||
http.get('http://localhost/testing').subscribe(resp => {
|
||||
@ -631,11 +631,11 @@ export function main() {
|
||||
platform.bootstrapModule(HttpBeforeExampleModule).then(ref => {
|
||||
const mock = ref.injector.get(MockBackend);
|
||||
const http = ref.injector.get(Http);
|
||||
expect(ref.injector.get<NgZone>(NgZone).hasPendingMacrotasks).toBeFalsy();
|
||||
ref.injector.get<NgZone>(NgZone).run(() => {
|
||||
expect(ref.injector.get(NgZone).hasPendingMacrotasks).toBeFalsy();
|
||||
ref.injector.get(NgZone).run(() => {
|
||||
NgZone.assertInAngularZone();
|
||||
mock.connections.subscribe((mc: MockConnection) => {
|
||||
expect(ref.injector.get<NgZone>(NgZone).hasPendingMacrotasks).toBeTruthy();
|
||||
expect(ref.injector.get(NgZone).hasPendingMacrotasks).toBeTruthy();
|
||||
mc.mockRespond(new Response(new ResponseOptions({body: 'success!', status: 200})));
|
||||
});
|
||||
http.get('http://localhost/testing').subscribe(resp => {
|
||||
@ -650,11 +650,11 @@ export function main() {
|
||||
platform.bootstrapModule(HttpAfterExampleModule).then(ref => {
|
||||
const mock = ref.injector.get(MockBackend);
|
||||
const http = ref.injector.get(Http);
|
||||
expect(ref.injector.get<NgZone>(NgZone).hasPendingMacrotasks).toBeFalsy();
|
||||
ref.injector.get<NgZone>(NgZone).run(() => {
|
||||
expect(ref.injector.get(NgZone).hasPendingMacrotasks).toBeFalsy();
|
||||
ref.injector.get(NgZone).run(() => {
|
||||
NgZone.assertInAngularZone();
|
||||
mock.connections.subscribe((mc: MockConnection) => {
|
||||
expect(ref.injector.get<NgZone>(NgZone).hasPendingMacrotasks).toBeTruthy();
|
||||
expect(ref.injector.get(NgZone).hasPendingMacrotasks).toBeTruthy();
|
||||
mc.mockRespond(new Response(new ResponseOptions({body: 'success!', status: 200})));
|
||||
});
|
||||
http.get('http://localhost/testing').subscribe(resp => {
|
||||
@ -688,7 +688,7 @@ export function main() {
|
||||
platform.bootstrapModule(HttpClientExmapleModule).then(ref => {
|
||||
const mock = ref.injector.get(HttpTestingController) as HttpTestingController;
|
||||
const http = ref.injector.get(HttpClient);
|
||||
ref.injector.get<NgZone>(NgZone).run(() => {
|
||||
ref.injector.get(NgZone).run(() => {
|
||||
http.get('http://localhost/testing').subscribe(body => {
|
||||
NgZone.assertInAngularZone();
|
||||
expect(body).toEqual('success!');
|
||||
@ -703,13 +703,13 @@ export function main() {
|
||||
platform.bootstrapModule(HttpClientExmapleModule).then(ref => {
|
||||
const mock = ref.injector.get(HttpTestingController) as HttpTestingController;
|
||||
const http = ref.injector.get(HttpClient);
|
||||
ref.injector.get<NgZone>(NgZone).run(() => {
|
||||
ref.injector.get(NgZone).run(() => {
|
||||
http.get('http://localhost/testing').subscribe(body => {
|
||||
expect(body).toEqual('success!');
|
||||
});
|
||||
expect(ref.injector.get<NgZone>(NgZone).hasPendingMacrotasks).toBeTruthy();
|
||||
expect(ref.injector.get(NgZone).hasPendingMacrotasks).toBeTruthy();
|
||||
mock.expectOne('http://localhost/testing').flush('success!');
|
||||
expect(ref.injector.get<NgZone>(NgZone).hasPendingMacrotasks).toBeFalsy();
|
||||
expect(ref.injector.get(NgZone).hasPendingMacrotasks).toBeFalsy();
|
||||
});
|
||||
});
|
||||
}));
|
||||
|
@ -32,7 +32,7 @@ export const WORKER_UI_LOCATION_PROVIDERS = <StaticProvider[]>[
|
||||
|
||||
function initUiLocation(injector: Injector): () => void {
|
||||
return () => {
|
||||
const zone = injector.get<NgZone>(NgZone);
|
||||
const zone = injector.get(NgZone);
|
||||
|
||||
zone.runGuarded(() => injector.get(MessageBasedPlatformLocation).start());
|
||||
};
|
||||
|
@ -112,7 +112,7 @@ export const _WORKER_UI_PLATFORM_PROVIDERS: StaticProvider[] = [
|
||||
|
||||
function initializeGenericWorkerRenderer(injector: Injector) {
|
||||
const bus = injector.get(MessageBus);
|
||||
const zone = injector.get<NgZone>(NgZone);
|
||||
const zone = injector.get(NgZone);
|
||||
bus.attachToZone(zone);
|
||||
|
||||
// initialize message services after the bus has been created
|
||||
|
@ -43,12 +43,12 @@ declare let Zone: any;
|
||||
*/
|
||||
export interface NavigationExtras {
|
||||
/**
|
||||
* Enables relative navigation from the current ActivatedRoute.
|
||||
*
|
||||
* Configuration:
|
||||
*
|
||||
* ```
|
||||
* [{
|
||||
* Enables relative navigation from the current ActivatedRoute.
|
||||
*
|
||||
* Configuration:
|
||||
*
|
||||
* ```
|
||||
* [{
|
||||
* path: 'parent',
|
||||
* component: ParentComponent,
|
||||
* children: [{
|
||||
@ -59,92 +59,92 @@ export interface NavigationExtras {
|
||||
* component: ChildComponent
|
||||
* }]
|
||||
* }]
|
||||
* ```
|
||||
*
|
||||
* Navigate to list route from child route:
|
||||
*
|
||||
* ```
|
||||
* @Component({...})
|
||||
* class ChildComponent {
|
||||
* ```
|
||||
*
|
||||
* Navigate to list route from child route:
|
||||
*
|
||||
* ```
|
||||
* @Component({...})
|
||||
* class ChildComponent {
|
||||
* constructor(private router: Router, private route: ActivatedRoute) {}
|
||||
*
|
||||
* go() {
|
||||
* this.router.navigate(['../list'], { relativeTo: this.route });
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
* ```
|
||||
*/
|
||||
relativeTo?: ActivatedRoute|null;
|
||||
|
||||
/**
|
||||
* Sets query parameters to the URL.
|
||||
*
|
||||
* ```
|
||||
* // Navigate to /results?page=1
|
||||
* this.router.navigate(['/results'], { queryParams: { page: 1 } });
|
||||
* ```
|
||||
*/
|
||||
* Sets query parameters to the URL.
|
||||
*
|
||||
* ```
|
||||
* // Navigate to /results?page=1
|
||||
* this.router.navigate(['/results'], { queryParams: { page: 1 } });
|
||||
* ```
|
||||
*/
|
||||
queryParams?: Params|null;
|
||||
|
||||
/**
|
||||
* Sets the hash fragment for the URL.
|
||||
*
|
||||
* ```
|
||||
* // Navigate to /results#top
|
||||
* this.router.navigate(['/results'], { fragment: 'top' });
|
||||
* ```
|
||||
*/
|
||||
* Sets the hash fragment for the URL.
|
||||
*
|
||||
* ```
|
||||
* // Navigate to /results#top
|
||||
* this.router.navigate(['/results'], { fragment: 'top' });
|
||||
* ```
|
||||
*/
|
||||
fragment?: string;
|
||||
|
||||
/**
|
||||
* Preserves the query parameters for the next navigation.
|
||||
*
|
||||
* deprecated, use `queryParamsHandling` instead
|
||||
*
|
||||
* ```
|
||||
* // Preserve query params from /results?page=1 to /view?page=1
|
||||
* this.router.navigate(['/view'], { preserveQueryParams: true });
|
||||
* ```
|
||||
*
|
||||
* @deprecated since v4
|
||||
*/
|
||||
* Preserves the query parameters for the next navigation.
|
||||
*
|
||||
* deprecated, use `queryParamsHandling` instead
|
||||
*
|
||||
* ```
|
||||
* // Preserve query params from /results?page=1 to /view?page=1
|
||||
* this.router.navigate(['/view'], { preserveQueryParams: true });
|
||||
* ```
|
||||
*
|
||||
* @deprecated since v4
|
||||
*/
|
||||
preserveQueryParams?: boolean;
|
||||
|
||||
/**
|
||||
* config strategy to handle the query parameters for the next navigation.
|
||||
*
|
||||
* ```
|
||||
* // from /results?page=1 to /view?page=1&page=2
|
||||
* this.router.navigate(['/view'], { queryParams: { page: 2 }, queryParamsHandling: "merge" });
|
||||
* ```
|
||||
*/
|
||||
* config strategy to handle the query parameters for the next navigation.
|
||||
*
|
||||
* ```
|
||||
* // from /results?page=1 to /view?page=1&page=2
|
||||
* this.router.navigate(['/view'], { queryParams: { page: 2 }, queryParamsHandling: "merge" });
|
||||
* ```
|
||||
*/
|
||||
queryParamsHandling?: QueryParamsHandling|null;
|
||||
/**
|
||||
* Preserves the fragment for the next navigation
|
||||
*
|
||||
* ```
|
||||
* // Preserve fragment from /results#top to /view#top
|
||||
* this.router.navigate(['/view'], { preserveFragment: true });
|
||||
* ```
|
||||
*/
|
||||
* Preserves the fragment for the next navigation
|
||||
*
|
||||
* ```
|
||||
* // Preserve fragment from /results#top to /view#top
|
||||
* this.router.navigate(['/view'], { preserveFragment: true });
|
||||
* ```
|
||||
*/
|
||||
preserveFragment?: boolean;
|
||||
/**
|
||||
* Navigates without pushing a new state into history.
|
||||
*
|
||||
* ```
|
||||
* // Navigate silently to /view
|
||||
* this.router.navigate(['/view'], { skipLocationChange: true });
|
||||
* ```
|
||||
*/
|
||||
* Navigates without pushing a new state into history.
|
||||
*
|
||||
* ```
|
||||
* // Navigate silently to /view
|
||||
* this.router.navigate(['/view'], { skipLocationChange: true });
|
||||
* ```
|
||||
*/
|
||||
skipLocationChange?: boolean;
|
||||
/**
|
||||
* Navigates while replacing the current state in history.
|
||||
*
|
||||
* ```
|
||||
* // Navigate to /view
|
||||
* this.router.navigate(['/view'], { replaceUrl: true });
|
||||
* ```
|
||||
*/
|
||||
* Navigates while replacing the current state in history.
|
||||
*
|
||||
* ```
|
||||
* // Navigate to /view
|
||||
* this.router.navigate(['/view'], { replaceUrl: true });
|
||||
* ```
|
||||
*/
|
||||
replaceUrl?: boolean;
|
||||
}
|
||||
|
||||
@ -241,14 +241,6 @@ export class Router {
|
||||
|
||||
routeReuseStrategy: RouteReuseStrategy = new DefaultRouteReuseStrategy();
|
||||
|
||||
/**
|
||||
* Define what the router should do if it receives a navigation request to the current URL.
|
||||
* By default, the router will ignore this navigation. However, this prevents features such
|
||||
* as a "refresh" button. Use this option to configure the behavior when navigating to the
|
||||
* current URL. Default is 'ignore'.
|
||||
*/
|
||||
onSameUrlNavigation: 'reload'|'ignore' = 'ignore';
|
||||
|
||||
/**
|
||||
* Creates the router service.
|
||||
*/
|
||||
@ -526,18 +518,11 @@ export class Router {
|
||||
|
||||
// Because of a bug in IE and Edge, the location class fires two events (popstate and
|
||||
// hashchange) every single time. The second one should be ignored. Otherwise, the URL will
|
||||
// flicker. Handles the case when a popstate was emitted first.
|
||||
// flicker.
|
||||
if (lastNavigation && source == 'hashchange' && lastNavigation.source === 'popstate' &&
|
||||
lastNavigation.rawUrl.toString() === rawUrl.toString()) {
|
||||
return Promise.resolve(true); // return value is not used
|
||||
}
|
||||
// Because of a bug in IE and Edge, the location class fires two events (popstate and
|
||||
// hashchange) every single time. The second one should be ignored. Otherwise, the URL will
|
||||
// flicker. Handles the case when a hashchange was emitted first.
|
||||
if (lastNavigation && source == 'popstate' && lastNavigation.source === 'hashchange' &&
|
||||
lastNavigation.rawUrl.toString() === rawUrl.toString()) {
|
||||
return Promise.resolve(true); // return value is not used
|
||||
}
|
||||
|
||||
let resolve: any = null;
|
||||
let reject: any = null;
|
||||
@ -560,8 +545,7 @@ export class Router {
|
||||
const url = this.urlHandlingStrategy.extract(rawUrl);
|
||||
const urlTransition = !this.navigated || url.toString() !== this.currentUrlTree.toString();
|
||||
|
||||
if ((this.onSameUrlNavigation === 'reload' ? true : urlTransition) &&
|
||||
this.urlHandlingStrategy.shouldProcessUrl(rawUrl)) {
|
||||
if (urlTransition && this.urlHandlingStrategy.shouldProcessUrl(rawUrl)) {
|
||||
(this.events as Subject<Event>).next(new NavigationStart(id, this.serializeUrl(url)));
|
||||
Promise.resolve()
|
||||
.then(
|
||||
@ -589,9 +573,10 @@ export class Router {
|
||||
}
|
||||
|
||||
private runNavigate(
|
||||
url: UrlTree, rawUrl: UrlTree, skipLocationChange: boolean, replaceUrl: boolean, id: number,
|
||||
precreatedState: RouterStateSnapshot|null): Promise<boolean> {
|
||||
url: UrlTree, rawUrl: UrlTree, shouldPreventPushState: boolean, shouldReplaceUrl: boolean,
|
||||
id: number, precreatedState: RouterStateSnapshot|null): Promise<boolean> {
|
||||
if (id !== this.navigationId) {
|
||||
this.location.go(this.urlSerializer.serialize(this.currentUrlTree));
|
||||
(this.events as Subject<Event>)
|
||||
.next(new NavigationCancel(
|
||||
id, this.serializeUrl(url),
|
||||
@ -713,9 +698,9 @@ export class Router {
|
||||
|
||||
(this as{routerState: RouterState}).routerState = state;
|
||||
|
||||
if (!skipLocationChange) {
|
||||
if (!shouldPreventPushState) {
|
||||
const path = this.urlSerializer.serialize(this.rawUrlTree);
|
||||
if (this.location.isCurrentPathEqualTo(path) || replaceUrl) {
|
||||
if (this.location.isCurrentPathEqualTo(path) || shouldReplaceUrl) {
|
||||
this.location.replaceState(path);
|
||||
} else {
|
||||
this.location.go(path);
|
||||
@ -763,13 +748,14 @@ export class Router {
|
||||
(this as{routerState: RouterState}).routerState = storedState;
|
||||
this.currentUrlTree = storedUrl;
|
||||
this.rawUrlTree = this.urlHandlingStrategy.merge(this.currentUrlTree, rawUrl);
|
||||
this.resetUrlToCurrentUrlTree();
|
||||
this.location.replaceState(this.serializeUrl(this.rawUrlTree));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private resetUrlToCurrentUrlTree(): void {
|
||||
this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree));
|
||||
const path = this.urlSerializer.serialize(this.rawUrlTree);
|
||||
this.location.replaceState(path);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -129,15 +129,12 @@ export class RouterModule {
|
||||
* Creates a module with all the router providers and directives. It also optionally sets up an
|
||||
* application listener to perform an initial navigation.
|
||||
*
|
||||
* Options (see {@link ExtraOptions}):
|
||||
* Options:
|
||||
* * `enableTracing` makes the router log all its internal events to the console.
|
||||
* * `useHash` enables the location strategy that uses the URL fragment instead of the history
|
||||
* API.
|
||||
* * `initialNavigation` disables the initial navigation.
|
||||
* * `errorHandler` provides a custom error handler.
|
||||
* * `preloadingStrategy` configures a preloading strategy (see {@link PreloadAllModules}).
|
||||
* * `onSameUrlNavigation` configures how the router handles navigation to the current URL. See
|
||||
* {@link ExtraOptions} for more details.
|
||||
*/
|
||||
static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders {
|
||||
return {
|
||||
@ -270,14 +267,6 @@ export interface ExtraOptions {
|
||||
* Configures a preloading strategy. See {@link PreloadAllModules}.
|
||||
*/
|
||||
preloadingStrategy?: any;
|
||||
|
||||
/**
|
||||
* Define what the router should do if it receives a navigation request to the current URL.
|
||||
* By default, the router will ignore this navigation. However, this prevents features such
|
||||
* as a "refresh" button. Use this option to configure the behavior when navigating to the
|
||||
* current URL. Default is 'ignore'.
|
||||
*/
|
||||
onSameUrlNavigation?: 'reload'|'ignore';
|
||||
}
|
||||
|
||||
export function setupRouter(
|
||||
@ -310,10 +299,6 @@ export function setupRouter(
|
||||
});
|
||||
}
|
||||
|
||||
if (opts.onSameUrlNavigation) {
|
||||
router.onSameUrlNavigation = opts.onSameUrlNavigation;
|
||||
}
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
@ -381,7 +366,7 @@ export class RouterInitializer {
|
||||
const opts = this.injector.get(ROUTER_CONFIGURATION);
|
||||
const preloader = this.injector.get(RouterPreloader);
|
||||
const router = this.injector.get(Router);
|
||||
const ref = this.injector.get<ApplicationRef>(ApplicationRef);
|
||||
const ref = this.injector.get(ApplicationRef);
|
||||
|
||||
if (bootstrappedComponentRef !== ref.components[0]) {
|
||||
return;
|
||||
|
@ -12,7 +12,6 @@ import {ComponentFixture, TestBed, fakeAsync, inject, tick} from '@angular/core/
|
||||
import {By} from '@angular/platform-browser/src/dom/debug/by';
|
||||
import {expect} from '@angular/platform-browser/testing/src/matchers';
|
||||
import {ActivatedRoute, ActivatedRouteSnapshot, ActivationEnd, ActivationStart, CanActivate, CanDeactivate, ChildActivationEnd, ChildActivationStart, DetachedRouteHandle, Event, GuardsCheckEnd, GuardsCheckStart, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, PRIMARY_OUTLET, ParamMap, Params, PreloadAllModules, PreloadingStrategy, Resolve, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouteReuseStrategy, Router, RouterEvent, RouterModule, RouterPreloader, RouterStateSnapshot, RoutesRecognized, RunGuardsAndResolvers, UrlHandlingStrategy, UrlSegmentGroup, UrlTree} from '@angular/router';
|
||||
import {SpyLocation} from 'common/testing';
|
||||
import {Observable} from 'rxjs/Observable';
|
||||
import {Observer} from 'rxjs/Observer';
|
||||
import {of } from 'rxjs/observable/of';
|
||||
@ -51,89 +50,6 @@ describe('Integration', () => {
|
||||
expect(fixture.nativeElement).toHaveText('route');
|
||||
})));
|
||||
|
||||
describe('navigation', function() {
|
||||
it('should navigate to the current URL', fakeAsync(inject([Router], (router: Router) => {
|
||||
router.onSameUrlNavigation = 'reload';
|
||||
router.resetConfig([
|
||||
{path: '', component: SimpleCmp},
|
||||
{path: 'simple', component: SimpleCmp},
|
||||
]);
|
||||
|
||||
const fixture = createRoot(router, RootCmp);
|
||||
const events: Event[] = [];
|
||||
router.events.subscribe(e => onlyNavigationStartAndEnd(e) && events.push(e));
|
||||
|
||||
router.navigateByUrl('/simple');
|
||||
tick();
|
||||
|
||||
router.navigateByUrl('/simple');
|
||||
tick();
|
||||
|
||||
expectEvents(events, [
|
||||
[NavigationStart, '/simple'], [NavigationEnd, '/simple'], [NavigationStart, '/simple'],
|
||||
[NavigationEnd, '/simple']
|
||||
]);
|
||||
})));
|
||||
|
||||
it('should not pollute browser history when replaceUrl is set to true',
|
||||
fakeAsync(inject([Router, Location], (router: Router, location: SpyLocation) => {
|
||||
router.resetConfig([
|
||||
{path: '', component: SimpleCmp}, {path: 'a', component: SimpleCmp},
|
||||
{path: 'b', component: SimpleCmp}
|
||||
]);
|
||||
|
||||
const fixture = createRoot(router, RootCmp);
|
||||
|
||||
router.navigateByUrl('/a', {replaceUrl: true});
|
||||
router.navigateByUrl('/b', {replaceUrl: true});
|
||||
tick();
|
||||
|
||||
expect(location.urlChanges).toEqual(['replace: /', 'replace: /b']);
|
||||
})));
|
||||
|
||||
it('should skip navigation if another navigation is already scheduled',
|
||||
fakeAsync(inject([Router, Location], (router: Router, location: SpyLocation) => {
|
||||
router.resetConfig([
|
||||
{path: '', component: SimpleCmp}, {path: 'a', component: SimpleCmp},
|
||||
{path: 'b', component: SimpleCmp}
|
||||
]);
|
||||
|
||||
const fixture = createRoot(router, RootCmp);
|
||||
|
||||
router.navigate(
|
||||
['/a'], {queryParams: {a: true}, queryParamsHandling: 'merge', replaceUrl: true});
|
||||
router.navigate(
|
||||
['/b'], {queryParams: {b: true}, queryParamsHandling: 'merge', replaceUrl: true});
|
||||
tick();
|
||||
|
||||
/**
|
||||
* Why do we have '/b?b=true' and not '/b?a=true&b=true'?
|
||||
*
|
||||
* This is because the router has the right to stop a navigation mid-flight if another
|
||||
* navigation has been already scheduled. This is why we can use a top-level guard
|
||||
* to perform redirects. Calling `navigate` in such a guard will stop the navigation, and
|
||||
* the components won't be instantiated.
|
||||
*
|
||||
* This is a fundamental property of the router: it only cares about its latest state.
|
||||
*
|
||||
* This means that components should only map params to something else, not reduce them.
|
||||
* In other words, the following component is asking for trouble:
|
||||
*
|
||||
* ```
|
||||
* class MyComponent {
|
||||
* constructor(a: ActivatedRoute) {
|
||||
* a.params.scan(...)
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* This also means "queryParamsHandling: 'merge'" should only be used to merge with
|
||||
* long-living query parameters (e.g., debug).
|
||||
*/
|
||||
expect(router.url).toEqual('/b?b=true');
|
||||
})));
|
||||
});
|
||||
|
||||
describe('should execute navigations serially', () => {
|
||||
let log: any[] = [];
|
||||
|
||||
@ -512,7 +428,7 @@ describe('Integration', () => {
|
||||
}]);
|
||||
|
||||
const recordedEvents: any[] = [];
|
||||
router.events.forEach(e => onlyNavigationStartAndEnd(e) && recordedEvents.push(e));
|
||||
router.events.forEach(e => e instanceof RouterEvent && recordedEvents.push(e));
|
||||
|
||||
router.navigateByUrl('/team/22/user/victor');
|
||||
advance(fixture);
|
||||
@ -526,8 +442,15 @@ describe('Integration', () => {
|
||||
expect(fixture.nativeElement).toHaveText('team 22 [ user fedor, right: ]');
|
||||
|
||||
expectEvents(recordedEvents, [
|
||||
[NavigationStart, '/team/22/user/victor'], [NavigationEnd, '/team/22/user/victor'],
|
||||
[NavigationStart, '/team/22/user/fedor'], [NavigationEnd, '/team/22/user/fedor']
|
||||
[NavigationStart, '/team/22/user/victor'], [RoutesRecognized, '/team/22/user/victor'],
|
||||
[GuardsCheckStart, '/team/22/user/victor'], [GuardsCheckEnd, '/team/22/user/victor'],
|
||||
[ResolveStart, '/team/22/user/victor'], [ResolveEnd, '/team/22/user/victor'],
|
||||
[NavigationEnd, '/team/22/user/victor'],
|
||||
|
||||
[NavigationStart, '/team/22/user/fedor'], [RoutesRecognized, '/team/22/user/fedor'],
|
||||
[GuardsCheckStart, '/team/22/user/fedor'], [GuardsCheckEnd, '/team/22/user/fedor'],
|
||||
[ResolveStart, '/team/22/user/fedor'], [ResolveEnd, '/team/22/user/fedor'],
|
||||
[NavigationEnd, '/team/22/user/fedor']
|
||||
]);
|
||||
})));
|
||||
|
||||
@ -3715,10 +3638,6 @@ function expectEvents(events: Event[], pairs: any[]) {
|
||||
}
|
||||
}
|
||||
|
||||
function onlyNavigationStartAndEnd(e: Event): boolean {
|
||||
return e instanceof NavigationStart || e instanceof NavigationEnd;
|
||||
}
|
||||
|
||||
@Component(
|
||||
{selector: 'link-cmp', template: `<a routerLink="/team/33/simple" [target]="'_self'">link</a>`})
|
||||
class StringLinkCmp {
|
||||
|
@ -21,7 +21,6 @@ const globals = {
|
||||
'rxjs/observable/defer': 'Rx.Observable',
|
||||
'rxjs/observable/fromEvent': 'Rx.Observable',
|
||||
'rxjs/observable/merge': 'Rx.Observable',
|
||||
'rxjs/observable/never': 'Rx.Observable',
|
||||
'rxjs/observable/of': 'Rx.Observable',
|
||||
'rxjs/observable/throw': 'Rx.Observable',
|
||||
|
||||
|
@ -24,7 +24,7 @@ import {switchMap as op_switchMap} from 'rxjs/operator/switchMap';
|
||||
import {take as op_take} from 'rxjs/operator/take';
|
||||
import {toPromise as op_toPromise} from 'rxjs/operator/toPromise';
|
||||
|
||||
export const ERR_SW_NOT_SUPPORTED = 'Service workers are disabled or not supported by this browser';
|
||||
const ERR_SW_NOT_SUPPORTED = 'Service workers are not supported by this browser';
|
||||
|
||||
export interface Version {
|
||||
hash: string;
|
||||
@ -86,9 +86,9 @@ export class NgswCommChannel {
|
||||
*/
|
||||
readonly events: Observable<IncomingEvent>;
|
||||
|
||||
constructor(private serviceWorker: ServiceWorkerContainer|undefined) {
|
||||
constructor(serviceWorker: ServiceWorkerContainer|undefined) {
|
||||
if (!serviceWorker) {
|
||||
this.worker = this.events = this.registration = errorObservable(ERR_SW_NOT_SUPPORTED);
|
||||
this.worker = this.events = errorObservable(ERR_SW_NOT_SUPPORTED);
|
||||
} else {
|
||||
const controllerChangeEvents =
|
||||
<Observable<any>>(obs_fromEvent(serviceWorker, 'controllerchange'));
|
||||
@ -176,6 +176,4 @@ export class NgswCommChannel {
|
||||
}));
|
||||
return op_toPromise.call(mapErrorAndValue);
|
||||
}
|
||||
|
||||
get isEnabled(): boolean { return !!this.serviceWorker; }
|
||||
}
|
@ -16,18 +16,14 @@ import {NgswCommChannel} from './low_level';
|
||||
import {SwPush} from './push';
|
||||
import {SwUpdate} from './update';
|
||||
|
||||
export abstract class RegistrationOptions {
|
||||
scope?: string;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export const SCRIPT = new InjectionToken<string>('NGSW_REGISTER_SCRIPT');
|
||||
export const OPTS = new InjectionToken<Object>('NGSW_REGISTER_OPTIONS');
|
||||
|
||||
export function ngswAppInitializer(
|
||||
injector: Injector, script: string, options: RegistrationOptions): Function {
|
||||
const initializer = () => {
|
||||
const app = injector.get<ApplicationRef>(ApplicationRef);
|
||||
if (!('serviceWorker' in navigator) || options.enabled === false) {
|
||||
if (!('serviceWorker' in navigator)) {
|
||||
return;
|
||||
}
|
||||
const onStable =
|
||||
@ -35,24 +31,15 @@ export function ngswAppInitializer(
|
||||
const isStable = op_take.call(onStable, 1) as Observable<boolean>;
|
||||
const whenStable = op_toPromise.call(isStable) as Promise<boolean>;
|
||||
|
||||
// Wait for service worker controller changes, and fire an INITIALIZE action when a new SW
|
||||
// becomes active. This allows the SW to initialize itself even if there is no application
|
||||
// traffic.
|
||||
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
||||
if (navigator.serviceWorker.controller !== null) {
|
||||
navigator.serviceWorker.controller.postMessage({action: 'INITIALIZE'});
|
||||
}
|
||||
});
|
||||
|
||||
// Don't return the Promise, as that will block the application until the SW is registered, and
|
||||
// cause a crash if the SW registration fails.
|
||||
whenStable.then(() => navigator.serviceWorker.register(script, {scope: options.scope}));
|
||||
whenStable.then(() => navigator.serviceWorker.register(script, options));
|
||||
};
|
||||
return initializer;
|
||||
}
|
||||
|
||||
export function ngswCommChannelFactory(opts: RegistrationOptions): NgswCommChannel {
|
||||
return new NgswCommChannel(opts.enabled !== false ? navigator.serviceWorker : undefined);
|
||||
export function ngswCommChannelFactory(): NgswCommChannel {
|
||||
return new NgswCommChannel(navigator.serviceWorker);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -62,27 +49,20 @@ export function ngswCommChannelFactory(opts: RegistrationOptions): NgswCommChann
|
||||
providers: [SwPush, SwUpdate],
|
||||
})
|
||||
export class ServiceWorkerModule {
|
||||
/**
|
||||
* Register the given Angular Service Worker script.
|
||||
*
|
||||
* If `enabled` is set to `false` in the given options, the module will behave as if service
|
||||
* workers are not supported by the browser, and the service worker will not be registered.
|
||||
*/
|
||||
static register(script: string, opts: {scope?: string; enabled?: boolean;} = {}):
|
||||
ModuleWithProviders {
|
||||
static register(script: string, opts: RegistrationOptions = {}): ModuleWithProviders {
|
||||
return {
|
||||
ngModule: ServiceWorkerModule,
|
||||
providers: [
|
||||
{provide: SCRIPT, useValue: script},
|
||||
{provide: RegistrationOptions, useValue: opts},
|
||||
{provide: NgswCommChannel, useFactory: ngswCommChannelFactory, deps: [RegistrationOptions]},
|
||||
{provide: OPTS, useValue: opts},
|
||||
{provide: NgswCommChannel, useFactory: ngswCommChannelFactory},
|
||||
{
|
||||
provide: APP_INITIALIZER,
|
||||
useFactory: ngswAppInitializer,
|
||||
deps: [Injector, SCRIPT, RegistrationOptions],
|
||||
deps: [Injector, SCRIPT, OPTS],
|
||||
multi: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
@ -9,15 +9,15 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Observable} from 'rxjs/Observable';
|
||||
import {Subject} from 'rxjs/Subject';
|
||||
|
||||
import {merge as obs_merge} from 'rxjs/observable/merge';
|
||||
import {never as obs_never} from 'rxjs/observable/never';
|
||||
|
||||
import {map as op_map} from 'rxjs/operator/map';
|
||||
import {switchMap as op_switchMap} from 'rxjs/operator/switchMap';
|
||||
import {take as op_take} from 'rxjs/operator/take';
|
||||
import {toPromise as op_toPromise} from 'rxjs/operator/toPromise';
|
||||
|
||||
import {ERR_SW_NOT_SUPPORTED, NgswCommChannel} from './low_level';
|
||||
|
||||
import {NgswCommChannel} from './low_level';
|
||||
|
||||
/**
|
||||
* Subscribe and listen to push notifications from the Service Worker.
|
||||
@ -34,11 +34,6 @@ export class SwPush {
|
||||
new Subject<PushSubscription|null>();
|
||||
|
||||
constructor(private sw: NgswCommChannel) {
|
||||
if (!sw.isEnabled) {
|
||||
this.messages = obs_never();
|
||||
this.subscription = obs_never();
|
||||
return;
|
||||
}
|
||||
this.messages =
|
||||
op_map.call(this.sw.eventsOfType('PUSH'), (message: {data: object}) => message.data);
|
||||
|
||||
@ -51,16 +46,7 @@ export class SwPush {
|
||||
this.subscription = obs_merge(workerDrivenSubscriptions, this.subscriptionChanges);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the Service Worker is enabled (supported by the browser and enabled via
|
||||
* ServiceWorkerModule).
|
||||
*/
|
||||
get isEnabled(): boolean { return this.sw.isEnabled; }
|
||||
|
||||
requestSubscription(options: {serverPublicKey: string}): Promise<PushSubscription> {
|
||||
if (!this.sw.isEnabled) {
|
||||
return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED));
|
||||
}
|
||||
const pushOptions: PushSubscriptionOptionsInit = {userVisibleOnly: true};
|
||||
let key = atob(options.serverPublicKey.replace(/_/g, '/').replace(/-/g, '+'));
|
||||
let applicationServerKey = new Uint8Array(new ArrayBuffer(key.length));
|
||||
@ -78,9 +64,6 @@ export class SwPush {
|
||||
}
|
||||
|
||||
unsubscribe(): Promise<void> {
|
||||
if (!this.sw.isEnabled) {
|
||||
return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED));
|
||||
}
|
||||
const unsubscribe = op_switchMap.call(this.subscription, (sub: PushSubscription | null) => {
|
||||
if (sub !== null) {
|
||||
return sub.unsubscribe().then(success => {
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user