Skip to content

Commit

Permalink
refactor(core): clean up platform bootstrap and initTestEnvironment
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
tbosch committed Jul 8, 2016
1 parent d84a43c commit fa47890
Show file tree
Hide file tree
Showing 33 changed files with 467 additions and 313 deletions.
4 changes: 3 additions & 1 deletion modules/@angular/compiler-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,10 @@ bootstrap.ts
-------------

import {MainModuleNgFactory} from './main_module.ngfactory';
import {bootstrapModuleFactory} from '@angular/core';
import {browserPlatform} from '@angular/platform-browser';

MainModuleNgFactory.create(browserPlatform().injector);
bootstrapModuleFactory(MainModuleNgFactory, browserPlatform());
```

## Configuration
Expand Down
4 changes: 2 additions & 2 deletions modules/@angular/compiler-cli/integrationtest/test/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
* found in the LICENSE file at https://angular.io/license
*/

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

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

export function createModule<M>(factory: AppModuleFactory<M>): AppModuleRef<M> {
return factory.create(serverPlatform().injector);
return bootstrapModuleFactory(factory, serverPlatform());
}

export function createComponent<C>(
Expand Down
2 changes: 1 addition & 1 deletion modules/@angular/compiler/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* @description
* Starting point to import all compiler APIs.
*/
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';
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';
export {ElementSchemaRegistry} from './src/schema/element_schema_registry';

export * from './src/template_ast';
Expand Down
111 changes: 110 additions & 1 deletion modules/@angular/compiler/src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/

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

export * from './template_ast';
export {TEMPLATE_TRANSFORMS} from './template_parser';
Expand Down Expand Up @@ -39,13 +39,16 @@ import {ViewResolver} from './view_resolver';
import {DirectiveResolver} from './directive_resolver';
import {PipeResolver} from './pipe_resolver';
import {Console, Reflector, reflector, ReflectorReader} from '../core_private';
import {XHR} from './xhr';

/**
* A set of providers that provide `RuntimeCompiler` and its dependencies to use for
* template compilation.
*/
export const COMPILER_PROVIDERS: Array<any|Type|{[k: string]: any}|any[]> =
/*@ts2dart_const*/[
{provide: PLATFORM_DIRECTIVES, useValue: [], multi: true},
{provide: PLATFORM_PIPES, useValue: [], multi: true},
{provide: Reflector, useValue: reflector},
{provide: ReflectorReader, useExisting: Reflector},
Console,
Expand All @@ -70,3 +73,109 @@ export const COMPILER_PROVIDERS: Array<any|Type|{[k: string]: any}|any[]> =
DirectiveResolver,
PipeResolver
];

@Injectable()
export class _RuntimeCompilerFactory extends CompilerFactory {
createCompiler(options: CompilerOptions): Compiler {
const deprecationMessages: string[] = [];
let platformDirectivesFromAppProviders: any[] = [];
let platformPipesFromAppProviders: any[] = [];
let compilerProvidersFromAppProviders: any[] = [];
let useDebugFromAppProviders: boolean;
let useJitFromAppProviders: boolean;
let defaultEncapsulationFromAppProviders: ViewEncapsulation;

if (options.deprecatedAppProviders && options.deprecatedAppProviders.length > 0) {
// Note: This is a hack to still support the old way
// of configuring platform directives / pipes and the compiler xhr.
// This will soon be deprecated!
const inj = ReflectiveInjector.resolveAndCreate(options.deprecatedAppProviders);
const compilerConfig: CompilerConfig = inj.get(CompilerConfig, null);
if (compilerConfig) {
platformDirectivesFromAppProviders = compilerConfig.platformDirectives;
platformPipesFromAppProviders = compilerConfig.platformPipes;
useJitFromAppProviders = compilerConfig.useJit;
useDebugFromAppProviders = compilerConfig.genDebugInfo;
defaultEncapsulationFromAppProviders = compilerConfig.defaultEncapsulation;
deprecationMessages.push(
`Passing a CompilerConfig to "bootstrap()" as provider is deprecated. Pass the provider via the new parameter "compilerOptions" of "bootstrap()" instead.`);
} else {
// If nobody provided a CompilerConfig, use the
// PLATFORM_DIRECTIVES / PLATFORM_PIPES values directly if existing
platformDirectivesFromAppProviders = inj.get(PLATFORM_DIRECTIVES, []);
if (platformDirectivesFromAppProviders.length > 0) {
deprecationMessages.push(
`Passing PLATFORM_DIRECTIVES to "bootstrap()" as provider is deprecated. Use the new parameter "directives" of "bootstrap()" instead.`);
}
platformPipesFromAppProviders = inj.get(PLATFORM_PIPES, []);
if (platformPipesFromAppProviders.length > 0) {
deprecationMessages.push(
`Passing PLATFORM_PIPES to "bootstrap()" as provider is deprecated. Use the new parameter "pipes" of "bootstrap()" instead.`);
}
}
const xhr = inj.get(XHR, null);
if (xhr) {
compilerProvidersFromAppProviders.push([{provide: XHR, useValue: xhr}]);
deprecationMessages.push(
`Passing an instance of XHR to "bootstrap()" as provider is deprecated. Pass the provider via the new parameter "compilerOptions" of "bootstrap()" instead.`);
}
// Need to copy console from deprecatedAppProviders to compiler providers
// as well so that we can test the above deprecation messages in old style bootstrap
// where we only have app providers!
const console = inj.get(Console, null);
if (console) {
compilerProvidersFromAppProviders.push([{provide: Console, useValue: console}]);
}
}

const injector = ReflectiveInjector.resolveAndCreate([
COMPILER_PROVIDERS, {
provide: CompilerConfig,
useFactory: (platformDirectives: any[], platformPipes: any[]) => {
return new CompilerConfig({
platformDirectives:
_mergeArrays(platformDirectivesFromAppProviders, platformDirectives),
platformPipes: _mergeArrays(platformPipesFromAppProviders, platformPipes),
// let explicit values from the compiler options overwrite options
// from the app providers. E.g. important for the testing platform.
genDebugInfo: _firstDefined(options.useDebug, useDebugFromAppProviders, isDevMode()),
// let explicit values from the compiler options overwrite options
// from the app providers
useJit: _firstDefined(options.useJit, useJitFromAppProviders, true),
// let explicit values from the compiler options overwrite options
// from the app providers
defaultEncapsulation: _firstDefined(
options.defaultEncapsulation, defaultEncapsulationFromAppProviders,
ViewEncapsulation.Emulated)
});
},
deps: [PLATFORM_DIRECTIVES, PLATFORM_PIPES]
},
// options.providers will always contain a provider for XHR as well
// (added by platforms). So allow compilerProvidersFromAppProviders to overwrite this
_mergeArrays(options.providers, compilerProvidersFromAppProviders)
]);
const console: Console = injector.get(Console);
deprecationMessages.forEach((msg) => { console.warn(msg); });

return injector.get(Compiler);
}
}


export const RUNTIME_COMPILER_FACTORY = new _RuntimeCompilerFactory();

function _firstDefined<T>(...args: T[]): T {
for (var i = 0; i < args.length; i++) {
if (args[i] !== undefined) {
return args[i];
}
}
return undefined;
}

function _mergeArrays(...parts: any[][]): any[] {
let result: any[] = [];
parts.forEach((part) => result.push(...part));
return result;
}
2 changes: 1 addition & 1 deletion modules/@angular/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
export * from './src/metadata';
export * from './src/util';
export * from './src/di';
export {createPlatform, assertPlatform, disposePlatform, getPlatform, coreBootstrap, coreLoadAndBootstrap, PlatformRef, ApplicationRef, enableProdMode, lockRunMode, isDevMode} from './src/application_ref';
export {createPlatform, assertPlatform, disposePlatform, getPlatform, bootstrapModuleFactory, bootstrapModule, coreBootstrap, coreLoadAndBootstrap, PlatformRef, ApplicationRef, enableProdMode, lockRunMode, isDevMode, createPlatformFactory} from './src/application_ref';
export {APP_ID, APP_INITIALIZER, PACKAGE_ROOT_URL, PLATFORM_INITIALIZER} from './src/application_tokens';
export * from './src/zone';
export * from './src/render';
Expand Down
84 changes: 83 additions & 1 deletion modules/@angular/core/src/application_ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ import {ConcreteType, IS_DART, Type, isBlank, isPresent, isPromise} from '../src
import {APP_INITIALIZER, PLATFORM_INITIALIZER} from './application_tokens';
import {ChangeDetectorRef} from './change_detection/change_detector_ref';
import {Console} from './console';
import {Inject, Injectable, Injector, Optional, OptionalMetadata, SkipSelf, SkipSelfMetadata, forwardRef} from './di';
import {Inject, Injectable, Injector, OpaqueToken, Optional, OptionalMetadata, ReflectiveInjector, SkipSelf, SkipSelfMetadata, forwardRef} from './di';
import {AppModuleFactory, AppModuleRef} from './linker/app_module_factory';
import {Compiler, CompilerFactory, CompilerOptions} from './linker/compiler';
import {ComponentFactory, ComponentRef} from './linker/component_factory';
import {ComponentFactoryResolver} from './linker/component_factory_resolver';
import {ComponentResolver} from './linker/component_resolver';
Expand Down Expand Up @@ -111,6 +113,22 @@ export function createPlatform(injector: Injector): PlatformRef {
return _platform;
}

/**
* Creates a fatory for a platform
*
* @experimental APIs related to application bootstrap are currently under review.
*/
export function createPlatformFactory(name: string, providers: any[]): () => PlatformRef {
const marker = new OpaqueToken(`Platform: ${name}`);
return () => {
if (!getPlatform()) {
createPlatform(
ReflectiveInjector.resolveAndCreate(providers.concat({provide: marker, useValue: true})));
}
return assertPlatform(marker);
};
}

/**
* Checks that there currently is a platform
* which contains the given token as a provider.
Expand Down Expand Up @@ -149,6 +167,70 @@ export function getPlatform(): PlatformRef {
return isPresent(_platform) && !_platform.disposed ? _platform : null;
}

/**
* Creates an instance of an `@AppModule` for the given platform
* for offline compilation.
*
* ## Simple Example
*
* ```typescript
* my_module.ts:
*
* @AppModule({
* modules: [BrowserModule]
* })
* class MyModule {}
*
* main.ts:
* import {MyModuleNgFactory} from './my_module.ngfactory';
* import {bootstrapModuleFactory} from '@angular/core';
* import {browserPlatform} from '@angular/platform-browser';
*
* let moduleRef = bootstrapModuleFactory(MyModuleNgFactory, browserPlatform());
* ```
*
* @experimental APIs related to application bootstrap are currently under review.
*/
export function bootstrapModuleFactory<M>(
moduleFactory: AppModuleFactory<M>, platform: PlatformRef): AppModuleRef<M> {
// Note: We need to create the NgZone _before_ we instantiate the module,
// as instantiating the module creates some providers eagerly.
// So we create a mini parent injector that just contains the new NgZone and
// pass that as parent to the AppModuleFactory.
const ngZone = new NgZone({enableLongStackTrace: isDevMode()});
const ngZoneInjector =
ReflectiveInjector.resolveAndCreate([{provide: NgZone, useValue: ngZone}], platform.injector);
return ngZone.run(() => moduleFactory.create(ngZoneInjector));
}

/**
* Creates an instance of an `@AppModule` for a given platform using the given runtime compiler.
*
* ## Simple Example
*
* ```typescript
* @AppModule({
* modules: [BrowserModule]
* })
* class MyModule {}
*
* let moduleRef = bootstrapModule(MyModule, browserPlatform());
* ```
* @stable
*/
export function bootstrapModule<M>(
moduleType: ConcreteType<M>, platform: PlatformRef,
compilerOptions: CompilerOptions = {}): Promise<AppModuleRef<M>> {
const compilerFactory: CompilerFactory = platform.injector.get(CompilerFactory);
const compiler = compilerFactory.createCompiler(compilerOptions);
return compiler.compileAppModuleAsync(moduleType)
.then((moduleFactory) => bootstrapModuleFactory(moduleFactory, platform))
.then((moduleRef) => {
const appRef: ApplicationRef = moduleRef.injector.get(ApplicationRef);
return appRef.waitForAsyncInitializers().then(() => moduleRef);
});
}

/**
* Shortcut for ApplicationRef.bootstrap.
* Requires a platform to be created first.
Expand Down
2 changes: 1 addition & 1 deletion modules/@angular/core/src/linker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// Public API for compiler
export {AppModuleFactory, AppModuleRef} from './linker/app_module_factory';
export {AppModuleFactoryLoader} from './linker/app_module_factory_loader';
export {Compiler, ComponentStillLoadingError} from './linker/compiler';
export {Compiler, CompilerFactory, CompilerOptions, ComponentStillLoadingError} from './linker/compiler';
export {ComponentFactory, ComponentRef} from './linker/component_factory';
export {ComponentFactoryResolver, NoComponentFactoryError} from './linker/component_factory_resolver';
export {ComponentResolver} from './linker/component_resolver';
Expand Down
62 changes: 62 additions & 0 deletions modules/@angular/core/src/linker/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import {Injector} from '../di';
import {BaseException} from '../facade/exceptions';
import {ConcreteType, Type, stringify} from '../facade/lang';
import {ViewEncapsulation} from '../metadata';
import {AppModuleMetadata} from '../metadata/app_module';

import {AppModuleFactory} from './app_module_factory';
Expand Down Expand Up @@ -86,3 +87,64 @@ export class Compiler {
*/
clearCacheFor(type: Type) {}
}

/**
* Options for creating a compiler
*
* @experimental
*/
export type CompilerOptions = {
useDebug?: boolean,
useJit?: boolean,
defaultEncapsulation?: ViewEncapsulation,
providers?: any[],
deprecatedAppProviders?: any[]
}

/**
* A factory for creating a Compiler
*
* @experimental
*/
export abstract class CompilerFactory {
static mergeOptions(defaultOptions: CompilerOptions = {}, newOptions: CompilerOptions = {}):
CompilerOptions {
return {
useDebug: _firstDefined(newOptions.useDebug, defaultOptions.useDebug),
useJit: _firstDefined(newOptions.useJit, defaultOptions.useJit),
defaultEncapsulation:
_firstDefined(newOptions.defaultEncapsulation, defaultOptions.defaultEncapsulation),
providers: _mergeArrays(defaultOptions.providers, newOptions.providers),
deprecatedAppProviders:
_mergeArrays(defaultOptions.deprecatedAppProviders, newOptions.deprecatedAppProviders)
};
}

withDefaults(options: CompilerOptions = {}): CompilerFactory {
return new _DefaultApplyingCompilerFactory(this, options);
}
abstract createCompiler(options?: CompilerOptions): Compiler;
}

class _DefaultApplyingCompilerFactory extends CompilerFactory {
constructor(private _delegate: CompilerFactory, private _options: CompilerOptions) { super(); }

createCompiler(options: CompilerOptions = {}): Compiler {
return this._delegate.createCompiler(CompilerFactory.mergeOptions(this._options, options));
}
}

function _firstDefined<T>(...args: T[]): T {
for (var i = 0; i < args.length; i++) {
if (args[i] !== undefined) {
return args[i];
}
}
return undefined;
}

function _mergeArrays(...parts: any[][]): any[] {
let result: any[] = [];
parts.forEach((part) => result.push(...part));
return result;
}
Loading

0 comments on commit fa47890

Please sign in to comment.