Since we generate a `.mjs` file as entry-point for jasmine tests,
a couple of issues prevented the transitive dependencies from
bootstrap targets to be brought in (causing resolution errors):
1. The `_files` (previously `_esm2015`) targets are no longer needed,
and they also miss all the information on runfiles.
2. The aspect for computing linker mappings does not respect the
`bootstrap` attribute from the `spec_entrypoint` so we manually
add the extract ESM output targets (this rule works with the aspect
and forwards linker mappings).
PR Close#48521
For every `ts_library` target we expose a shorthand that grants
access to the JS files because `DefaultInfo` of a ts library
only exposes the `.d.ts` files.
We rename this away from `es2015` since in practice it's a much
higher target these days. Additionally we no longer use the devmode
output but rather use the prodmode output which has the explicit
`.mjs` output- compatible with ESM.
PR Close#48521
The `__ESM_IMPORT_META_URL__` trick was used because we used both ESM
and CommonJS in this repo. It was an interop needed because
`import.meta.url` syntax couldn't be used as it woud have caused syntax
errors.
We still need to keep the CommonJS/ESM interop in the compiler-cli
because g3 relies on the compiler and uses CommonJS. This affects very
few places, just in the compiler- so this is acceptable.
PR Close#48521
In AOT compilations, the `strictInjectionParameters` compiler option can
be enabled to report errors when an `@Injectable` annotated class has a
constructor with parameters that do not provide an injection token, e.g.
only a primitive type or interface.
Since Ivy it's become required that any class with Angular behavior
(e.g. the `ngOnDestroy` lifecycle hook) is decorated using an Angular
decorator, which meant that `@Injectable()` may need to have been added
to abstract base classes. Doing so would then report an error if
`strictInjectionParameters` is enabled, if the abstract class has an
incompatible constructor for DI purposes. This may be fine though, as
a subclass may call the constructor explicitly without relying on
Angular's DI mechanism.
Therefore, this commit excludes abstract classes from the
`strictInjectionParameters` check. This avoids an error from being
reported at compile time. If the constructor ends up being used by
Angular's DI system at runtime, then the factory function of the
abstract class will throw an error by means of the `ɵɵinvalidFactory`
instruction.
In addition to the runtime error, this commit also analyzes the inheritance
chain of an injectable without a constructor to verify that their inherited
constructor is valid.
BREAKING CHANGE: Invalid constructors for DI may now report compilation errors
When a class inherits its constructor from a base class, the compiler may now
report an error when that constructor cannot be used for DI purposes. This may
either be because the base class is missing an Angular decorator such as
`@Injectable()` or `@Directive()`, or because the constructor contains parameters
which do not have an associated token (such as primitive types like `string`).
These situations used to behave unexpectedly at runtime, where the class may be
constructed without any of its constructor parameters, so this is now reported
as an error during compilation.
Any new errors that may be reported because of this change can be resolved either
by decorating the base class from which the constructor is inherited, or by adding
an explicit constructor to the class for which the error is reported.
Closes#37914
PR Close#44615
This is the compile-time implementation of the `hostDirectives` feature plus a little bit of runtime code to illustrate how the newly-generated code will plug into the runtime. It works by creating a call to the new `ɵɵHostDirectivesFeature` feature whenever a directive has a `hostDirectives` field. Afterwards `ɵɵHostDirectivesFeature` will patch a new function onto the directive definition that will be invoked during directive matching.
For example, if we take the following definition:
```ts
@Directive({
hostDirectives: [HostA, {directive: HostB, inputs: ['input: alias']}]
})
class MyDir {}
```
Will compile to:
```js
MyDir.ɵdir = ɵɵdefineComponent({
features: [ɵɵHostDirectivesFeature([HostA, {
directive: HostB,
inputs: {
input: "alias"
}
}])]
});
```
The template type checking is implemented during directive matching by adding the host directives applied on the host to the array of matched directives whenever the host is matched in a template.
Relates to #8785.
PR Close#46868
Adds support for TypeScript 4.8 and resolves some issues that came up as a result of the update.
Most of the issues came from some changes in TypeScript where the `decorators` and `modifiers` properties were removed from most node types, and were combined into a single `modifiers` array. Since we need to continue supporting TS 4.6 and 4.7 until v15, I ended up creating a new `ngtsc/ts_compatibility` directory to make it easier to reuse the new backwards-compatible code.
PR Close#47038
When generating .d.ts metadata for NgModules, by default we emit type
references to their declarations, imports, and exports. However, this
information is not necessarily useful to consumers. References to private
directives (those that aren't exported by the NgModule) for example aren't
at all useful as they can only affect other components declared in the
NgModule. References to imports are of limited usefulness - they might be
helpful for an IDE to understand the DI structure of an application, but
aren't at all used by a downstream compiler.
Generating this metadata is not without cost. When an incremental build
system uses changes in inputs to determine when a rebuild is necessary, any
changes in .d.ts files might cause downstream targets to rebuild. If those
.d.ts changes are in the "private" side of the NgModule (imports or non-
exported directives/pipes), then these rebuilds are wholly unnecessary.
This commit introduces the `onlyPublishPublicTypingsForNgModules` flag for
the compiler. When this flag is set, the compiler will filter the emitted
references in NgModule .d.ts output and only reference those directives/
pipes that are exported from the NgModule (its public API surface). Omitting
the flag preserves the existing behavior of emitting all references, both
public and private.
This is especially useful for build systems such as Bazel.
PR Close#45894
When an external template is read, adds the template file to to the project which contains.
This is necessary to keep the projects open when navigating away from HTML files.
Since a `tsconfig` cannot express including non-TS files,
we need another way to indicate the template files are considered part of the project.
Note that this does not ensure that the project in question _directly_ contains the component
file. That is, the project might just include the component file through the program rather
than directly in the `include` glob of the `tsconfig`. This distinction is somewhat important
because the TypeScript language service/server prefers projects which _directly_ contain the TS
file (see `projectContainsInfoDirectly` in the TS codebase). What this means it that there can
possibly be a different project used between the TS and HTML files.
For example, in Nx projects, the referenced configs are `tsconfig.app.json` and
`tsconfig.editor.json`. `tsconfig.app.json` comes first in the base `tsconfig.json` and
contains the entry point of the app. `tsconfig.editor.json` contains the `**.ts` glob of all TS
files. This means that `tsconfig.editor.json` will be preferred by the TS server for TS files
but the `tsconfig.app.json` will be used for HTML files since it comes first and we cannot
effectively express `projectContainsInfoDirectly` for HTML files.
We could consider also updating the language server implementation to attempt
to select the project to use for the template file based on which project
contains its component file directly, using either the internal `project.projectContainsInfoDirectly`
or as a workaround, check `project.isRoot(componentTsFile)`.
Finally, keeping the projects open is hugely important in the solution style config case like
Nx. When a TS file is opened, TypeScript will only retain `tsconfig.editor.json` and not
`tsconfig.app.json`. However, if our extension does not also know to select
`tsconfig.editor.json`, it will automatically select `tsconfig.app.json` since it is defined
first in the `tsconfig.json` file. So we need to teach TS server that we are (1) interested in
keeping projects open when there is an HTML file open and (2) optionally attempt to do this
_only_ for projects that we know the TS language service will prioritize in TS files (i.e.,
attempt to only keep `tsconfig.editor.json` open and allow `tsconfig.app.json` to close)
and prioritize that project for all requests.
fixes https://github.com/angular/vscode-ng-language-service/issues/1623
fixes https://github.com/angular/vscode-ng-language-service/issues/876
PR Close#45601
In PR #45405, the Angular Package Format (APF) was updated so that
secondary entry-points (such as `@angular/common/http`) do not have
their own `package.json` file, as they used to. Instead, the paths to
their various formats and types are exposed via the primary
`package.json` file's `exports` property. As an example, see the v13
[@angular/common/http/package.json][1] and compare it with the v14
[@angular/common/package.json > exports][2].
Previously, `ngcc` was not able to analyze such v14+ entry-points and
would instead error as it considered such entry-points missing.
This commit addresses the issue by detecting this situation and
synthesizing a `package.json` file for the secondary entry-points based
on the `exports` property of the primary `package.json` file. This data
is only used by `ngcc` in order to determine that the entry-point does
not need further processing, since it is already in Ivy format.
[1]: https://unpkg.com/browse/@angular/common@13.3.5/http/package.json
[2]: https://unpkg.com/browse/@angular/common@14.0.0-next.15/package.json
PR Close#45833
Move the `loadPackageJson()` helper (and associated generic types, such
as `JsonObject`) from `packages/entry_point.ts` to `utils.ts` and also
rename it to `loadJson()`. This way, they can be used in other places in
future commits, without introducing cyclical dependencies.
PR Close#45833
The NodeJS Bazel linker does not work well on Windows because there
is no sandboxing and linker processes from different tests will attempt
to modify the same `node_modules`, causing concurrency race conditions
and resulting in flakiness.
PR Close#45872
In AOT compilations, the `strictInjectionParameters` compiler option can
be enabled to report errors when an `@Injectable` annotated class has a
constructor with parameters that do not provide an injection token, e.g.
only a primitive type or interface.
Since Ivy it's become required that any class with Angular behavior
(e.g. the `ngOnDestroy` lifecycle hook) is decorated using an Angular
decorator, which meant that `@Injectable()` may need to have been added
to abstract base classes. Doing so would then report an error if
`strictInjectionParameters` is enabled, if the abstract class has an
incompatible constructor for DI purposes. This may be fine though, as
a subclass may call the constructor explicitly without relying on
Angular's DI mechanism.
Therefore, this commit excludes abstract classes from the
`strictInjectionParameters` check. This avoids an error from being
reported at compile time. If the constructor ends up being used by
Angular's DI system at runtime, then the factory function of the
abstract class will throw an error by means of the `ɵɵinvalidFactory`
instruction.
In addition to the runtime error, this commit also analyzes the inheritance
chain of an injectable without a constructor to verify that their inherited
constructor is valid.
Closes#37914
PR Close#44615
Adds support for TypeScript 4.7. Changes include:
* Bumping the TS version as well as some Bazel dependencies to include https://github.com/bazelbuild/rules_nodejs/pull/3420.
* Adding a backwards-compatibility layer for calls to `updateTypeParameterDeclaration`.
* Making `LView` generic in order to make it easier to type the context based on the usage. Currently the context can be 4 different types which coupled with stricter type checking would required a lot of extra casting all over `core`.
* Fixing a bunch of miscellaneous type errors.
* Removing assertions of `ReferenceEntry.isDefinition` in a few of the language service tests. The field isn't returned by TS anymore and we weren't using it for anything.
* Resolving in error in the language service that was caused by TS attempting to parse HTML files when we try to open them. Previous TS was silently setting them as `ScriptKind.Unknown` and ignoring the errors, but now it throws. I've worked around it by setting them as `ScriptKind.JSX`.
PR Close#45749
This commit adds a type field to .d.ts metadata for directives, components,
and pipes which carries a boolean literal indicating whether the given type
is standalone or not. For backwards compatibility, this flag defaults to
`false`.
Tests are added to validate that standalone types coming from .d.ts files
can be correctly imported into new standalone components.
PR Close#45672
This commit implements the next step of Angular's "standalone" functionality,
by allowing directives/components/pipes declared as `standalone` to be imported
into NgModules. Errors are raised when such a type is not standalone but is
included in an NgModule's imports.
PR Close#44973
Node.js v12 will become EOL on 2022-04-30. As a result, Angular CLI v14 will no longer support Node.js v12.
BREAKING CHANGE:
Support for Node.js v12 has been removed as it will become EOL on 2022-04-30. Please use Node.js v14.15 or later.
PR Close#45286
Proactively replaces our usages of the deprecated `ts.create*` methods in favor of using `ts.factory.create*` so that we're not surprised when the TS removes them in the future. Also accounts for some cases where the signature had changed.
PR Close#45134
This commit implements the first phase of standalone components in the Angular
compiler. This mainly includes the scoping rules for standalone components
(`@Component({imports})`).
Significant functionality from the design is _not_ implemented by this PR,
including:
* imports of standalone components into NgModules.
* the provider aspect of standalone components
Future commits will address these issues, as we proceed with the design of
this feature.
PR Close#44812
Previously each `DecoratorHandler` in the compiler was stored in a single file
in the 'annotations' package. The `ComponentDecoratorHandler` in particular was
several thousand lines long.
Prior to implementing the new standalone functionality for components, this
commit refactors 'annotations' to split these large files into their own build
targets with multiple separate files. This should make the implementation of
standalone significantly cleaner.
PR Close#44812
Bundlers like Rollup may use an element access expression for an export
declaration, which causes ngcc to ignore those export declarations possibly
resulting in incomplete processing of packages.
Element access syntax may be used when the declared name is not considered
as valid JS identifier, but bundlers may be conservative in determining whether
an identifier can be used (to emit a property access) and opt for a string
literal in an element access instead.
The element access syntax introduces a problem for ngcc, where it wouldn't
consider such export as class declaration, causing them to be skipped. The
ngtsc compiler is implemented with the assumption that all class declarations
use a `ts.Identifier` as name, whereas the element access is using a string
literal for the declared name. This makes it troublesome for ngcc to support
this syntax form in UMD bundles.
To work around the problem, this function transforms these access expressions
into regular property accesses. The source text is parsed to an AST to allow
finding the element accesses in a robust way, after which the affected text
ranges are replaced with property accesses in the original source text.
Closes#44037
PR Close#44669
To make our test output i.e. devmode output more aligned
with what we produce in the NPM packages, or to be more
aligned with what Angular applications will usually consume,
the devmode output is switched from ES5 to ES2015.
Additionally various tsconfigs (outside of Bazel) have been
updated to match with the other parts of the build. The rules
are:
ES2015 for test configurations, ES2020 for actual code that will
end up being shipped (this includes the IDE-only tsconfigs).
PR Close#44505
Now that ViewEngine libraries can no longer be created, the latest
TypeScript version that ngcc should be able to process is TypeScript 4.3,
i.e. the version of TypeScript that was supported in Angular 12.
However, ngcc's integration tests used the TypeScript version of the
workspace to create the JavaScript files from TypeScript sources on
demand. This introduces friction when upgrading the TypeScript version
within the workspace, as changes to TypeScript's emit format may affect
ngcc's ability to process it correctly.
The on demand creation of JavaScript files was convenient for authoring
tests, but it also helped to detect incompatibilities with newer
versions of TypeScript. Now that ngcc no longer has to process newer
versions of TypeScript, we want to pin the integration suite to use
JavaScript code as if it were compiled using TypeScript 4.3, i.e. a
version of TypeScript that is actually supported by ngcc.
This commit updates the integration test to inline all the generated
files directly in the tests, instead of compiling them on demand. This
was done by temporarily installing TypeScript 4.3 and using it to create
the `loadTestFiles` statement from the original TypeScript inputs.
An alternative could have been to install TypeScript 4.3 as an actual
dependency in the workspace and using that to continue compiling the
integration suite on demand, but this brings some overhead in package
installations (TypeScript is ~60MB) and the authoring aspect of ngcc
integration test is expected to diminish, now that ngcc's support is no
longer a moving target.
PR Close#44448
Previously, when processing UMD, ngcc assumed that the `exports`
argument of the CommonJS factory call (if present) would be the first
argument of the call. This is generally true for the supported UMD
formats, but can change if ngcc prepends more imports (and thus factory
arguments) while processing the module. This could lead to errors when
trying to collect dependencies of an already processed module.
(This was accidentally broken in #44245 (commit 2bc3522e16).)
This commit fixes it by not making any assumptions about the position of
an `exports` argument in the CommonJS factory call.
Fixes#44380
PR Close#44381
Adds support for TypeScript 4.5. Includes the following changes:
* Bumping the package versions.
* Fixing a few calls to `createExportSpecifier` and `createImportSpecifier` that require an extra parameter.
* Adding some missing methods to the TS compiler hosts.
* Fixing an issue in the TS mocks for the ngcc tests where a regex was too agressive and was trying to match a path like `/node_modules/@typescript/lib-es5`.
* Accounting for type-only import specifiers when reporting DI errors (see #43620).
Fixes#43620.
PR Close#44164
Previously, the mock packages created for `UmdDependencyHost`'s tests,
specified the entry-point as `esm2015`. This does not matter in tests,
since the packages are explicitly passed to the `UmdDependencyHost`
(while in reality the appropriate host would be determined based on the
name of the entry-point property - in this case, detecting the
entry-point as ES2015 and not UMD).
However, in order to avoid confusion, this commit updates the test
packages to use `main` (the default property used for the UMD format in
`package.json` files).
PR Close#44245
Previously, the ngcc `UmdReflectionHost` would throw a misleading error
when trying to collect dependencies of an invalidly formatted UMD
module. This happened because an error would be thrown while trying to
construct the error message for the actual error, by calling `getText()`
on certain TypeScript AST nodes. See
https://github.com/angular/angular/issues/44019#issuecomment-959954121
for a more in-depth explanation.
This commit ensures `getText()` can be safely called on TypeScript AST
nodes when collecting dependencies of UMD modules.
PR Close#44245
This commit utilizes the infrastructure added in the previous commit to
run more tests against more of the supported UMD formats. This shall
give us more confidence that all aspects of UMD processing work
correctly with the various formats.
PR Close#44245
Previously, several ngcc test suites used their own helper to generate
test UMD modules.
This commit switches to using the same helper for generating UMD modules
across test suites. This improves DRYness (ensuring changes/fixes to the
UMD format need only be applied once) and makes it easier to test
different UMD formats in all test suites.
PR Close#44245
Previously, ngcc could only handle UMD modules whose wrapper function
was implemented as a `ts.ConditionalExpression` (i.e. using a ternary
operator). This is the format emitted by popular bundlers, such as
Rollup.
This commit adds support for a different format, that uses `if/else`
statements, which is what is [emitted by Webpack][1].
[1]: https://webpack.js.org/configuration/output/#type-umdFixes#44019
PR Close#44245
Previously, ngcc could only handle UMD modules whose wrapper function
was implemented as a `ts.ConditionalExpression` (i.e. using a ternary
operator). This is the format emitted by popular bundlers, such as
Rollup. However, this failed to account for a different format, using
`if/else` statements, such as the one [emitted by Webpack][1].
This commit prepares ngcc for supporting different UMD wrapper function
formats by decoupling the operation of parsing the wrapper function body
to capture the various factory function calls and that of operating on
the factory function calls (for example, to read or update their
arguments). In a subsequent commit, this will be used to add support for
the Webpack format.
[1]: https://webpack.js.org/configuration/output/#type-umd
PR Close#44245
ngcc used to rewrite `PRE_R3` markers to become `POST_R3` in order to
switch the runtime implementation in `@angular/core` from View Engine to
Ivy. Now that `@angular/core` is published as native Ivy package and the
runtime switch code has been removed, there is no need for ngcc to
perform this transform anymore.
PR Close#43891
This commit removes the View Engine runtime. Itself, this change is
relatively straightforward, but it represents the final step in a multi-year
journey. It's only possible due to the hard work of many current and former
team members and collaborators, who are too numerous to list here.
Co-authored-by: Alan Agius <alan.agius4@gmail.com>
Co-authored-by: Andrew Kushnir <akushnir@google.com>
Co-authored-by: Andrew Scott <atscott01@gmail.com>
Co-authored-by: Andrew Seguin <andrewjs@google.com>
Co-authored-by: Cédric Exbrayat <cedric@ninja-squad.com>
Co-authored-by: Charles Lyding <19598772+clydin@users.noreply.github.com>
Co-authored-by: Dave Shevitz <dshevitz@google.com>
Co-authored-by: Doug Parker <dgp1130@users.noreply.github.com>
Co-authored-by: Dylan Hunn <dylhunn@gmail.com>
Co-authored-by: Emma Twersky <emmatwersky@google.com>
Co-authored-by: George Kalpakas <kalpakas.g@gmail.com>
Co-authored-by: Igor Minar <iminar@google.com>
Co-authored-by: Jeremy Elbourn <jelbourn@google.com>
Co-authored-by: Jessica Janiuk <jessicajaniuk@google.com>
Co-authored-by: JiaLiPassion <JiaLi.Passion@gmail.com>
Co-authored-by: Joey Perrott <josephperrott@gmail.com>
Co-authored-by: Joost Koehoorn <joost.koehoorn@gmail.com>
Co-authored-by: Kristiyan Kostadinov <crisbeto@abv.bg>
Co-authored-by: Madleina Scheidegger <mscheid@google.com>
Co-authored-by: Mark Thompson <2554588+MarkTechson@users.noreply.github.com>
Co-authored-by: Minko Gechev <mgechev@gmail.com>
Co-authored-by: Paul Gschwendtner <paulgschwendtner@gmail.com>
Co-authored-by: Pawel Kozlowski <pkozlowski.opensource@gmail.com>
Co-authored-by: Pete Bacon Darwin <pete@bacondarwin.com>
Co-authored-by: Wagner Maciel <wagnermaciel@google.com>
Co-authored-by: Zach Arend <zachzach@google.com>
PR Close#43884
When executing, ngcc writes a lock-file that is used to coordinate multiple concurrent instances of ngcc.
Previously, this file was written at `node_modules/@angular/compiler-cli/ngcc`, or similar depending upon the bundling of the package.
But this causes problems for setups where `node_modules` package directories are expected to be read-only.
Now, the lock-file is written as `.ngcc_lock_file` into the top of the `node_modules`, which is an acceptable place to store transient files.
This change should help to unblock use of tools like pnpm and lerna, which can use symlinks to readonly package directories.
PR Close#44228
This commit adds additional information to encourage developers to contact
the author of View Engine libraries and ask them to update to partial Ivy.
Fixes#42308
PR Close#43996
In #43879, `UmdReflectionHost` was updated to deal with the new UMD
format used by Rollup, where the parenthesis is around the wrapper
function and not the wrapper function call.
For reference, this caused failures in the `ngcc-validation` repo
([example 1][1], [example 2][2]).
This commit updates `UmdRenderingFormatter` to also handle both UMD
formats. In order to validate the change, this commit also updates the
`UmdRenderingFormatter` tests to run against both UMD formats.
[1]: https://circleci.com/gh/angular/ngcc-validation/65916
[2]: https://circleci.com/gh/angular/ngcc-validation/65758
PR Close#43931
Recently rollup, used by ng-packagr, changed the position of parentheses
around its generated UMD wrapper functions.
This commit ensures that ngcc can handle both.
Fixes#43870
PR Close#43879
Ngcc relies on cluster for distributing work. The master controller
sends messages to the workers as soon as the worker becomes `online`.
The online event is sent as part of the NodeJS cluster logic itself.
This does not work well because technically `online` could emit before the
worker started listening (this seems to be case now with ESM as the
imports are loaded in a way where `online` emits too early; before the
worker actually listens for messages).
We fix this by explicitly notifying the master when the worker
is ready for retrieving IPC messages/or tasks. This is more safe
anyway as it's not clearly specified when `online` emits.
PR Close#43431
Given that we ship all of compiler-cli and localize in ESM
mode now, we need to use a ESM compatible version of Yargs.
The latest version seems ESM compatible but with some small
API changes. This commit updates Yargs and updates the command
line option code to use the new API.
PR Close#43431
Updates the lock file resolution logic in ngcc to work with ESM output.
The compiler-cli is now shipped in bundles, so the actual module resolution
needs to stay to keep the lock file path consistent regardless of where the
lock file code is bundled into. The ngcc integration test needs to be updated
though since the `ngcc` entry-point will always reside in the `bundles/` directory
now.
It has been considered using the top-level `package.json` of the compiler-cli
package, but that caused problems in tests down the line because the ngcc
tests only have the `@angular/compiler-cli/ngcc/...` targets linked into
the node modules. It's not worth changing this and reworking tests if ngcc
is going away in the future anyway (+ it has been like that before!).
PR Close#43431