Skip to content

Commit fa47890

Browse files
committed
refactor(core): clean up platform bootstrap and initTestEnvironment
- Introduces `CompilerFactory` which can be part of a `PlatformRef`. - Introduces `WorkerAppModule`, `WorkerUiModule`, `ServerModule` - Introduces `serverDynamicPlatform` for applications using runtime compilation on the server. - Changes browser bootstrap for runtime and offline compilation (see below for an example). * introduces `bootstrapModule` and `bootstrapModuleFactory` in `@angular/core` * introduces new `browserDynamicPlatform` in `@angular/platform-browser-dynamic - Changes `initTestEnvironment` (which used to be `setBaseTestProviders`) to not take a compiler factory any more (see below for an example). BREAKING CHANGE: ## Migration from `setBaseTestProviders` to `initTestEnvironment`: - For the browser platform: BEFORE: ``` import {setBaseTestProviders} from ‘@angular/core/testing’; import {TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS} from ‘@angular/platform-browser-dynamic/testing’; setBaseTestProviders(TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS); ``` AFTER: ``` import {initTestEnvironment} from ‘@angular/core/testing’; import {browserDynamicTestPlatform, BrowserDynamicTestModule} from ‘@angular/platform-browser-dynamic/testing’; initTestEnvironment( BrowserDynamicTestModule, browserDynamicTestPlatform()); ``` - For the server platform: BEFORE: ``` import {setBaseTestProviders} from ‘@angular/core/testing’; import {TEST_SERVER_PLATFORM_PROVIDERS, TEST_SERVER_APPLICATION_PROVIDERS} from ‘@angular/platform-server/testing/server’; setBaseTestProviders(TEST_SERVER_PLATFORM_PROVIDERS, TEST_SERVER_APPLICATION_PROVIDERS); ``` AFTER: ``` import {initTestEnvironment} from ‘@angular/core/testing’; import {serverTestPlatform, ServerTestModule} from ‘@angular/platform-browser-dynamic/testing’; initTestEnvironment( ServerTestModule, serverTestPlatform()); ``` ## Bootstrap changes ``` @appmodule({ modules: [BrowserModule], precompile: [MainComponent], providers: […], // additional providers directives: […], // additional platform directives pipes: […] // additional platform pipes }) class MyModule { constructor(appRef: ApplicationRef) { appRef.bootstrap(MainComponent); } } // offline compile import {browserPlatform} from ‘@angular/platform-browser’; import {bootstrapModuleFactory} from ‘@angular/core’; bootstrapModuleFactory(MyModuleNgFactory, browserPlatform()); // runtime compile long form import {browserDynamicPlatform} from ‘@angular/platform-browser-dynamic’; import {bootstrapModule} from ‘@angular/core’; bootstrapModule(MyModule, browserDynamicPlatform()); ``` Closes #9922 Part of #9726
1 parent d84a43c commit fa47890

File tree

33 files changed

+467
-313
lines changed

33 files changed

+467
-313
lines changed

modules/@angular/compiler-cli/README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,10 @@ bootstrap.ts
4949
-------------
5050

5151
import {MainModuleNgFactory} from './main_module.ngfactory';
52+
import {bootstrapModuleFactory} from '@angular/core';
53+
import {browserPlatform} from '@angular/platform-browser';
5254

53-
MainModuleNgFactory.create(browserPlatform().injector);
55+
bootstrapModuleFactory(MainModuleNgFactory, browserPlatform());
5456
```
5557

5658
## Configuration

modules/@angular/compiler-cli/integrationtest/test/util.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88

9-
import {AppModuleFactory, AppModuleRef} from '@angular/core';
9+
import {AppModuleFactory, AppModuleRef, bootstrapModuleFactory} from '@angular/core';
1010
import {ComponentFixture} from '@angular/core/testing';
1111
import {serverPlatform} from '@angular/platform-server';
1212

1313
import {MainModuleNgFactory} from '../src/module.ngfactory';
1414

1515
export function createModule<M>(factory: AppModuleFactory<M>): AppModuleRef<M> {
16-
return factory.create(serverPlatform().injector);
16+
return bootstrapModuleFactory(factory, serverPlatform());
1717
}
1818

1919
export function createComponent<C>(

modules/@angular/compiler/compiler.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
* @description
1212
* Starting point to import all compiler APIs.
1313
*/
14-
export {COMPILER_PROVIDERS, CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileFactoryMetadata, CompileIdentifierMetadata, CompileMetadataWithIdentifier, CompileMetadataWithType, CompilePipeMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTemplateMetadata, CompileTokenMetadata, CompileTypeMetadata, CompilerConfig, DEFAULT_PACKAGE_URL_PROVIDER, DirectiveResolver, OfflineCompiler, PipeResolver, RenderTypes, RuntimeCompiler, SourceModule, TEMPLATE_TRANSFORMS, UrlResolver, ViewResolver, XHR, createOfflineCompileUrlResolver} from './src/compiler';
14+
export {COMPILER_PROVIDERS, CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileFactoryMetadata, CompileIdentifierMetadata, CompileMetadataWithIdentifier, CompileMetadataWithType, CompilePipeMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTemplateMetadata, CompileTokenMetadata, CompileTypeMetadata, CompilerConfig, DEFAULT_PACKAGE_URL_PROVIDER, DirectiveResolver, OfflineCompiler, PipeResolver, RUNTIME_COMPILER_FACTORY, RenderTypes, RuntimeCompiler, SourceModule, TEMPLATE_TRANSFORMS, UrlResolver, ViewResolver, XHR, createOfflineCompileUrlResolver} from './src/compiler';
1515
export {ElementSchemaRegistry} from './src/schema/element_schema_registry';
1616

1717
export * from './src/template_ast';

modules/@angular/compiler/src/compiler.ts

Lines changed: 110 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88

9-
import {Compiler, ComponentResolver, Type} from '@angular/core';
9+
import {Compiler, CompilerFactory, CompilerOptions, ComponentResolver, Injectable, PLATFORM_DIRECTIVES, PLATFORM_PIPES, ReflectiveInjector, Type, ViewEncapsulation, isDevMode} from '@angular/core';
1010

1111
export * from './template_ast';
1212
export {TEMPLATE_TRANSFORMS} from './template_parser';
@@ -39,13 +39,16 @@ import {ViewResolver} from './view_resolver';
3939
import {DirectiveResolver} from './directive_resolver';
4040
import {PipeResolver} from './pipe_resolver';
4141
import {Console, Reflector, reflector, ReflectorReader} from '../core_private';
42+
import {XHR} from './xhr';
4243

4344
/**
4445
* A set of providers that provide `RuntimeCompiler` and its dependencies to use for
4546
* template compilation.
4647
*/
4748
export const COMPILER_PROVIDERS: Array<any|Type|{[k: string]: any}|any[]> =
4849
/*@ts2dart_const*/[
50+
{provide: PLATFORM_DIRECTIVES, useValue: [], multi: true},
51+
{provide: PLATFORM_PIPES, useValue: [], multi: true},
4952
{provide: Reflector, useValue: reflector},
5053
{provide: ReflectorReader, useExisting: Reflector},
5154
Console,
@@ -70,3 +73,109 @@ export const COMPILER_PROVIDERS: Array<any|Type|{[k: string]: any}|any[]> =
7073
DirectiveResolver,
7174
PipeResolver
7275
];
76+
77+
@Injectable()
78+
export class _RuntimeCompilerFactory extends CompilerFactory {
79+
createCompiler(options: CompilerOptions): Compiler {
80+
const deprecationMessages: string[] = [];
81+
let platformDirectivesFromAppProviders: any[] = [];
82+
let platformPipesFromAppProviders: any[] = [];
83+
let compilerProvidersFromAppProviders: any[] = [];
84+
let useDebugFromAppProviders: boolean;
85+
let useJitFromAppProviders: boolean;
86+
let defaultEncapsulationFromAppProviders: ViewEncapsulation;
87+
88+
if (options.deprecatedAppProviders && options.deprecatedAppProviders.length > 0) {
89+
// Note: This is a hack to still support the old way
90+
// of configuring platform directives / pipes and the compiler xhr.
91+
// This will soon be deprecated!
92+
const inj = ReflectiveInjector.resolveAndCreate(options.deprecatedAppProviders);
93+
const compilerConfig: CompilerConfig = inj.get(CompilerConfig, null);
94+
if (compilerConfig) {
95+
platformDirectivesFromAppProviders = compilerConfig.platformDirectives;
96+
platformPipesFromAppProviders = compilerConfig.platformPipes;
97+
useJitFromAppProviders = compilerConfig.useJit;
98+
useDebugFromAppProviders = compilerConfig.genDebugInfo;
99+
defaultEncapsulationFromAppProviders = compilerConfig.defaultEncapsulation;
100+
deprecationMessages.push(
101+
`Passing a CompilerConfig to "bootstrap()" as provider is deprecated. Pass the provider via the new parameter "compilerOptions" of "bootstrap()" instead.`);
102+
} else {
103+
// If nobody provided a CompilerConfig, use the
104+
// PLATFORM_DIRECTIVES / PLATFORM_PIPES values directly if existing
105+
platformDirectivesFromAppProviders = inj.get(PLATFORM_DIRECTIVES, []);
106+
if (platformDirectivesFromAppProviders.length > 0) {
107+
deprecationMessages.push(
108+
`Passing PLATFORM_DIRECTIVES to "bootstrap()" as provider is deprecated. Use the new parameter "directives" of "bootstrap()" instead.`);
109+
}
110+
platformPipesFromAppProviders = inj.get(PLATFORM_PIPES, []);
111+
if (platformPipesFromAppProviders.length > 0) {
112+
deprecationMessages.push(
113+
`Passing PLATFORM_PIPES to "bootstrap()" as provider is deprecated. Use the new parameter "pipes" of "bootstrap()" instead.`);
114+
}
115+
}
116+
const xhr = inj.get(XHR, null);
117+
if (xhr) {
118+
compilerProvidersFromAppProviders.push([{provide: XHR, useValue: xhr}]);
119+
deprecationMessages.push(
120+
`Passing an instance of XHR to "bootstrap()" as provider is deprecated. Pass the provider via the new parameter "compilerOptions" of "bootstrap()" instead.`);
121+
}
122+
// Need to copy console from deprecatedAppProviders to compiler providers
123+
// as well so that we can test the above deprecation messages in old style bootstrap
124+
// where we only have app providers!
125+
const console = inj.get(Console, null);
126+
if (console) {
127+
compilerProvidersFromAppProviders.push([{provide: Console, useValue: console}]);
128+
}
129+
}
130+
131+
const injector = ReflectiveInjector.resolveAndCreate([
132+
COMPILER_PROVIDERS, {
133+
provide: CompilerConfig,
134+
useFactory: (platformDirectives: any[], platformPipes: any[]) => {
135+
return new CompilerConfig({
136+
platformDirectives:
137+
_mergeArrays(platformDirectivesFromAppProviders, platformDirectives),
138+
platformPipes: _mergeArrays(platformPipesFromAppProviders, platformPipes),
139+
// let explicit values from the compiler options overwrite options
140+
// from the app providers. E.g. important for the testing platform.
141+
genDebugInfo: _firstDefined(options.useDebug, useDebugFromAppProviders, isDevMode()),
142+
// let explicit values from the compiler options overwrite options
143+
// from the app providers
144+
useJit: _firstDefined(options.useJit, useJitFromAppProviders, true),
145+
// let explicit values from the compiler options overwrite options
146+
// from the app providers
147+
defaultEncapsulation: _firstDefined(
148+
options.defaultEncapsulation, defaultEncapsulationFromAppProviders,
149+
ViewEncapsulation.Emulated)
150+
});
151+
},
152+
deps: [PLATFORM_DIRECTIVES, PLATFORM_PIPES]
153+
},
154+
// options.providers will always contain a provider for XHR as well
155+
// (added by platforms). So allow compilerProvidersFromAppProviders to overwrite this
156+
_mergeArrays(options.providers, compilerProvidersFromAppProviders)
157+
]);
158+
const console: Console = injector.get(Console);
159+
deprecationMessages.forEach((msg) => { console.warn(msg); });
160+
161+
return injector.get(Compiler);
162+
}
163+
}
164+
165+
166+
export const RUNTIME_COMPILER_FACTORY = new _RuntimeCompilerFactory();
167+
168+
function _firstDefined<T>(...args: T[]): T {
169+
for (var i = 0; i < args.length; i++) {
170+
if (args[i] !== undefined) {
171+
return args[i];
172+
}
173+
}
174+
return undefined;
175+
}
176+
177+
function _mergeArrays(...parts: any[][]): any[] {
178+
let result: any[] = [];
179+
parts.forEach((part) => result.push(...part));
180+
return result;
181+
}

modules/@angular/core/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
export * from './src/metadata';
1515
export * from './src/util';
1616
export * from './src/di';
17-
export {createPlatform, assertPlatform, disposePlatform, getPlatform, coreBootstrap, coreLoadAndBootstrap, PlatformRef, ApplicationRef, enableProdMode, lockRunMode, isDevMode} from './src/application_ref';
17+
export {createPlatform, assertPlatform, disposePlatform, getPlatform, bootstrapModuleFactory, bootstrapModule, coreBootstrap, coreLoadAndBootstrap, PlatformRef, ApplicationRef, enableProdMode, lockRunMode, isDevMode, createPlatformFactory} from './src/application_ref';
1818
export {APP_ID, APP_INITIALIZER, PACKAGE_ROOT_URL, PLATFORM_INITIALIZER} from './src/application_tokens';
1919
export * from './src/zone';
2020
export * from './src/render';

modules/@angular/core/src/application_ref.ts

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ import {ConcreteType, IS_DART, Type, isBlank, isPresent, isPromise} from '../src
1414
import {APP_INITIALIZER, PLATFORM_INITIALIZER} from './application_tokens';
1515
import {ChangeDetectorRef} from './change_detection/change_detector_ref';
1616
import {Console} from './console';
17-
import {Inject, Injectable, Injector, Optional, OptionalMetadata, SkipSelf, SkipSelfMetadata, forwardRef} from './di';
17+
import {Inject, Injectable, Injector, OpaqueToken, Optional, OptionalMetadata, ReflectiveInjector, SkipSelf, SkipSelfMetadata, forwardRef} from './di';
18+
import {AppModuleFactory, AppModuleRef} from './linker/app_module_factory';
19+
import {Compiler, CompilerFactory, CompilerOptions} from './linker/compiler';
1820
import {ComponentFactory, ComponentRef} from './linker/component_factory';
1921
import {ComponentFactoryResolver} from './linker/component_factory_resolver';
2022
import {ComponentResolver} from './linker/component_resolver';
@@ -111,6 +113,22 @@ export function createPlatform(injector: Injector): PlatformRef {
111113
return _platform;
112114
}
113115

116+
/**
117+
* Creates a fatory for a platform
118+
*
119+
* @experimental APIs related to application bootstrap are currently under review.
120+
*/
121+
export function createPlatformFactory(name: string, providers: any[]): () => PlatformRef {
122+
const marker = new OpaqueToken(`Platform: ${name}`);
123+
return () => {
124+
if (!getPlatform()) {
125+
createPlatform(
126+
ReflectiveInjector.resolveAndCreate(providers.concat({provide: marker, useValue: true})));
127+
}
128+
return assertPlatform(marker);
129+
};
130+
}
131+
114132
/**
115133
* Checks that there currently is a platform
116134
* which contains the given token as a provider.
@@ -149,6 +167,70 @@ export function getPlatform(): PlatformRef {
149167
return isPresent(_platform) && !_platform.disposed ? _platform : null;
150168
}
151169

170+
/**
171+
* Creates an instance of an `@AppModule` for the given platform
172+
* for offline compilation.
173+
*
174+
* ## Simple Example
175+
*
176+
* ```typescript
177+
* my_module.ts:
178+
*
179+
* @AppModule({
180+
* modules: [BrowserModule]
181+
* })
182+
* class MyModule {}
183+
*
184+
* main.ts:
185+
* import {MyModuleNgFactory} from './my_module.ngfactory';
186+
* import {bootstrapModuleFactory} from '@angular/core';
187+
* import {browserPlatform} from '@angular/platform-browser';
188+
*
189+
* let moduleRef = bootstrapModuleFactory(MyModuleNgFactory, browserPlatform());
190+
* ```
191+
*
192+
* @experimental APIs related to application bootstrap are currently under review.
193+
*/
194+
export function bootstrapModuleFactory<M>(
195+
moduleFactory: AppModuleFactory<M>, platform: PlatformRef): AppModuleRef<M> {
196+
// Note: We need to create the NgZone _before_ we instantiate the module,
197+
// as instantiating the module creates some providers eagerly.
198+
// So we create a mini parent injector that just contains the new NgZone and
199+
// pass that as parent to the AppModuleFactory.
200+
const ngZone = new NgZone({enableLongStackTrace: isDevMode()});
201+
const ngZoneInjector =
202+
ReflectiveInjector.resolveAndCreate([{provide: NgZone, useValue: ngZone}], platform.injector);
203+
return ngZone.run(() => moduleFactory.create(ngZoneInjector));
204+
}
205+
206+
/**
207+
* Creates an instance of an `@AppModule` for a given platform using the given runtime compiler.
208+
*
209+
* ## Simple Example
210+
*
211+
* ```typescript
212+
* @AppModule({
213+
* modules: [BrowserModule]
214+
* })
215+
* class MyModule {}
216+
*
217+
* let moduleRef = bootstrapModule(MyModule, browserPlatform());
218+
* ```
219+
* @stable
220+
*/
221+
export function bootstrapModule<M>(
222+
moduleType: ConcreteType<M>, platform: PlatformRef,
223+
compilerOptions: CompilerOptions = {}): Promise<AppModuleRef<M>> {
224+
const compilerFactory: CompilerFactory = platform.injector.get(CompilerFactory);
225+
const compiler = compilerFactory.createCompiler(compilerOptions);
226+
return compiler.compileAppModuleAsync(moduleType)
227+
.then((moduleFactory) => bootstrapModuleFactory(moduleFactory, platform))
228+
.then((moduleRef) => {
229+
const appRef: ApplicationRef = moduleRef.injector.get(ApplicationRef);
230+
return appRef.waitForAsyncInitializers().then(() => moduleRef);
231+
});
232+
}
233+
152234
/**
153235
* Shortcut for ApplicationRef.bootstrap.
154236
* Requires a platform to be created first.

modules/@angular/core/src/linker.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
// Public API for compiler
1010
export {AppModuleFactory, AppModuleRef} from './linker/app_module_factory';
1111
export {AppModuleFactoryLoader} from './linker/app_module_factory_loader';
12-
export {Compiler, ComponentStillLoadingError} from './linker/compiler';
12+
export {Compiler, CompilerFactory, CompilerOptions, ComponentStillLoadingError} from './linker/compiler';
1313
export {ComponentFactory, ComponentRef} from './linker/component_factory';
1414
export {ComponentFactoryResolver, NoComponentFactoryError} from './linker/component_factory_resolver';
1515
export {ComponentResolver} from './linker/component_resolver';

modules/@angular/core/src/linker/compiler.ts

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import {Injector} from '../di';
1010
import {BaseException} from '../facade/exceptions';
1111
import {ConcreteType, Type, stringify} from '../facade/lang';
12+
import {ViewEncapsulation} from '../metadata';
1213
import {AppModuleMetadata} from '../metadata/app_module';
1314

1415
import {AppModuleFactory} from './app_module_factory';
@@ -86,3 +87,64 @@ export class Compiler {
8687
*/
8788
clearCacheFor(type: Type) {}
8889
}
90+
91+
/**
92+
* Options for creating a compiler
93+
*
94+
* @experimental
95+
*/
96+
export type CompilerOptions = {
97+
useDebug?: boolean,
98+
useJit?: boolean,
99+
defaultEncapsulation?: ViewEncapsulation,
100+
providers?: any[],
101+
deprecatedAppProviders?: any[]
102+
}
103+
104+
/**
105+
* A factory for creating a Compiler
106+
*
107+
* @experimental
108+
*/
109+
export abstract class CompilerFactory {
110+
static mergeOptions(defaultOptions: CompilerOptions = {}, newOptions: CompilerOptions = {}):
111+
CompilerOptions {
112+
return {
113+
useDebug: _firstDefined(newOptions.useDebug, defaultOptions.useDebug),
114+
useJit: _firstDefined(newOptions.useJit, defaultOptions.useJit),
115+
defaultEncapsulation:
116+
_firstDefined(newOptions.defaultEncapsulation, defaultOptions.defaultEncapsulation),
117+
providers: _mergeArrays(defaultOptions.providers, newOptions.providers),
118+
deprecatedAppProviders:
119+
_mergeArrays(defaultOptions.deprecatedAppProviders, newOptions.deprecatedAppProviders)
120+
};
121+
}
122+
123+
withDefaults(options: CompilerOptions = {}): CompilerFactory {
124+
return new _DefaultApplyingCompilerFactory(this, options);
125+
}
126+
abstract createCompiler(options?: CompilerOptions): Compiler;
127+
}
128+
129+
class _DefaultApplyingCompilerFactory extends CompilerFactory {
130+
constructor(private _delegate: CompilerFactory, private _options: CompilerOptions) { super(); }
131+
132+
createCompiler(options: CompilerOptions = {}): Compiler {
133+
return this._delegate.createCompiler(CompilerFactory.mergeOptions(this._options, options));
134+
}
135+
}
136+
137+
function _firstDefined<T>(...args: T[]): T {
138+
for (var i = 0; i < args.length; i++) {
139+
if (args[i] !== undefined) {
140+
return args[i];
141+
}
142+
}
143+
return undefined;
144+
}
145+
146+
function _mergeArrays(...parts: any[][]): any[] {
147+
let result: any[] = [];
148+
parts.forEach((part) => result.push(...part));
149+
return result;
150+
}

0 commit comments

Comments
 (0)