chore: fix DDC errors / warnings

Closes #7195
This commit is contained in:
Misko Hevery 2016-02-19 11:49:31 -08:00 committed by Miško Hevery
parent ef9e40e82b
commit 14f0e9ada8
88 changed files with 527 additions and 468 deletions

View File

@ -1,6 +1,7 @@
import {ControlValueAccessor} from './control_value_accessor'; import {ControlValueAccessor} from './control_value_accessor';
import {AbstractControlDirective} from './abstract_control_directive'; import {AbstractControlDirective} from './abstract_control_directive';
import {unimplemented} from 'angular2/src/facade/exceptions'; import {unimplemented} from 'angular2/src/facade/exceptions';
import {AsyncValidatorFn, ValidatorFn} from './validators';
/** /**
* A base class that all control directive extend. * A base class that all control directive extend.
@ -12,8 +13,8 @@ export abstract class NgControl extends AbstractControlDirective {
name: string = null; name: string = null;
valueAccessor: ControlValueAccessor = null; valueAccessor: ControlValueAccessor = null;
get validator(): Function { return unimplemented(); } get validator(): ValidatorFn { return <ValidatorFn>unimplemented(); }
get asyncValidator(): Function { return unimplemented(); } get asyncValidator(): AsyncValidatorFn { return <AsyncValidatorFn>unimplemented(); }
abstract viewToModelUpdate(newValue: any): void; abstract viewToModelUpdate(newValue: any): void;
} }

View File

@ -16,7 +16,8 @@ import {ControlContainer} from './control_container';
import {controlPath, composeValidators, composeAsyncValidators} from './shared'; import {controlPath, composeValidators, composeAsyncValidators} from './shared';
import {ControlGroup} from '../model'; import {ControlGroup} from '../model';
import {Form} from './form_interface'; import {Form} from './form_interface';
import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {AsyncValidatorFn, ValidatorFn} from './validators';
const controlGroupProvider = const controlGroupProvider =
CONST_EXPR(new Provider(ControlContainer, {useExisting: forwardRef(() => NgControlGroup)})); CONST_EXPR(new Provider(ControlContainer, {useExisting: forwardRef(() => NgControlGroup)}));
@ -106,7 +107,7 @@ export class NgControlGroup extends ControlContainer implements OnInit,
*/ */
get formDirective(): Form { return this._parent.formDirective; } get formDirective(): Form { return this._parent.formDirective; }
get validator(): Function { return composeValidators(this._validators); } get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); } get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
} }

View File

@ -27,7 +27,8 @@ import {
selectValueAccessor selectValueAccessor
} from './shared'; } from './shared';
import {Control} from '../model'; import {Control} from '../model';
import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {ValidatorFn, AsyncValidatorFn} from './validators';
const controlNameBinding = const controlNameBinding =
@ -136,9 +137,9 @@ export class NgControlName extends NgControl implements OnChanges,
get formDirective(): any { return this._parent.formDirective; } get formDirective(): any { return this._parent.formDirective; }
get validator(): Function { return composeValidators(this._validators); } get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); } get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
get control(): Control { return this.formDirective.getControl(this); } get control(): Control { return this.formDirective.getControl(this); }
} }

View File

@ -23,6 +23,7 @@ import {
isPropertyUpdated, isPropertyUpdated,
selectValueAccessor selectValueAccessor
} from './shared'; } from './shared';
import {ValidatorFn, AsyncValidatorFn} from './validators';
const formControlBinding = const formControlBinding =
CONST_EXPR(new Provider(NgControl, {useExisting: forwardRef(() => NgFormControl)})); CONST_EXPR(new Provider(NgControl, {useExisting: forwardRef(() => NgFormControl)}));
@ -110,9 +111,9 @@ export class NgFormControl extends NgControl implements OnChanges {
get path(): string[] { return []; } get path(): string[] { return []; }
get validator(): Function { return composeValidators(this._validators); } get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); } get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
get control(): Control { return this.form; } get control(): Control { return this.form; }

View File

@ -3,7 +3,6 @@ import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import { import {
OnChanges, OnChanges,
SimpleChange, SimpleChange,
Query,
Directive, Directive,
forwardRef, forwardRef,
Provider, Provider,
@ -14,7 +13,7 @@ import {
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {NgControl} from './ng_control'; import {NgControl} from './ng_control';
import {Control} from '../model'; import {Control} from '../model';
import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import { import {
setUpControl, setUpControl,
isPropertyUpdated, isPropertyUpdated,
@ -22,6 +21,7 @@ import {
composeValidators, composeValidators,
composeAsyncValidators composeAsyncValidators
} from './shared'; } from './shared';
import {ValidatorFn, AsyncValidatorFn} from './validators';
const formControlBinding = const formControlBinding =
CONST_EXPR(new Provider(NgControl, {useExisting: forwardRef(() => NgModel)})); CONST_EXPR(new Provider(NgControl, {useExisting: forwardRef(() => NgModel)}));
@ -88,9 +88,9 @@ export class NgModel extends NgControl implements OnChanges {
get path(): string[] { return []; } get path(): string[] { return []; }
get validator(): Function { return composeValidators(this._validators); } get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); } get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
viewToModelUpdate(newValue: any): void { viewToModelUpdate(newValue: any): void {
this.viewModel = newValue; this.viewModel = newValue;

View File

@ -10,3 +10,11 @@ Function normalizeValidator(dynamic validator){
} }
} }
Function normalizeAsyncValidator(dynamic validator){
if (validator is Validator) {
return (c) => validator.validate(c);
} else {
return validator;
}
}

View File

@ -1,14 +1,18 @@
import {Validator} from './validators'; import {AbstractControl} from "../model";
import {Control} from "../model"; import {Validator, ValidatorFn, AsyncValidatorFn} from './validators';
export type ctrlFunc = ((c: Control) => { export function normalizeValidator(validator: ValidatorFn | Validator): ValidatorFn {
[key: string]: any
});
export function normalizeValidator(validator: (ctrlFunc | Validator)): ctrlFunc {
if ((<Validator>validator).validate !== undefined) { if ((<Validator>validator).validate !== undefined) {
return (c: Control) => (<Validator>validator).validate(c); return (c: AbstractControl) => (<Validator>validator).validate(c);
} else { } else {
return <ctrlFunc>validator; return <ValidatorFn>validator;
}
}
export function normalizeAsyncValidator(validator: AsyncValidatorFn | Validator): AsyncValidatorFn {
if ((<Validator>validator).validate !== undefined) {
return (c: AbstractControl) => Promise.resolve((<Validator>validator).validate(c));
} else {
return <AsyncValidatorFn>validator;
} }
} }

View File

@ -14,7 +14,8 @@ import {NumberValueAccessor} from './number_value_accessor';
import {CheckboxControlValueAccessor} from './checkbox_value_accessor'; import {CheckboxControlValueAccessor} from './checkbox_value_accessor';
import {SelectControlValueAccessor} from './select_control_value_accessor'; import {SelectControlValueAccessor} from './select_control_value_accessor';
import {RadioControlValueAccessor} from './radio_control_value_accessor'; import {RadioControlValueAccessor} from './radio_control_value_accessor';
import {normalizeValidator} from './normalize_validator'; import {normalizeValidator, normalizeAsyncValidator} from './normalize_validator';
import {ValidatorFn, AsyncValidatorFn} from './validators';
export function controlPath(name: string, parent: ControlContainer): string[] { export function controlPath(name: string, parent: ControlContainer): string[] {
@ -56,13 +57,14 @@ function _throwError(dir: AbstractControlDirective, message: string): void {
throw new BaseException(`${message} '${path}'`); throw new BaseException(`${message} '${path}'`);
} }
export function composeValidators(validators: /* Array<Validator|Function> */ any[]): Function { export function composeValidators(validators: /* Array<Validator|Function> */ any[]): ValidatorFn {
return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null; return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null;
} }
export function composeAsyncValidators( export function composeAsyncValidators(
validators: /* Array<Validator|Function> */ any[]): Function { validators: /* Array<Validator|Function> */ any[]): AsyncValidatorFn {
return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeValidator)) : null; return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) :
null;
} }
export function isPropertyUpdated(changes: {[key: string]: any}, viewModel: any): boolean { export function isPropertyUpdated(changes: {[key: string]: any}, viewModel: any): boolean {

View File

@ -1,11 +1,12 @@
import {forwardRef, Provider, OpaqueToken, Attribute, Directive} from 'angular2/core'; import {forwardRef, Provider, Attribute, Directive} from 'angular2/core';
import {CONST_EXPR} from 'angular2/src/facade/lang'; import {CONST_EXPR} from 'angular2/src/facade/lang';
import {Validators, NG_VALIDATORS} from '../validators'; import {Validators, NG_VALIDATORS} from '../validators';
import {Control} from '../model'; import {AbstractControl} from '../model';
import * as modelModule from '../model'; import * as modelModule from '../model';
import {NumberWrapper} from "angular2/src/facade/lang"; import {NumberWrapper} from "angular2/src/facade/lang";
/** /**
* An interface that can be implemented by classes that can act as validators. * An interface that can be implemented by classes that can act as validators.
* *
@ -23,7 +24,7 @@ import {NumberWrapper} from "angular2/src/facade/lang";
* } * }
* ``` * ```
*/ */
export interface Validator { validate(c: modelModule.Control): {[key: string]: any}; } export interface Validator { validate(c: modelModule.AbstractControl): {[key: string]: any}; }
const REQUIRED_VALIDATOR = const REQUIRED_VALIDATOR =
CONST_EXPR(new Provider(NG_VALIDATORS, {useValue: Validators.required, multi: true})); CONST_EXPR(new Provider(NG_VALIDATORS, {useValue: Validators.required, multi: true}));
@ -45,6 +46,11 @@ const REQUIRED_VALIDATOR =
export class RequiredValidator { export class RequiredValidator {
} }
export interface ValidatorFn { (c: AbstractControl): {[key: string]: any}; }
export interface AsyncValidatorFn {
(c: AbstractControl): any /*Promise<{[key: string]: any}>|Observable<{[key: string]: any}>*/;
}
/** /**
* Provivder which adds {@link MinLengthValidator} to {@link NG_VALIDATORS}. * Provivder which adds {@link MinLengthValidator} to {@link NG_VALIDATORS}.
* *
@ -64,13 +70,13 @@ const MIN_LENGTH_VALIDATOR = CONST_EXPR(
providers: [MIN_LENGTH_VALIDATOR] providers: [MIN_LENGTH_VALIDATOR]
}) })
export class MinLengthValidator implements Validator { export class MinLengthValidator implements Validator {
private _validator: Function; private _validator: ValidatorFn;
constructor(@Attribute("minlength") minLength: string) { constructor(@Attribute("minlength") minLength: string) {
this._validator = Validators.minLength(NumberWrapper.parseInt(minLength, 10)); this._validator = Validators.minLength(NumberWrapper.parseInt(minLength, 10));
} }
validate(c: Control): {[key: string]: any} { return this._validator(c); } validate(c: AbstractControl): {[key: string]: any} { return this._validator(c); }
} }
/** /**
@ -92,13 +98,13 @@ const MAX_LENGTH_VALIDATOR = CONST_EXPR(
providers: [MAX_LENGTH_VALIDATOR] providers: [MAX_LENGTH_VALIDATOR]
}) })
export class MaxLengthValidator implements Validator { export class MaxLengthValidator implements Validator {
private _validator: Function; private _validator: ValidatorFn;
constructor(@Attribute("maxlength") maxLength: string) { constructor(@Attribute("maxlength") maxLength: string) {
this._validator = Validators.maxLength(NumberWrapper.parseInt(maxLength, 10)); this._validator = Validators.maxLength(NumberWrapper.parseInt(maxLength, 10));
} }
validate(c: Control): {[key: string]: any} { return this._validator(c); } validate(c: AbstractControl): {[key: string]: any} { return this._validator(c); }
} }
@ -121,11 +127,11 @@ const PATTERN_VALIDATOR = CONST_EXPR(
providers: [PATTERN_VALIDATOR] providers: [PATTERN_VALIDATOR]
}) })
export class PatternValidator implements Validator { export class PatternValidator implements Validator {
private _validator: Function; private _validator: ValidatorFn;
constructor(@Attribute("pattern") pattern: string) { constructor(@Attribute("pattern") pattern: string) {
this._validator = Validators.pattern(pattern); this._validator = Validators.pattern(pattern);
} }
validate(c: Control): {[key: string]: any} { return this._validator(c); } validate(c: AbstractControl): {[key: string]: any} { return this._validator(c); }
} }

View File

@ -2,6 +2,7 @@ import {Injectable} from 'angular2/core';
import {StringMapWrapper} from 'angular2/src/facade/collection'; import {StringMapWrapper} from 'angular2/src/facade/collection';
import {isPresent, isArray, CONST_EXPR, Type} from 'angular2/src/facade/lang'; import {isPresent, isArray, CONST_EXPR, Type} from 'angular2/src/facade/lang';
import * as modelModule from './model'; import * as modelModule from './model';
import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
/** /**
@ -56,16 +57,18 @@ export class FormBuilder {
group(controlsConfig: {[key: string]: any}, group(controlsConfig: {[key: string]: any},
extra: {[key: string]: any} = null): modelModule.ControlGroup { extra: {[key: string]: any} = null): modelModule.ControlGroup {
var controls = this._reduceControls(controlsConfig); var controls = this._reduceControls(controlsConfig);
var optionals = isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null; var optionals = <{[key: string]: boolean}>(
var validator = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null; isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null);
var asyncValidator = isPresent(extra) ? StringMapWrapper.get(extra, "asyncValidator") : null; var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null;
var asyncValidator: AsyncValidatorFn =
isPresent(extra) ? StringMapWrapper.get(extra, "asyncValidator") : null;
return new modelModule.ControlGroup(controls, optionals, validator, asyncValidator); return new modelModule.ControlGroup(controls, optionals, validator, asyncValidator);
} }
/** /**
* Construct a new {@link Control} with the given `value`,`validator`, and `asyncValidator`. * Construct a new {@link Control} with the given `value`,`validator`, and `asyncValidator`.
*/ */
control(value: Object, validator: Function = null, control(value: Object, validator: ValidatorFn = null,
asyncValidator: Function = null): modelModule.Control { asyncValidator: AsyncValidatorFn = null): modelModule.Control {
return new modelModule.Control(value, validator, asyncValidator); return new modelModule.Control(value, validator, asyncValidator);
} }
@ -73,8 +76,8 @@ export class FormBuilder {
* Construct an array of {@link Control}s from the given `controlsConfig` array of * Construct an array of {@link Control}s from the given `controlsConfig` array of
* configuration, with the given optional `validator` and `asyncValidator`. * configuration, with the given optional `validator` and `asyncValidator`.
*/ */
array(controlsConfig: any[], validator: Function = null, array(controlsConfig: any[], validator: ValidatorFn = null,
asyncValidator: Function = null): modelModule.ControlArray { asyncValidator: AsyncValidatorFn = null): modelModule.ControlArray {
var controls = controlsConfig.map(c => this._createControl(c)); var controls = controlsConfig.map(c => this._createControl(c));
return new modelModule.ControlArray(controls, validator, asyncValidator); return new modelModule.ControlArray(controls, validator, asyncValidator);
} }
@ -98,8 +101,8 @@ export class FormBuilder {
} else if (isArray(controlConfig)) { } else if (isArray(controlConfig)) {
var value = controlConfig[0]; var value = controlConfig[0];
var validator = controlConfig.length > 1 ? controlConfig[1] : null; var validator: ValidatorFn = controlConfig.length > 1 ? controlConfig[1] : null;
var asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null; var asyncValidator: AsyncValidatorFn = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator); return this.control(value, validator, asyncValidator);
} else { } else {

View File

@ -1,7 +1,8 @@
import {StringWrapper, isPresent, isBlank, normalizeBool} from 'angular2/src/facade/lang'; import {isPresent, isBlank, normalizeBool} from 'angular2/src/facade/lang';
import {Observable, EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; import {Observable, EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {PromiseWrapper} from 'angular2/src/facade/promise'; import {PromiseWrapper} from 'angular2/src/facade/promise';
import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection'; import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection';
import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
/** /**
* Indicates that a Control is valid, i.e. that no errors exist in the input value. * Indicates that a Control is valid, i.e. that no errors exist in the input value.
@ -64,7 +65,7 @@ export abstract class AbstractControl {
private _parent: ControlGroup | ControlArray; private _parent: ControlGroup | ControlArray;
private _asyncValidationSubscription: any; private _asyncValidationSubscription: any;
constructor(public validator: Function, public asyncValidator: Function) {} constructor(public validator: ValidatorFn, public asyncValidator: AsyncValidatorFn) {}
get value(): any { return this._value; } get value(): any { return this._value; }
@ -137,15 +138,17 @@ export abstract class AbstractControl {
} }
} }
private _runValidator() { return isPresent(this.validator) ? this.validator(this) : null; } private _runValidator(): {[key: string]: any} {
return isPresent(this.validator) ? this.validator(this) : null;
}
private _runAsyncValidator(emitEvent: boolean): void { private _runAsyncValidator(emitEvent: boolean): void {
if (isPresent(this.asyncValidator)) { if (isPresent(this.asyncValidator)) {
this._status = PENDING; this._status = PENDING;
this._cancelExistingSubscription(); this._cancelExistingSubscription();
var obs = toObservable(this.asyncValidator(this)); var obs = toObservable(this.asyncValidator(this));
this._asyncValidationSubscription = this._asyncValidationSubscription = ObservableWrapper.subscribe(
ObservableWrapper.subscribe(obs, res => this.setErrors(res, {emitEvent: emitEvent})); obs, (res: {[key: string]: any}) => this.setErrors(res, {emitEvent: emitEvent}));
} }
} }
@ -268,7 +271,8 @@ export class Control extends AbstractControl {
/** @internal */ /** @internal */
_onChange: Function; _onChange: Function;
constructor(value: any = null, validator: Function = null, asyncValidator: Function = null) { constructor(value: any = null, validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator); super(validator, asyncValidator);
this._value = value; this._value = value;
this.updateValueAndValidity({onlySelf: true, emitEvent: false}); this.updateValueAndValidity({onlySelf: true, emitEvent: false});
@ -331,8 +335,8 @@ export class ControlGroup extends AbstractControl {
private _optionals: {[key: string]: boolean}; private _optionals: {[key: string]: boolean};
constructor(public controls: {[key: string]: AbstractControl}, constructor(public controls: {[key: string]: AbstractControl},
optionals: {[key: string]: boolean} = null, validator: Function = null, optionals: {[key: string]: boolean} = null, validator: ValidatorFn = null,
asyncValidator: Function = null) { asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator); super(validator, asyncValidator);
this._optionals = isPresent(optionals) ? optionals : {}; this._optionals = isPresent(optionals) ? optionals : {};
this._initObservables(); this._initObservables();
@ -444,8 +448,8 @@ export class ControlGroup extends AbstractControl {
* ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview)) * ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview))
*/ */
export class ControlArray extends AbstractControl { export class ControlArray extends AbstractControl {
constructor(public controls: AbstractControl[], validator: Function = null, constructor(public controls: AbstractControl[], validator: ValidatorFn = null,
asyncValidator: Function = null) { asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator); super(validator, asyncValidator);
this._initObservables(); this._initObservables();
this._setParentForControls(); this._setParentForControls();

View File

@ -5,6 +5,7 @@ import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {OpaqueToken} from 'angular2/core'; import {OpaqueToken} from 'angular2/core';
import * as modelModule from './model'; import * as modelModule from './model';
import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
/** /**
* Providers for validators to be used for {@link Control}s in a form. * Providers for validators to be used for {@link Control}s in a form.
@ -43,7 +44,7 @@ export class Validators {
/** /**
* Validator that requires controls to have a non-empty value. * Validator that requires controls to have a non-empty value.
*/ */
static required(control: modelModule.Control): {[key: string]: boolean} { static required(control: modelModule.AbstractControl): {[key: string]: boolean} {
return isBlank(control.value) || (isString(control.value) && control.value == "") ? return isBlank(control.value) || (isString(control.value) && control.value == "") ?
{"required": true} : {"required": true} :
null; null;
@ -52,8 +53,8 @@ export class Validators {
/** /**
* Validator that requires controls to have a value of a minimum length. * Validator that requires controls to have a value of a minimum length.
*/ */
static minLength(minLength: number): Function { static minLength(minLength: number): ValidatorFn {
return (control: modelModule.Control): {[key: string]: any} => { return (control: modelModule.AbstractControl): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null; if (isPresent(Validators.required(control))) return null;
var v: string = control.value; var v: string = control.value;
return v.length < minLength ? return v.length < minLength ?
@ -65,8 +66,8 @@ export class Validators {
/** /**
* Validator that requires controls to have a value of a maximum length. * Validator that requires controls to have a value of a maximum length.
*/ */
static maxLength(maxLength: number): Function { static maxLength(maxLength: number): ValidatorFn {
return (control: modelModule.Control): {[key: string]: any} => { return (control: modelModule.AbstractControl): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null; if (isPresent(Validators.required(control))) return null;
var v: string = control.value; var v: string = control.value;
return v.length > maxLength ? return v.length > maxLength ?
@ -78,8 +79,8 @@ export class Validators {
/** /**
* Validator that requires a control to match a regex to its value. * Validator that requires a control to match a regex to its value.
*/ */
static pattern(pattern: string): Function { static pattern(pattern: string): ValidatorFn {
return (control: modelModule.Control): {[key: string]: any} => { return (control: modelModule.AbstractControl): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null; if (isPresent(Validators.required(control))) return null;
let regex = new RegExp(`^${pattern}$`); let regex = new RegExp(`^${pattern}$`);
let v: string = control.value; let v: string = control.value;
@ -91,13 +92,13 @@ export class Validators {
/** /**
* No-op validator. * No-op validator.
*/ */
static nullValidator(c: any): {[key: string]: boolean} { return null; } static nullValidator(c: modelModule.AbstractControl): {[key: string]: boolean} { return null; }
/** /**
* Compose multiple validators into a single function that returns the union * Compose multiple validators into a single function that returns the union
* of the individual error maps. * of the individual error maps.
*/ */
static compose(validators: Function[]): Function { static compose(validators: ValidatorFn[]): ValidatorFn {
if (isBlank(validators)) return null; if (isBlank(validators)) return null;
var presentValidators = validators.filter(isPresent); var presentValidators = validators.filter(isPresent);
if (presentValidators.length == 0) return null; if (presentValidators.length == 0) return null;
@ -107,13 +108,13 @@ export class Validators {
}; };
} }
static composeAsync(validators: Function[]): Function { static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn {
if (isBlank(validators)) return null; if (isBlank(validators)) return null;
var presentValidators = validators.filter(isPresent); var presentValidators = validators.filter(isPresent);
if (presentValidators.length == 0) return null; if (presentValidators.length == 0) return null;
return function(control: modelModule.AbstractControl) { return function(control: modelModule.AbstractControl) {
let promises = _executeValidators(control, presentValidators).map(_convertToPromise); let promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise);
return PromiseWrapper.all(promises).then(_mergeErrors); return PromiseWrapper.all(promises).then(_mergeErrors);
}; };
} }
@ -123,13 +124,20 @@ function _convertToPromise(obj: any): any {
return PromiseWrapper.isPromise(obj) ? obj : ObservableWrapper.toPromise(obj); return PromiseWrapper.isPromise(obj) ? obj : ObservableWrapper.toPromise(obj);
} }
function _executeValidators(control: modelModule.AbstractControl, validators: Function[]): any[] { function _executeValidators(control: modelModule.AbstractControl,
validators: ValidatorFn[]): any[] {
return validators.map(v => v(control));
}
function _executeAsyncValidators(control: modelModule.AbstractControl,
validators: AsyncValidatorFn[]): any[] {
return validators.map(v => v(control)); return validators.map(v => v(control));
} }
function _mergeErrors(arrayOfErrors: any[]): {[key: string]: any} { function _mergeErrors(arrayOfErrors: any[]): {[key: string]: any} {
var res = arrayOfErrors.reduce((res, errors) => { var res: {[key: string]: any} =
return isPresent(errors) ? StringMapWrapper.merge(<any>res, <any>errors) : res; arrayOfErrors.reduce((res: {[key: string]: any}, errors: {[key: string]: any}) => {
return isPresent(errors) ? StringMapWrapper.merge(res, errors) : res;
}, {}); }, {});
return StringMapWrapper.isEmpty(res) ? null : res; return StringMapWrapper.isEmpty(res) ? null : res;
} }

View File

@ -22,7 +22,7 @@ class ObservableStrategy {
} }
class PromiseStrategy { class PromiseStrategy {
createSubscription(async: any, updateLatestValue: any): any { createSubscription(async: Promise<any>, updateLatestValue: (v: any) => any): any {
return async.then(updateLatestValue); return async.then(updateLatestValue);
} }

View File

@ -48,7 +48,7 @@ export class I18nPluralPipe implements PipeTransform {
transform(value: number, args: any[] = null): string { transform(value: number, args: any[] = null): string {
var key: string; var key: string;
var valueStr: string; var valueStr: string;
var pluralMap: {[count: string]: string} = args[0]; var pluralMap: {[count: string]: string} = <{[count: string]: string}>(args[0]);
if (!isStringMap(pluralMap)) { if (!isStringMap(pluralMap)) {
throw new InvalidPipeArgumentException(I18nPluralPipe, pluralMap); throw new InvalidPipeArgumentException(I18nPluralPipe, pluralMap);

View File

@ -37,7 +37,7 @@ import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
@Injectable() @Injectable()
export class I18nSelectPipe implements PipeTransform { export class I18nSelectPipe implements PipeTransform {
transform(value: string, args: any[] = null): string { transform(value: string, args: any[] = null): string {
var mapping: {[key: string]: string} = args[0]; var mapping: {[key: string]: string} = <{[count: string]: string}>(args[0]);
if (!isStringMap(mapping)) { if (!isStringMap(mapping)) {
throw new InvalidPipeArgumentException(I18nSelectPipe, mapping); throw new InvalidPipeArgumentException(I18nSelectPipe, mapping);
} }

View File

@ -146,8 +146,9 @@ class ProtoViewVisitor implements TemplateAstVisitor {
var directiveIndex = new DirectiveIndex(this.boundElementCount - 1, directiveIndexAsNumber); var directiveIndex = new DirectiveIndex(this.boundElementCount - 1, directiveIndexAsNumber);
var directiveMetadata = ast.directive; var directiveMetadata = ast.directive;
var outputsArray = []; var outputsArray = [];
StringMapWrapper.forEach(ast.directive.outputs, (eventName, dirProperty) => outputsArray.push( StringMapWrapper.forEach(
[dirProperty, eventName])); ast.directive.outputs,
(eventName: string, dirProperty: string) => outputsArray.push([dirProperty, eventName]));
var directiveRecord = new DirectiveRecord({ var directiveRecord = new DirectiveRecord({
directiveIndex: directiveIndex, directiveIndex: directiveIndex,
callAfterContentInit: callAfterContentInit:

View File

@ -31,7 +31,7 @@ export abstract class CompileMetadataWithIdentifier {
abstract toJson(): {[key: string]: any}; abstract toJson(): {[key: string]: any};
get identifier(): CompileIdentifierMetadata { return unimplemented(); } get identifier(): CompileIdentifierMetadata { return <CompileIdentifierMetadata>unimplemented(); }
} }
export abstract class CompileMetadataWithType extends CompileMetadataWithIdentifier { export abstract class CompileMetadataWithType extends CompileMetadataWithIdentifier {
@ -41,9 +41,9 @@ export abstract class CompileMetadataWithType extends CompileMetadataWithIdentif
abstract toJson(): {[key: string]: any}; abstract toJson(): {[key: string]: any};
get type(): CompileTypeMetadata { return unimplemented(); } get type(): CompileTypeMetadata { return <CompileTypeMetadata>unimplemented(); }
get identifier(): CompileIdentifierMetadata { return unimplemented(); } get identifier(): CompileIdentifierMetadata { return <CompileIdentifierMetadata>unimplemented(); }
} }
export class CompileIdentifierMetadata implements CompileMetadataWithIdentifier { export class CompileIdentifierMetadata implements CompileMetadataWithIdentifier {

View File

@ -234,7 +234,7 @@ class ProtoViewBuilderVisitor<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> implement
attrAsts: TemplateAst[]): string[][] { attrAsts: TemplateAst[]): string[][] {
var attrs = visitAndReturnContext(this, attrAsts, {}); var attrs = visitAndReturnContext(this, attrAsts, {});
directives.forEach(directiveMeta => { directives.forEach(directiveMeta => {
StringMapWrapper.forEach(directiveMeta.hostAttributes, (value, name) => { StringMapWrapper.forEach(directiveMeta.hostAttributes, (value: string, name: string) => {
var prevValue = attrs[name]; var prevValue = attrs[name];
attrs[name] = isPresent(prevValue) ? mergeAttributeValue(name, prevValue, value) : value; attrs[name] = isPresent(prevValue) ? mergeAttributeValue(name, prevValue, value) : value;
}); });
@ -330,12 +330,14 @@ class ProtoViewBuilderVisitor<APP_PROTO_VIEW, APP_PROTO_EL, STATEMENT> implement
} }
function mapToKeyValueArray(data: {[key: string]: string}): string[][] { function mapToKeyValueArray(data: {[key: string]: string}): string[][] {
var entryArray = []; var entryArray: string[][] = [];
StringMapWrapper.forEach(data, (value, name) => { entryArray.push([name, value]); }); StringMapWrapper.forEach(data,
(value: string, name: string) => { entryArray.push([name, value]); });
// We need to sort to get a defined output order // We need to sort to get a defined output order
// for tests and for caching generated artifacts... // for tests and for caching generated artifacts...
ListWrapper.sort(entryArray, (entry1, entry2) => StringWrapper.compare(entry1[0], entry2[0])); ListWrapper.sort<string[]>(entryArray, (entry1: string[], entry2: string[]) =>
var keyValueArray = []; StringWrapper.compare(entry1[0], entry2[0]));
var keyValueArray: string[][] = [];
entryArray.forEach((entry) => { keyValueArray.push([entry[0], entry[1]]); }); entryArray.forEach((entry) => { keyValueArray.push([entry[0], entry[1]]); });
return keyValueArray; return keyValueArray;
} }

View File

@ -53,9 +53,9 @@ export class StyleCompiler {
private _loadStyles(plainStyles: string[], absUrls: string[], private _loadStyles(plainStyles: string[], absUrls: string[],
encapsulate: boolean): Promise<Array<string | any[]>> { encapsulate: boolean): Promise<Array<string | any[]>> {
var promises = absUrls.map((absUrl) => { var promises: Promise<string[]>[] = absUrls.map((absUrl: string): Promise<string[]> => {
var cacheKey = `${absUrl}${encapsulate ? '.shim' : ''}`; var cacheKey = `${absUrl}${encapsulate ? '.shim' : ''}`;
var result = this._styleCache.get(cacheKey); var result: Promise<string[]> = this._styleCache.get(cacheKey);
if (isBlank(result)) { if (isBlank(result)) {
result = this._xhr.get(absUrl).then((style) => { result = this._xhr.get(absUrl).then((style) => {
var styleWithImports = extractStyleUrls(this._urlResolver, absUrl, style); var styleWithImports = extractStyleUrls(this._urlResolver, absUrl, style);
@ -66,7 +66,7 @@ export class StyleCompiler {
} }
return result; return result;
}); });
return PromiseWrapper.all(promises).then((nestedStyles: string[][]) => { return PromiseWrapper.all<string[]>(promises).then((nestedStyles: string[][]) => {
var result: Array<string | any[]> = var result: Array<string | any[]> =
plainStyles.map(plainStyle => this._shimIfNeeded(plainStyle, encapsulate)); plainStyles.map(plainStyle => this._shimIfNeeded(plainStyle, encapsulate));
nestedStyles.forEach(styles => result.push(styles)); nestedStyles.forEach(styles => result.push(styles));

View File

@ -505,7 +505,7 @@ class TemplateParseVisitor implements HtmlAstVisitor {
sourceSpan: ParseSourceSpan, sourceSpan: ParseSourceSpan,
targetPropertyAsts: BoundElementPropertyAst[]) { targetPropertyAsts: BoundElementPropertyAst[]) {
if (isPresent(hostProps)) { if (isPresent(hostProps)) {
StringMapWrapper.forEach(hostProps, (expression, propName) => { StringMapWrapper.forEach(hostProps, (expression: string, propName: string) => {
var exprAst = this._parseBinding(expression, sourceSpan); var exprAst = this._parseBinding(expression, sourceSpan);
targetPropertyAsts.push( targetPropertyAsts.push(
this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan)); this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan));
@ -517,7 +517,7 @@ class TemplateParseVisitor implements HtmlAstVisitor {
sourceSpan: ParseSourceSpan, sourceSpan: ParseSourceSpan,
targetEventAsts: BoundEventAst[]) { targetEventAsts: BoundEventAst[]) {
if (isPresent(hostListeners)) { if (isPresent(hostListeners)) {
StringMapWrapper.forEach(hostListeners, (expression, propName) => { StringMapWrapper.forEach(hostListeners, (expression: string, propName: string) => {
this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts); this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts);
}); });
} }
@ -645,7 +645,7 @@ class TemplateParseVisitor implements HtmlAstVisitor {
var allDirectiveEvents = new Set<string>(); var allDirectiveEvents = new Set<string>();
directives.forEach(directive => { directives.forEach(directive => {
StringMapWrapper.forEach(directive.directive.outputs, StringMapWrapper.forEach(directive.directive.outputs,
(eventName, _) => { allDirectiveEvents.add(eventName); }); (eventName: string, _) => { allDirectiveEvents.add(eventName); });
}); });
events.forEach(event => { events.forEach(event => {
if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) { if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) {

View File

@ -128,7 +128,7 @@ function _createPlatform(providers?: Array<Type | Provider | any[]>): PlatformRe
} }
function _runPlatformInitializers(injector: Injector): void { function _runPlatformInitializers(injector: Injector): void {
let inits: Function[] = injector.getOptional(PLATFORM_INITIALIZER); let inits: Function[] = <Function[]>injector.getOptional(PLATFORM_INITIALIZER);
if (isPresent(inits)) inits.forEach(init => init()); if (isPresent(inits)) inits.forEach(init => init());
} }
@ -150,7 +150,7 @@ export abstract class PlatformRef {
* Retrieve the platform {@link Injector}, which is the parent injector for * Retrieve the platform {@link Injector}, which is the parent injector for
* every Angular application on the page and provides singleton providers. * every Angular application on the page and provides singleton providers.
*/ */
get injector(): Injector { return unimplemented(); }; get injector(): Injector { throw unimplemented(); };
/** /**
* Instantiate a new Angular application on the page. * Instantiate a new Angular application on the page.
@ -222,7 +222,7 @@ export class PlatformRef_ extends PlatformRef {
asyncApplication(bindingFn: (zone: NgZone) => Promise<Array<Type | Provider | any[]>>, asyncApplication(bindingFn: (zone: NgZone) => Promise<Array<Type | Provider | any[]>>,
additionalProviders?: Array<Type | Provider | any[]>): Promise<ApplicationRef> { additionalProviders?: Array<Type | Provider | any[]>): Promise<ApplicationRef> {
var zone = createNgZone(); var zone = createNgZone();
var completer = PromiseWrapper.completer(); var completer = PromiseWrapper.completer<ApplicationRef>();
if (bindingFn === null) { if (bindingFn === null) {
completer.resolve(this._initApp(zone, additionalProviders)); completer.resolve(this._initApp(zone, additionalProviders));
} else { } else {
@ -342,12 +342,12 @@ export abstract class ApplicationRef {
/** /**
* Retrieve the application {@link Injector}. * Retrieve the application {@link Injector}.
*/ */
get injector(): Injector { return unimplemented(); }; get injector(): Injector { return <Injector>unimplemented(); };
/** /**
* Retrieve the application {@link NgZone}. * Retrieve the application {@link NgZone}.
*/ */
get zone(): NgZone { return unimplemented(); }; get zone(): NgZone { return <NgZone>unimplemented(); };
/** /**
* Dispose of this application and all of its components. * Dispose of this application and all of its components.
@ -369,7 +369,7 @@ export abstract class ApplicationRef {
/** /**
* Get a list of component types registered to this application. * Get a list of component types registered to this application.
*/ */
get componentTypes(): Type[] { return unimplemented(); }; get componentTypes(): Type[] { return <Type[]>unimplemented(); };
} }
export class ApplicationRef_ extends ApplicationRef { export class ApplicationRef_ extends ApplicationRef {
@ -449,13 +449,13 @@ export class ApplicationRef_ extends ApplicationRef {
completer.reject(e, e.stack); completer.reject(e, e.stack);
} }
}); });
return completer.promise.then(_ => { return completer.promise.then<ComponentRef>((ref: ComponentRef) => {
let c = this._injector.get(Console); let c = this._injector.get(Console);
if (assertionsEnabled()) { if (assertionsEnabled()) {
c.log( c.log(
"Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode."); "Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.");
} }
return _; return ref;
}); });
} }

View File

@ -64,8 +64,9 @@ export class DynamicProtoChangeDetector implements ProtoChangeDetector {
export function createPropertyRecords(definition: ChangeDetectorDefinition): ProtoRecord[] { export function createPropertyRecords(definition: ChangeDetectorDefinition): ProtoRecord[] {
var recordBuilder = new ProtoRecordBuilder(); var recordBuilder = new ProtoRecordBuilder();
ListWrapper.forEachWithIndex(definition.bindingRecords, ListWrapper.forEachWithIndex(
(b, index) => recordBuilder.add(b, definition.variableNames, index)); definition.bindingRecords,
(b: BindingRecord, index: number) => recordBuilder.add(b, definition.variableNames, index));
return coalesce(recordBuilder.records); return coalesce(recordBuilder.records);
} }

View File

@ -91,19 +91,19 @@ export class DebugElement extends DebugNode {
} }
queryAll(predicate: Predicate<DebugElement>): DebugElement[] { queryAll(predicate: Predicate<DebugElement>): DebugElement[] {
var matches = []; var matches: DebugElement[] = [];
_queryElementChildren(this, predicate, matches); _queryElementChildren(this, predicate, matches);
return matches; return matches;
} }
queryAllNodes(predicate: Predicate<DebugNode>): DebugNode[] { queryAllNodes(predicate: Predicate<DebugNode>): DebugNode[] {
var matches = []; var matches: DebugNode[] = [];
_queryNodeChildren(this, predicate, matches); _queryNodeChildren(this, predicate, matches);
return matches; return matches;
} }
get children(): DebugElement[] { get children(): DebugElement[] {
var children = []; var children: DebugElement[] = [];
this.childNodes.forEach((node) => { this.childNodes.forEach((node) => {
if (node instanceof DebugElement) { if (node instanceof DebugElement) {
children.push(node); children.push(node);

View File

@ -73,7 +73,7 @@ export class DebugDomRenderer implements Renderer {
if (isPresent(debugNode)) { if (isPresent(debugNode)) {
var debugParent = debugNode.parent; var debugParent = debugNode.parent;
if (viewRootNodes.length > 0 && isPresent(debugParent)) { if (viewRootNodes.length > 0 && isPresent(debugParent)) {
var debugViewRootNodes = []; var debugViewRootNodes: DebugNode[] = [];
viewRootNodes.forEach((rootNode) => debugViewRootNodes.push(getDebugNode(rootNode))); viewRootNodes.forEach((rootNode) => debugViewRootNodes.push(getDebugNode(rootNode)));
debugParent.insertChildrenAfter(debugNode, debugViewRootNodes); debugParent.insertChildrenAfter(debugNode, debugViewRootNodes);
} }

View File

@ -513,7 +513,7 @@ export class ProviderBuilder {
*/ */
export function resolveFactory(provider: Provider): ResolvedFactory { export function resolveFactory(provider: Provider): ResolvedFactory {
var factoryFn: Function; var factoryFn: Function;
var resolvedDeps; var resolvedDeps: Dependency[];
if (isPresent(provider.useClass)) { if (isPresent(provider.useClass)) {
var useClass = resolveForwardRef(provider.useClass); var useClass = resolveForwardRef(provider.useClass);
factoryFn = reflector.factory(useClass); factoryFn = reflector.factory(useClass);
@ -619,7 +619,7 @@ function _constructDependencies(factoryFunction: Function, dependencies: any[]):
} }
function _dependenciesFor(typeOrFunc): Dependency[] { function _dependenciesFor(typeOrFunc): Dependency[] {
var params = reflector.parameters(typeOrFunc); var params: any[][] = reflector.parameters(typeOrFunc);
if (isBlank(params)) return []; if (isBlank(params)) return [];
if (params.some(isBlank)) { if (params.some(isBlank)) {
throw new NoAnnotationError(typeOrFunc, params); throw new NoAnnotationError(typeOrFunc, params);

View File

@ -115,8 +115,9 @@ export class AppView implements ChangeDispatcher {
this.disposables = disposables; this.disposables = disposables;
this.appElements = appElements; this.appElements = appElements;
var localsMap = new Map<string, any>(); var localsMap = new Map<string, any>();
StringMapWrapper.forEach(this.proto.templateVariableBindings, StringMapWrapper.forEach(
(templateName, _) => { localsMap.set(templateName, null); }); this.proto.templateVariableBindings,
(templateName: string, _: string) => { localsMap.set(templateName, null); });
for (var i = 0; i < appElements.length; i++) { for (var i = 0; i < appElements.length; i++) {
var appEl = appElements[i]; var appEl = appElements[i];
var providerTokens = []; var providerTokens = [];
@ -125,7 +126,8 @@ export class AppView implements ChangeDispatcher {
providerTokens.push(appEl.proto.protoInjector.getProviderAtIndex(j).key.token); providerTokens.push(appEl.proto.protoInjector.getProviderAtIndex(j).key.token);
} }
} }
StringMapWrapper.forEach(appEl.proto.directiveVariableBindings, (directiveIndex, name) => { StringMapWrapper.forEach(appEl.proto.directiveVariableBindings,
(directiveIndex: number, name: string) => {
if (isBlank(directiveIndex)) { if (isBlank(directiveIndex)) {
localsMap.set(name, appEl.nativeElement); localsMap.set(name, appEl.nativeElement);
} else { } else {

View File

@ -41,7 +41,7 @@ export abstract class ViewContainerRef {
* Anchor element that specifies the location of this container in the containing View. * Anchor element that specifies the location of this container in the containing View.
* <!-- TODO: rename to anchorElement --> * <!-- TODO: rename to anchorElement -->
*/ */
get element(): ElementRef { return unimplemented(); } get element(): ElementRef { return <ElementRef>unimplemented(); }
/** /**
* Destroys all Views in this container. * Destroys all Views in this container.
@ -60,7 +60,7 @@ export abstract class ViewContainerRef {
/** /**
* Returns the number of Views currently attached to this container. * Returns the number of Views currently attached to this container.
*/ */
get length(): number { return unimplemented(); }; get length(): number { return <number>unimplemented(); };
/** /**
* Instantiates an Embedded View based on the {@link TemplateRef `templateRef`} and inserts it * Instantiates an Embedded View based on the {@link TemplateRef `templateRef`} and inserts it

View File

@ -6,9 +6,9 @@ export abstract class ViewRef {
/** /**
* @internal * @internal
*/ */
get changeDetectorRef(): ChangeDetectorRef { return unimplemented(); }; get changeDetectorRef(): ChangeDetectorRef { return <ChangeDetectorRef>unimplemented(); };
get destroyed(): boolean { return unimplemented(); } get destroyed(): boolean { return <boolean>unimplemented(); }
} }
/** /**
@ -21,7 +21,7 @@ export abstract class ViewRef {
* {@link AppViewManager#createHostViewInContainer}, {@link ViewContainerRef#createHostView}. * {@link AppViewManager#createHostViewInContainer}, {@link ViewContainerRef#createHostView}.
*/ */
export abstract class HostViewRef extends ViewRef { export abstract class HostViewRef extends ViewRef {
get rootNodes(): any[] { return unimplemented(); }; get rootNodes(): any[] { return <any[]>unimplemented(); };
} }
/** /**
@ -88,7 +88,7 @@ export abstract class EmbeddedViewRef extends ViewRef {
*/ */
abstract hasLocal(variableName: string): boolean; abstract hasLocal(variableName: string): boolean;
get rootNodes(): any[] { return unimplemented(); }; get rootNodes(): any[] { return <any[]>unimplemented(); };
} }
export class ViewRef_ implements EmbeddedViewRef, HostViewRef { export class ViewRef_ implements EmbeddedViewRef, HostViewRef {

View File

@ -87,7 +87,7 @@ export class Reflector {
} }
} }
parameters(typeOrFunc: /*Type*/ any): any[] { parameters(typeOrFunc: /*Type*/ any): any[][] {
if (this._injectableInfo.has(typeOrFunc)) { if (this._injectableInfo.has(typeOrFunc)) {
var res = this._getReflectionInfo(typeOrFunc).parameters; var res = this._getReflectionInfo(typeOrFunc).parameters;
return isPresent(res) ? res : []; return isPresent(res) ? res : [];
@ -148,7 +148,7 @@ export class Reflector {
} }
/** @internal */ /** @internal */
_getReflectionInfo(typeOrFunc: any) { _getReflectionInfo(typeOrFunc: any): ReflectionInfo {
if (isPresent(this._usedKeys)) { if (isPresent(this._usedKeys)) {
this._usedKeys.add(typeOrFunc); this._usedKeys.add(typeOrFunc);
} }

View File

@ -25,7 +25,7 @@ class TimerWrapper {
} }
class ObservableWrapper { class ObservableWrapper {
static StreamSubscription subscribe(Stream s, Function onNext, static StreamSubscription subscribe/*<T>*/(Stream s, onNext(/*=T*/ value),
[onError, onComplete]) { [onError, onComplete]) {
return s.listen(onNext, return s.listen(onNext,
onError: onError, onDone: onComplete, cancelOnError: true); onError: onError, onDone: onComplete, cancelOnError: true);

View File

@ -1,10 +1,8 @@
import {global, isPresent, noop} from 'angular2/src/facade/lang'; import {global, noop} from 'angular2/src/facade/lang';
export {PromiseWrapper, PromiseCompleter} from 'angular2/src/facade/promise'; export {PromiseWrapper, PromiseCompleter} from 'angular2/src/facade/promise';
import {Observable} from 'rxjs/Observable'; import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject'; import {Subject} from 'rxjs/Subject';
import {Subscription} from 'rxjs/Subscription';
import {Operator} from 'rxjs/Operator';
import {PromiseObservable} from 'rxjs/observable/PromiseObservable'; import {PromiseObservable} from 'rxjs/observable/PromiseObservable';
import {toPromise} from 'rxjs/operator/toPromise'; import {toPromise} from 'rxjs/operator/toPromise';

View File

@ -33,15 +33,15 @@ class IterableMap extends IterableBase<List> {
} }
class MapWrapper { class MapWrapper {
static Map clone(Map m) => new Map.from(m); static Map/*<K,V>*/ clone/*<K,V>*/(Map/*<K,V>*/ m) => new Map.from(m);
// in opposite to JS, Dart does not create a new map // in opposite to JS, Dart does not create a new map
static Map createFromStringMap(Map m) => m; static Map/*<K,V>*/ createFromStringMap/*<K,V>*/(Map/*<K,V>*/ m) => m;
// in opposite to JS, Dart does not create a new map // in opposite to JS, Dart does not create a new map
static Map toStringMap(Map m) => m; static Map/*<K,V>*/ toStringMap/*<K,V>*/(Map/*<K,V>*/ m) => m;
static Map createFromPairs(List pairs) => pairs.fold({}, (m, p) { static Map/*<K,V>*/ createFromPairs/*<K,V>*/(List pairs) => pairs.fold(/*<K,V>*/{}, (m, p) {
m[p[0]] = p[1]; m[p[0]] = p[1];
return m; return m;
}); });
@ -52,29 +52,29 @@ class MapWrapper {
} }
} }
static Iterable iterable(Map m) => new IterableMap(m); static Iterable/*<List<dynamic>>*/ iterable/*<K,V>*/(Map/*<K,V>*/ m) => new IterableMap(m);
static List keys(Map m) => m.keys.toList(); static List/*<K>*/ keys/*<K,V>*/(Map/*<K,V>*/ m) => m.keys.toList();
static List values(Map m) => m.values.toList(); static List/*<V>*/ values/*<K,V>*/(Map/*<K,V>*/ m) => m.values.toList();
} }
class StringMapWrapper { class StringMapWrapper {
static Map create() => {}; static Map/*<String,V>*/ create/*<V>*/() => {};
static bool contains(Map map, key) => map.containsKey(key); static bool contains/*<V>*/(Map/*<String,V>*/ map, String key) => map.containsKey(key);
static get(Map map, key) => map[key]; static get/*<V>*/(Map/*<String,V>*/ map, String key) => map[key];
static void set(Map map, key, value) { static void set/*<V>*/(Map/*<String,V>*/ map, String key, /*=V*/value) {
map[key] = value; map[key] = value;
} }
static void delete(Map m, k) { static void delete/*<V>*/(Map/*<String,V>*/ m, String k) {
m.remove(k); m.remove(k);
} }
static void forEach(Map m, fn(v, k)) { static void forEach/*<V>*/(Map/*<String,V>*/ m, fn(/*=V*/ v, String k)) {
m.forEach((k, v) => fn(v, k)); m.forEach((k, v) => fn(v, k));
} }
static Map merge(Map a, Map b) { static Map/*<String,V>*/ merge/*<V>*/(Map/*<String,V>*/ a, Map/*<String,V>*/ b) {
var m = new Map.from(a); var m = new Map/*<String,V>*/.from(a);
if (b != null) { if (b != null) {
b.forEach((k, v) => m[k] = v); b.forEach((k, v) => m[k] = v);
} }
@ -86,7 +86,7 @@ class StringMapWrapper {
} }
static bool isEmpty(Map m) => m.isEmpty; static bool isEmpty(Map m) => m.isEmpty;
static bool equals(Map m1, Map m2) { static bool equals/*<V>*/(Map/*<String,V>*/ m1, Map/*<String,V>*/ m2) {
if (m1.length != m2.length) { if (m1.length != m2.length) {
return false; return false;
} }
@ -102,9 +102,9 @@ class StringMapWrapper {
typedef bool Predicate<T>(T item); typedef bool Predicate<T>(T item);
class ListWrapper { class ListWrapper {
static List clone(Iterable l) => new List.from(l); static List/*<T>*/ clone/*<T>*/(Iterable/*<T>*/ l) => new List.from(l);
static List createFixedSize(int size) => new List(size); static List/*<T>*/ createFixedSize/*<T>*/(int size) => new List(size);
static List createGrowableSize(int size) => static List/*<T>*/ createGrowableSize/*<T>*/(int size) =>
new List.generate(size, (_) => null, growable: true); new List.generate(size, (_) => null, growable: true);
static UnmodifiableListView createImmutable(List input) { static UnmodifiableListView createImmutable(List input) {
return new UnmodifiableListView(input); return new UnmodifiableListView(input);
@ -116,43 +116,43 @@ class ListWrapper {
static int lastIndexOf(List list, value, [int startIndex = null]) => static int lastIndexOf(List list, value, [int startIndex = null]) =>
list.lastIndexOf(value, startIndex == null ? list.length : startIndex); list.lastIndexOf(value, startIndex == null ? list.length : startIndex);
static void forEachWithIndex(List list, fn(item, index)) { static void forEachWithIndex/*<T>*/(List/*<T>*/ list, fn(/*=T*/ item, int index)) {
for (var i = 0; i < list.length; ++i) { for (var i = 0; i < list.length; ++i) {
fn(list[i], i); fn(list[i], i);
} }
} }
static first(List list) => list.isEmpty ? null : list.first; static /*=T*/ first/*<T>*/(List/*<T>*/ list) => list.isEmpty ? null : list.first;
static last(List list) => list.isEmpty ? null : list.last; static /*=T*/ last/*<T>*/(List/*<T>*/ list) => list.isEmpty ? null : list.last;
static List reversed(List list) => list.reversed.toList(); static List/*<T>*/ reversed/*<T>*/(List/*<T>*/ list) => list.reversed.toList();
static List concat(List a, List b) { static List/*<T>*/ concat/*<T>*/(List/*<T>*/ a, List/*<T>*/ b) {
return new List() return new List()
..length = a.length + b.length ..length = a.length + b.length
..setRange(0, a.length, a) ..setRange(0, a.length, a)
..setRange(a.length, a.length + b.length, b); ..setRange(a.length, a.length + b.length, b);
} }
static void insert(List l, int index, value) { static void insert/*<T>*/(List/*<T>*/ l, int index, /*=T*/ value) {
l.insert(index, value); l.insert(index, value);
} }
static removeAt(List l, int index) => l.removeAt(index); static removeAt(List l, int index) => l.removeAt(index);
static void removeAll(List list, List items) { static void removeAll/*<T>*/(List/*<T>*/ list, List/*<T>*/ items) {
for (var i = 0; i < items.length; ++i) { for (var i = 0; i < items.length; ++i) {
list.remove(items[i]); list.remove(items[i]);
} }
} }
static bool remove(List list, item) => list.remove(item); static bool remove/*<T>*/(List/*<T>*/ list, /*=T*/ item) => list.remove(item);
static void clear(List l) { static void clear(List l) {
l.clear(); l.clear();
} }
static bool isEmpty(Iterable list) => list.isEmpty; static bool isEmpty(Iterable list) => list.isEmpty;
static void fill(List l, value, [int start = 0, int end]) { static void fill/*<T>*/(List/*<T>*/ l, /*=T*/ value, [int start = 0, int end]) {
l.fillRange(_startOffset(l, start), _endOffset(l, end), value); l.fillRange(_startOffset(l, start), _endOffset(l, end), value);
} }
static bool equals(List a, List b) { static bool equals/*<T>*/(List/*<T>*/ a, List/*<T>*/ b) {
if (a.length != b.length) return false; if (a.length != b.length) return false;
for (var i = 0; i < a.length; ++i) { for (var i = 0; i < a.length; ++i) {
if (a[i] != b[i]) return false; if (a[i] != b[i]) return false;
@ -160,7 +160,7 @@ class ListWrapper {
return true; return true;
} }
static List slice(List l, [int from = 0, int to]) { static List/*<T>*/ slice/*<T>*/(List/*<T>*/ l, [int from = 0, int to]) {
from = _startOffset(l, from); from = _startOffset(l, from);
to = _endOffset(l, to); to = _endOffset(l, to);
//in JS if from > to an empty array is returned //in JS if from > to an empty array is returned
@ -170,7 +170,7 @@ class ListWrapper {
return l.sublist(from, to); return l.sublist(from, to);
} }
static List splice(List l, int from, int length) { static List/*<T>*/ splice/*<T>*/(List/*<T>*/ l, int from, int length) {
from = _startOffset(l, from); from = _startOffset(l, from);
var to = from + length; var to = from + length;
var sub = l.sublist(from, to); var sub = l.sublist(from, to);
@ -178,7 +178,7 @@ class ListWrapper {
return sub; return sub;
} }
static void sort(List l, [compareFn(a, b) = null]) { static void sort/*<T>*/(List/*<T>*/ l, [int compareFn(/*=T*/a, /*=T*/b) = null]) {
if (compareFn == null) { if (compareFn == null) {
l.sort(); l.sort();
} else { } else {
@ -232,7 +232,11 @@ class ListWrapper {
bool isListLikeIterable(obj) => obj is Iterable; bool isListLikeIterable(obj) => obj is Iterable;
bool areIterablesEqual(Iterable a, Iterable b, Function comparator) { bool areIterablesEqual/*<T>*/(
Iterable/*<T>*/ a,
Iterable/*<T>*/ b,
bool comparator(/*=T*/a, /*=T*/b))
{
var iterator1 = a.iterator; var iterator1 = a.iterator;
var iterator2 = b.iterator; var iterator2 = b.iterator;
@ -241,11 +245,11 @@ bool areIterablesEqual(Iterable a, Iterable b, Function comparator) {
var done2 = !iterator2.moveNext(); var done2 = !iterator2.moveNext();
if (done1 && done2) return true; if (done1 && done2) return true;
if (done1 || done2) return false; if (done1 || done2) return false;
if (!comparator(iterator2.current, iterator2.current)) return false; if (!comparator(iterator1.current, iterator2.current)) return false;
} }
} }
void iterateListLike(iter, fn(item)) { void iterateListLike/*<T>*/(Iterable/*<T>*/ iter, fn(/*=T*/item)) {
assert(iter is Iterable); assert(iter is Iterable);
for (var item in iter) { for (var item in iter) {
fn(item); fn(item);
@ -253,9 +257,9 @@ void iterateListLike(iter, fn(item)) {
} }
class SetWrapper { class SetWrapper {
static Set createFromList(List l) => new Set.from(l); static Set/*<T>*/ createFromList/*<T>*/(List/*<T>*/ l) => new Set.from(l);
static bool has(Set s, key) => s.contains(key); static bool has/*<T>*/(Set/*<T>*/ s, /*=T*/key) => s.contains(key);
static void delete(Set m, k) { static void delete/*<T>*/(Set/*<T>*/ m, /*=T*/k) {
m.remove(k); m.remove(k);
} }
} }

View File

@ -20,16 +20,16 @@ class CONST {
const IS_DART = true; const IS_DART = true;
bool isPresent(obj) => obj != null; bool isPresent(Object obj) => obj != null;
bool isBlank(obj) => obj == null; bool isBlank(Object obj) => obj == null;
bool isString(obj) => obj is String; bool isString(Object obj) => obj is String;
bool isFunction(obj) => obj is Function; bool isFunction(Object obj) => obj is Function;
bool isType(obj) => obj is Type; bool isType(Object obj) => obj is Type;
bool isStringMap(obj) => obj is Map; bool isStringMap(Object obj) => obj is Map;
bool isArray(obj) => obj is List; bool isArray(Object obj) => obj is List;
bool isPromise(obj) => obj is Future; bool isPromise(Object obj) => obj is Future;
bool isNumber(obj) => obj is num; bool isNumber(Object obj) => obj is num;
bool isDate(obj) => obj is DateTime; bool isDate(Object obj) => obj is DateTime;
String stringify(obj) { String stringify(obj) {
final exp = new RegExp(r"from Function '(\w+)'"); final exp = new RegExp(r"from Function '(\w+)'");

View File

@ -4,22 +4,21 @@ import 'dart:async';
import 'dart:async' as async; import 'dart:async' as async;
class PromiseWrapper { class PromiseWrapper {
static Future resolve(obj) => new Future.value(obj); static Future/*<T>*/ resolve/*<T>*/(dynamic /*=T*/ obj) => new Future.value(obj);
static Future reject(obj, stackTrace) => new Future.error(obj, static Future/*<T>*/ reject/*<T>*/(dynamic /*=T*/ obj, Object stackTrace) => new Future.error(obj,
stackTrace != null ? stackTrace : obj is Error ? obj.stackTrace : null); stackTrace != null ? stackTrace : obj is Error ? (obj as Error).stackTrace : null);
static Future<List> all(List<dynamic> promises) { static Future<List/*<T>*/> all/*<T>*/(List<dynamic> promises) {
return Future return Future
.wait(promises.map((p) => p is Future ? p : new Future.value(p))); .wait(promises.map((p) => p is Future ? p as Future/*<T>*/ : new Future/*<T>*/.value(p)));
} }
static Future/*<R>*/ then/*<T, R>*/(Future/*<T>*/ promise, dynamic /*=R*/ success(dynamic /*=T*/ value), [Function onError]) {
static Future then(Future promise, success(value), [Function onError]) {
if (success == null) return promise.catchError(onError); if (success == null) return promise.catchError(onError);
return promise.then(success, onError: onError); return promise.then(success, onError: onError);
} }
static Future wrap(Function fn) { static Future/*<T>*/ wrap/*<T>*/(dynamic /*=T*/ fn()) {
return new Future(fn); return new Future(fn);
} }
@ -37,16 +36,14 @@ class PromiseWrapper {
return obj is Future; return obj is Future;
} }
static PromiseCompleter<dynamic> completer() => static PromiseCompleter/*<T>*/ completer/*<T>*/() =>
new PromiseCompleter(new Completer()); new PromiseCompleter();
} }
class PromiseCompleter<T> { class PromiseCompleter<T> {
final Completer<T> c; final Completer<T> c = new Completer();
PromiseCompleter(this.c); Future<T> get promise => c.future;
Future get promise => c.future;
void resolve(v) { void resolve(v) {
c.complete(v); c.complete(v);

View File

@ -1,8 +1,15 @@
export interface PromiseCompleter<R> { export class PromiseCompleter<R> {
promise: Promise<R>; promise: Promise<R>;
resolve: (value?: R | PromiseLike<R>) => void; resolve: (value?: R | PromiseLike<R>) => void;
reject: (error?: any, stackTrace?: string) => void; reject: (error?: any, stackTrace?: string) => void;
constructor() {
this.promise = new Promise((res, rej) => {
this.resolve = res;
this.reject = rej;
});
}
} }
export class PromiseWrapper { export class PromiseWrapper {
@ -17,7 +24,7 @@ export class PromiseWrapper {
return promise.catch(onError); return promise.catch(onError);
} }
static all(promises: any[]): Promise<any> { static all<T>(promises: (T | Promise<T>)[]): Promise<T[]> {
if (promises.length == 0) return Promise.resolve([]); if (promises.length == 0) return Promise.resolve([]);
return Promise.all(promises); return Promise.all(promises);
} }
@ -43,15 +50,5 @@ export class PromiseWrapper {
static isPromise(obj: any): boolean { return obj instanceof Promise; } static isPromise(obj: any): boolean { return obj instanceof Promise; }
static completer(): PromiseCompleter<any> { static completer<T>(): PromiseCompleter<T> { return new PromiseCompleter<T>(); }
var resolve;
var reject;
var p = new Promise(function(res, rej) {
resolve = res;
reject = rej;
});
return {promise: p, resolve: resolve, reject: reject};
}
} }

View File

@ -31,7 +31,7 @@ export abstract class GenericBrowserDomAdapter extends DomAdapter {
OTransition: 'oTransitionEnd otransitionend', OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend' transition: 'transitionend'
}; };
StringMapWrapper.forEach(transEndEventNames, (value, key) => { StringMapWrapper.forEach(transEndEventNames, (value: string, key: string) => {
if (isPresent(this.getStyle(element, key))) { if (isPresent(this.getStyle(element, key))) {
this._transitionEnd = value; this._transitionEnd = value;
} }

View File

@ -102,7 +102,7 @@ export class RouterOutlet implements OnDestroy {
var next = _resolveToTrue; var next = _resolveToTrue;
if (isPresent(this._componentRef) && isPresent(this._currentInstruction) && if (isPresent(this._componentRef) && isPresent(this._currentInstruction) &&
hasLifecycleHook(hookMod.routerOnDeactivate, this._currentInstruction.componentType)) { hasLifecycleHook(hookMod.routerOnDeactivate, this._currentInstruction.componentType)) {
next = PromiseWrapper.resolve( next = <Promise<boolean>>PromiseWrapper.resolve(
(<OnDeactivate>this._componentRef.instance) (<OnDeactivate>this._componentRef.instance)
.routerOnDeactivate(nextInstruction, this._currentInstruction)); .routerOnDeactivate(nextInstruction, this._currentInstruction));
} }
@ -127,7 +127,7 @@ export class RouterOutlet implements OnDestroy {
return _resolveToTrue; return _resolveToTrue;
} }
if (hasLifecycleHook(hookMod.routerCanDeactivate, this._currentInstruction.componentType)) { if (hasLifecycleHook(hookMod.routerCanDeactivate, this._currentInstruction.componentType)) {
return PromiseWrapper.resolve( return <Promise<boolean>>PromiseWrapper.resolve(
(<CanDeactivate>this._componentRef.instance) (<CanDeactivate>this._componentRef.instance)
.routerCanDeactivate(nextInstruction, this._currentInstruction)); .routerCanDeactivate(nextInstruction, this._currentInstruction));
} }
@ -158,7 +158,7 @@ export class RouterOutlet implements OnDestroy {
(isPresent(nextInstruction.params) && isPresent(this._currentInstruction.params) && (isPresent(nextInstruction.params) && isPresent(this._currentInstruction.params) &&
StringMapWrapper.equals(nextInstruction.params, this._currentInstruction.params)); StringMapWrapper.equals(nextInstruction.params, this._currentInstruction.params));
} }
return PromiseWrapper.resolve(result); return <Promise<boolean>>PromiseWrapper.resolve(result);
} }
ngOnDestroy(): void { this._parentRouter.unregisterPrimaryOutlet(this); } ngOnDestroy(): void { this._parentRouter.unregisterPrimaryOutlet(this); }

View File

@ -195,7 +195,7 @@ export abstract class Instruction {
/** @internal */ /** @internal */
_stringifyAux(): string { _stringifyAux(): string {
var routes = []; var routes = [];
StringMapWrapper.forEach(this.auxInstruction, (auxInstruction, _) => { StringMapWrapper.forEach(this.auxInstruction, (auxInstruction: Instruction, _: string) => {
routes.push(auxInstruction._stringifyPathMatrixAux()); routes.push(auxInstruction._stringifyPathMatrixAux());
}); });
if (routes.length > 0) { if (routes.length > 0) {
@ -308,7 +308,7 @@ export class ComponentInstruction {
*/ */
constructor(public urlPath: string, public urlParams: string[], data: RouteData, constructor(public urlPath: string, public urlParams: string[], data: RouteData,
public componentType, public terminal: boolean, public specificity: string, public componentType, public terminal: boolean, public specificity: string,
public params: {[key: string]: any} = null) { public params: {[key: string]: string} = null) {
this.routeData = isPresent(data) ? data : BLANK_ROUTE_DATA; this.routeData = isPresent(data) ? data : BLANK_ROUTE_DATA;
} }
} }

View File

@ -5,7 +5,7 @@ import {global} from 'angular2/src/facade/lang';
// TODO(rado): find a better way to fix this, or remove if likely culprit // TODO(rado): find a better way to fix this, or remove if likely culprit
// https://github.com/systemjs/systemjs/issues/487 gets closed. // https://github.com/systemjs/systemjs/issues/487 gets closed.
var __ignore_me = global; var __ignore_me = global;
var __make_dart_analyzer_happy: Promise<any> = null;
/** /**
* Defines route lifecycle method `routerOnActivate`, which is called by the router at the end of a * Defines route lifecycle method `routerOnActivate`, which is called by the router at the end of a
@ -27,7 +27,8 @@ var __ignore_me = global;
*/ */
export interface OnActivate { export interface OnActivate {
routerOnActivate(nextInstruction: ComponentInstruction, routerOnActivate(nextInstruction: ComponentInstruction,
prevInstruction: ComponentInstruction): any; prevInstruction: ComponentInstruction): any |
Promise<any>;
} }
/** /**
@ -46,7 +47,8 @@ export interface OnActivate {
* {@example router/ts/reuse/reuse_example.ts region='reuseCmp'} * {@example router/ts/reuse/reuse_example.ts region='reuseCmp'}
*/ */
export interface OnReuse { export interface OnReuse {
routerOnReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any; routerOnReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any |
Promise<any>;
} }
/** /**
@ -66,7 +68,8 @@ export interface OnReuse {
*/ */
export interface OnDeactivate { export interface OnDeactivate {
routerOnDeactivate(nextInstruction: ComponentInstruction, routerOnDeactivate(nextInstruction: ComponentInstruction,
prevInstruction: ComponentInstruction): any; prevInstruction: ComponentInstruction): any |
Promise<any>;
} }
/** /**
@ -90,7 +93,9 @@ export interface OnDeactivate {
* {@example router/ts/reuse/reuse_example.ts region='reuseCmp'} * {@example router/ts/reuse/reuse_example.ts region='reuseCmp'}
*/ */
export interface CanReuse { export interface CanReuse {
routerCanReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any; routerCanReuse(nextInstruction: ComponentInstruction,
prevInstruction: ComponentInstruction): boolean |
Promise<boolean>;
} }
/** /**
@ -114,5 +119,6 @@ export interface CanReuse {
*/ */
export interface CanDeactivate { export interface CanDeactivate {
routerCanDeactivate(nextInstruction: ComponentInstruction, routerCanDeactivate(nextInstruction: ComponentInstruction,
prevInstruction: ComponentInstruction): any; prevInstruction: ComponentInstruction): boolean |
Promise<boolean>;
} }

View File

@ -27,9 +27,9 @@ export abstract class PlatformLocation {
abstract onPopState(fn: UrlChangeListener): void; abstract onPopState(fn: UrlChangeListener): void;
abstract onHashChange(fn: UrlChangeListener): void; abstract onHashChange(fn: UrlChangeListener): void;
pathname: string; /* abstract */ get pathname(): string { return null; }
search: string; /* abstract */ get search(): string { return null; }
hash: string; /* abstract */ get hash(): string { return null; }
abstract replaceState(state: any, title: string, url: string): void; abstract replaceState(state: any, title: string, url: string): void;

View File

@ -4,6 +4,8 @@ import {RegexSerializer} from '../rules/route_paths/regex_route_path';
export {RouteDefinition} from '../route_definition'; export {RouteDefinition} from '../route_definition';
var __make_dart_analyzer_happy: Promise<any> = null;
/** /**
* The `RouteConfig` decorator defines routes for a given component. * The `RouteConfig` decorator defines routes for a given component.
* *
@ -136,7 +138,7 @@ export class AuxRoute extends AbstractRoute {
*/ */
@CONST() @CONST()
export class AsyncRoute extends AbstractRoute { export class AsyncRoute extends AbstractRoute {
loader: Function; loader: () => Promise<Type>;
aux: string = null; aux: string = null;
constructor({name, useAsDefault, path, regex, serializer, data, loader}: RouteDefinition) { constructor({name, useAsDefault, path, regex, serializer, data, loader}: RouteDefinition) {

View File

@ -92,7 +92,8 @@ export function normalizeRouteConfig(config: RouteDefinition,
} }
function wrapLoaderToReconfigureRegistry(loader: Function, registry: RouteRegistry): Function { function wrapLoaderToReconfigureRegistry(loader: Function, registry: RouteRegistry): () =>
Promise<Type> {
return () => { return () => {
return loader().then((componentType) => { return loader().then((componentType) => {
registry.configFromComponent(componentType); registry.configFromComponent(componentType);

View File

@ -18,7 +18,7 @@ export interface RouteDefinition {
regex?: string; regex?: string;
serializer?: RegexSerializer; serializer?: RegexSerializer;
component?: Type | ComponentDefinition; component?: Type | ComponentDefinition;
loader?: Function; loader?: () => Promise<Type>;
redirectTo?: any[]; redirectTo?: any[];
as?: string; as?: string;
name?: string; name?: string;
@ -34,6 +34,6 @@ export interface RouteDefinition {
*/ */
export interface ComponentDefinition { export interface ComponentDefinition {
type: string; type: string;
loader?: Function; loader?: () => Promise<Type>;
component?: Type; component?: Type;
} }

View File

@ -37,8 +37,9 @@ import {
import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_normalizer'; import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_normalizer';
import {parser, Url, convertUrlParamsToArray, pathSegmentsToUrl} from './url_parser'; import {parser, Url, convertUrlParamsToArray, pathSegmentsToUrl} from './url_parser';
import {GeneratedUrl} from './rules/route_paths/route_path';
var _resolveToNull = PromiseWrapper.resolve(null); var _resolveToNull = PromiseWrapper.resolve<Instruction>(null);
// A LinkItemArray is an array, which describes a set of routes // A LinkItemArray is an array, which describes a set of routes
// The items in the array are found in groups: // The items in the array are found in groups:
@ -180,7 +181,7 @@ export class RouteRegistry {
(candidate: Promise<RouteMatch>) => candidate.then((candidate: RouteMatch) => { (candidate: Promise<RouteMatch>) => candidate.then((candidate: RouteMatch) => {
if (candidate instanceof PathMatch) { if (candidate instanceof PathMatch) {
var auxParentInstructions = var auxParentInstructions: Instruction[] =
ancestorInstructions.length > 0 ? [ListWrapper.last(ancestorInstructions)] : []; ancestorInstructions.length > 0 ? [ListWrapper.last(ancestorInstructions)] : [];
var auxInstructions = var auxInstructions =
this._auxRoutesToUnresolved(candidate.remainingAux, auxParentInstructions); this._auxRoutesToUnresolved(candidate.remainingAux, auxParentInstructions);
@ -191,7 +192,7 @@ export class RouteRegistry {
return instruction; return instruction;
} }
var newAncestorInstructions = ancestorInstructions.concat([instruction]); var newAncestorInstructions: Instruction[] = ancestorInstructions.concat([instruction]);
return this._recognize(candidate.remaining, newAncestorInstructions) return this._recognize(candidate.remaining, newAncestorInstructions)
.then((childInstruction) => { .then((childInstruction) => {
@ -220,7 +221,7 @@ export class RouteRegistry {
return PromiseWrapper.resolve(this.generateDefault(parentComponent)); return PromiseWrapper.resolve(this.generateDefault(parentComponent));
} }
return PromiseWrapper.all(matchPromises).then(mostSpecific); return PromiseWrapper.all<Instruction>(matchPromises).then(mostSpecific);
} }
private _auxRoutesToUnresolved(auxRoutes: Url[], private _auxRoutesToUnresolved(auxRoutes: Url[],
@ -400,7 +401,7 @@ export class RouteRegistry {
// we'll figure out the rest of the route when we resolve the instruction and // we'll figure out the rest of the route when we resolve the instruction and
// perform a navigation // perform a navigation
if (isBlank(routeRecognizer.handler.componentType)) { if (isBlank(routeRecognizer.handler.componentType)) {
var generatedUrl = routeRecognizer.generateComponentPathValues(routeParams); var generatedUrl: GeneratedUrl = routeRecognizer.generateComponentPathValues(routeParams);
return new UnresolvedInstruction(() => { return new UnresolvedInstruction(() => {
return routeRecognizer.handler.resolveComponentType().then((_) => { return routeRecognizer.handler.resolveComponentType().then((_) => {
return this._generate(linkParams, ancestorInstructions, prevInstruction, _aux, return this._generate(linkParams, ancestorInstructions, prevInstruction, _aux,
@ -416,7 +417,7 @@ export class RouteRegistry {
// Next, recognize auxiliary instructions. // Next, recognize auxiliary instructions.
// If we have an ancestor instruction, we preserve whatever aux routes are active from it. // If we have an ancestor instruction, we preserve whatever aux routes are active from it.
while (linkParamIndex < linkParams.length && isArray(linkParams[linkParamIndex])) { while (linkParamIndex < linkParams.length && isArray(linkParams[linkParamIndex])) {
let auxParentInstruction = [parentInstruction]; let auxParentInstruction: Instruction[] = [parentInstruction];
let auxInstruction = this._generate(linkParams[linkParamIndex], auxParentInstruction, null, let auxInstruction = this._generate(linkParams[linkParamIndex], auxParentInstruction, null,
true, _originalLink); true, _originalLink);
@ -436,7 +437,7 @@ export class RouteRegistry {
// TODO: throw that there are extra link params beyond the terminal component // TODO: throw that there are extra link params beyond the terminal component
} }
} else { } else {
let childAncestorComponents = ancestorInstructions.concat([instruction]); let childAncestorComponents: Instruction[] = ancestorInstructions.concat([instruction]);
let remainingLinkParams = linkParams.slice(linkParamIndex); let remainingLinkParams = linkParams.slice(linkParamIndex);
childInstruction = this._generate(remainingLinkParams, childAncestorComponents, null, false, childInstruction = this._generate(remainingLinkParams, childAncestorComponents, null, false,
_originalLink); _originalLink);

View File

@ -75,7 +75,7 @@ export class Router {
* *
* You probably don't need to use this unless you're writing a reusable component. * You probably don't need to use this unless you're writing a reusable component.
*/ */
registerPrimaryOutlet(outlet: RouterOutlet): Promise<boolean> { registerPrimaryOutlet(outlet: RouterOutlet): Promise<any> {
if (isPresent(outlet.name)) { if (isPresent(outlet.name)) {
throw new BaseException(`registerPrimaryOutlet expects to be called with an unnamed outlet.`); throw new BaseException(`registerPrimaryOutlet expects to be called with an unnamed outlet.`);
} }
@ -109,7 +109,7 @@ export class Router {
* *
* You probably don't need to use this unless you're writing a reusable component. * You probably don't need to use this unless you're writing a reusable component.
*/ */
registerAuxOutlet(outlet: RouterOutlet): Promise<boolean> { registerAuxOutlet(outlet: RouterOutlet): Promise<any> {
var outletName = outlet.name; var outletName = outlet.name;
if (isBlank(outletName)) { if (isBlank(outletName)) {
throw new BaseException(`registerAuxOutlet expects to be called with an outlet with a name.`); throw new BaseException(`registerAuxOutlet expects to be called with an outlet with a name.`);
@ -230,7 +230,7 @@ export class Router {
unsettledInstructions.push(this._settleInstruction(instruction.child)); unsettledInstructions.push(this._settleInstruction(instruction.child));
} }
StringMapWrapper.forEach(instruction.auxInstruction, (instruction, _) => { StringMapWrapper.forEach(instruction.auxInstruction, (instruction: Instruction, _) => {
unsettledInstructions.push(this._settleInstruction(instruction)); unsettledInstructions.push(this._settleInstruction(instruction));
}); });
return PromiseWrapper.all(unsettledInstructions); return PromiseWrapper.all(unsettledInstructions);
@ -311,7 +311,7 @@ export class Router {
next = this._outlet.routerCanDeactivate(componentInstruction); next = this._outlet.routerCanDeactivate(componentInstruction);
} }
// TODO: aux route lifecycle hooks // TODO: aux route lifecycle hooks
return next.then((result) => { return next.then<boolean>((result): boolean | Promise<boolean> => {
if (result == false) { if (result == false) {
return false; return false;
} }
@ -346,7 +346,7 @@ export class Router {
} }
} }
var promises = []; var promises: Promise<any>[] = [];
this._auxRouters.forEach((router, name) => { this._auxRouters.forEach((router, name) => {
if (isPresent(instruction.auxInstruction[name])) { if (isPresent(instruction.auxInstruction[name])) {
promises.push(router.commit(instruction.auxInstruction[name])); promises.push(router.commit(instruction.auxInstruction[name]));
@ -405,7 +405,7 @@ export class Router {
} }
private _getAncestorInstructions(): Instruction[] { private _getAncestorInstructions(): Instruction[] {
var ancestorInstructions = [this.currentInstruction]; var ancestorInstructions: Instruction[] = [this.currentInstruction];
var ancestorRouter: Router = this; var ancestorRouter: Router = this;
while (isPresent(ancestorRouter = ancestorRouter.parent)) { while (isPresent(ancestorRouter = ancestorRouter.parent)) {
ancestorInstructions.unshift(ancestorRouter.currentInstruction); ancestorInstructions.unshift(ancestorRouter.currentInstruction);
@ -534,7 +534,7 @@ function canActivateOne(nextInstruction: Instruction,
next = canActivateOne(nextInstruction.child, next = canActivateOne(nextInstruction.child,
isPresent(prevInstruction) ? prevInstruction.child : null); isPresent(prevInstruction) ? prevInstruction.child : null);
} }
return next.then((result) => { return next.then<boolean>((result: boolean): boolean => {
if (result == false) { if (result == false) {
return false; return false;
} }

View File

@ -6,15 +6,15 @@ import {RouteData, BLANK_ROUTE_DATA} from '../../instruction';
export class AsyncRouteHandler implements RouteHandler { export class AsyncRouteHandler implements RouteHandler {
/** @internal */ /** @internal */
_resolvedComponent: Promise<any> = null; _resolvedComponent: Promise<Type> = null;
componentType: Type; componentType: Type;
public data: RouteData; public data: RouteData;
constructor(private _loader: Function, data: {[key: string]: any} = null) { constructor(private _loader: () => Promise<Type>, data: {[key: string]: any} = null) {
this.data = isPresent(data) ? new RouteData(data) : BLANK_ROUTE_DATA; this.data = isPresent(data) ? new RouteData(data) : BLANK_ROUTE_DATA;
} }
resolveComponentType(): Promise<any> { resolveComponentType(): Promise<Type> {
if (isPresent(this._resolvedComponent)) { if (isPresent(this._resolvedComponent)) {
return this._resolvedComponent; return this._resolvedComponent;
} }

View File

@ -113,7 +113,7 @@ export class UrlParser {
var path = matchUrlSegment(this._remaining); var path = matchUrlSegment(this._remaining);
this.capture(path); this.capture(path);
var aux = []; var aux: Url[] = [];
if (this.peekStartsWith('(')) { if (this.peekStartsWith('(')) {
aux = this.parseAuxiliaryRoutes(); aux = this.parseAuxiliaryRoutes();
} }
@ -126,7 +126,7 @@ export class UrlParser {
this.capture('/'); this.capture('/');
child = this.parseSegment(); child = this.parseSegment();
} }
var queryParams = null; var queryParams: {[key: string]: any} = null;
if (this.peekStartsWith('?')) { if (this.peekStartsWith('?')) {
queryParams = this.parseQueryParams(); queryParams = this.parseQueryParams();
} }
@ -144,15 +144,15 @@ export class UrlParser {
var path = matchUrlSegment(this._remaining); var path = matchUrlSegment(this._remaining);
this.capture(path); this.capture(path);
var matrixParams = null; var matrixParams: {[key: string]: any} = null;
if (this.peekStartsWith(';')) { if (this.peekStartsWith(';')) {
matrixParams = this.parseMatrixParams(); matrixParams = this.parseMatrixParams();
} }
var aux = []; var aux: Url[] = [];
if (this.peekStartsWith('(')) { if (this.peekStartsWith('(')) {
aux = this.parseAuxiliaryRoutes(); aux = this.parseAuxiliaryRoutes();
} }
var child = null; var child: Url = null;
if (this.peekStartsWith('/') && !this.peekStartsWith('//')) { if (this.peekStartsWith('/') && !this.peekStartsWith('//')) {
this.capture('/'); this.capture('/');
child = this.parseSegment(); child = this.parseSegment();
@ -161,7 +161,7 @@ export class UrlParser {
} }
parseQueryParams(): {[key: string]: any} { parseQueryParams(): {[key: string]: any} {
var params = {}; var params: {[key: string]: any} = {};
this.capture('?'); this.capture('?');
this.parseParam(params); this.parseParam(params);
while (this._remaining.length > 0 && this.peekStartsWith('&')) { while (this._remaining.length > 0 && this.peekStartsWith('&')) {
@ -172,7 +172,7 @@ export class UrlParser {
} }
parseMatrixParams(): {[key: string]: any} { parseMatrixParams(): {[key: string]: any} {
var params = {}; var params: {[key: string]: any} = {};
while (this._remaining.length > 0 && this.peekStartsWith(';')) { while (this._remaining.length > 0 && this.peekStartsWith(';')) {
this.capture(';'); this.capture(';');
this.parseParam(params); this.parseParam(params);
@ -200,7 +200,7 @@ export class UrlParser {
} }
parseAuxiliaryRoutes(): Url[] { parseAuxiliaryRoutes(): Url[] {
var routes = []; var routes: Url[] = [];
this.capture('('); this.capture('(');
while (!this.peekStartsWith(')') && this._remaining.length > 0) { while (!this.peekStartsWith(')') && this._remaining.length > 0) {

View File

@ -18,6 +18,6 @@ export function verifyNoBrowserErrors() {
} }
return logEntry.level.value > webdriver.logging.Level.WARNING.value; return logEntry.level.value > webdriver.logging.Level.WARNING.value;
}); });
expect(filteredLog.length).toEqual(0); expect(filteredLog).toEqual([]);
}); });
} }

View File

@ -254,8 +254,9 @@ export class TestComponentBuilder {
DOM.appendChild(doc.body, rootEl); DOM.appendChild(doc.body, rootEl);
return this._injector.get(DynamicComponentLoader) var promise: Promise<ComponentRef> =
.loadAsRoot(rootComponentType, `#${rootElId}`, this._injector) this._injector.get(DynamicComponentLoader)
.then((componentRef) => { return new ComponentFixture_(componentRef); }); .loadAsRoot(rootComponentType, `#${rootElId}`, this._injector);
return promise.then((componentRef) => { return new ComponentFixture_(componentRef); });
} }
} }

View File

@ -140,7 +140,7 @@ export function main() {
]); ]);
var value = null; var value = null;
c(new Control("invalid")).then(v => value = v); (<Promise<any>>c(new Control("invalid"))).then(v => value = v);
tick(1); tick(1);
@ -151,7 +151,7 @@ export function main() {
var c = Validators.composeAsync([asyncValidator("expected", {"one": true})]); var c = Validators.composeAsync([asyncValidator("expected", {"one": true})]);
var value = null; var value = null;
c(new Control("expected")).then(v => value = v); (<Promise<any>>c(new Control("expected"))).then(v => value = v);
tick(1); tick(1);
@ -162,7 +162,7 @@ export function main() {
var c = Validators.composeAsync([asyncValidator("expected", {"one": true}), null]); var c = Validators.composeAsync([asyncValidator("expected", {"one": true}), null]);
var value = null; var value = null;
c(new Control("invalid")).then(v => value = v); (<Promise<any>>c(new Control("invalid"))).then(v => value = v);
tick(1); tick(1);

View File

@ -23,6 +23,7 @@ import {
TimerWrapper TimerWrapper
} from 'angular2/src/facade/async'; } from 'angular2/src/facade/async';
import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {PromiseCompleter} from 'angular2/src/facade/promise';
export function main() { export function main() {
describe("AsyncPipe", () => { describe("AsyncPipe", () => {
@ -116,16 +117,16 @@ export function main() {
describe("Promise", () => { describe("Promise", () => {
var message = new Object(); var message = new Object();
var pipe; var pipe: AsyncPipe;
var completer; var completer: PromiseCompleter<any>;
var ref; var ref: SpyChangeDetectorRef;
// adds longer timers for passing tests in IE // adds longer timers for passing tests in IE
var timer = (!isBlank(DOM) && browserDetection.isIE) ? 50 : 0; var timer = (!isBlank(DOM) && browserDetection.isIE) ? 50 : 0;
beforeEach(() => { beforeEach(() => {
completer = PromiseWrapper.completer(); completer = PromiseWrapper.completer();
ref = new SpyChangeDetectorRef(); ref = new SpyChangeDetectorRef();
pipe = new AsyncPipe(ref); pipe = new AsyncPipe(<any>ref);
}); });
describe("transform", () => { describe("transform", () => {

View File

@ -76,9 +76,10 @@ export function main() {
describe('compile templates', () => { describe('compile templates', () => {
function runTests(compile) { function runTests(compile: (components: Type[]) => Promise<any[]>) {
it('should throw for non components', inject([AsyncTestCompleter], (async) => { it('should throw for non components', inject([AsyncTestCompleter], (async) => {
PromiseWrapper.catchError(PromiseWrapper.wrap(() => compile([NonComponent])), (error) => { PromiseWrapper.catchError(
PromiseWrapper.wrap(() => compile([NonComponent])), (error): any => {
expect(error.message) expect(error.message)
.toEqual( .toEqual(
`Could not compile '${stringify(NonComponent)}' because it is not a component.`); `Could not compile '${stringify(NonComponent)}' because it is not a component.`);

View File

@ -99,14 +99,14 @@ export function main() {
}); });
it('should contain a default value of "/packages" when nothing is provided for DART', it('should contain a default value of "/packages" when nothing is provided for DART',
inject([UrlResolver], (resolver) => { inject([UrlResolver], (resolver: UrlResolver) => {
if (IS_DART) { if (IS_DART) {
expect(resolver.resolve(null, 'package:file')).toEqual('/packages/file'); expect(resolver.resolve(null, 'package:file')).toEqual('/packages/file');
} }
})); }));
it('should contain a default value of "/" when nothing is provided for TS/ESM', it('should contain a default value of "/" when nothing is provided for TS/ESM',
inject([UrlResolver], (resolver) => { inject([UrlResolver], (resolver: UrlResolver) => {
if (!IS_DART) { if (!IS_DART) {
expect(resolver.resolve(null, 'package:file')).toEqual('/file'); expect(resolver.resolve(null, 'package:file')).toEqual('/file');
} }

View File

@ -65,8 +65,8 @@ export function main() {
}); });
})); }));
function mockAsyncAppInitializer(completer, providers: Array<any> = null, function mockAsyncAppInitializer(completer: PromiseCompleter<any>,
injector?: Injector) { providers: Array<any> = null, injector?: Injector) {
return () => { return () => {
if (providers != null) { if (providers != null) {
expectProviders(injector, providers); expectProviders(injector, providers);
@ -76,23 +76,11 @@ export function main() {
}; };
} }
function createSpyPromiseCompleter(): SpyObject {
let completer = PromiseWrapper.completer();
let completerSpy = <any>new SpyObject();
// Note that in TypeScript we need to provide a value for the promise attribute
// whereas in dart we need to override the promise getter
completerSpy.promise = completer.promise;
completerSpy.spy("get:promise").andReturn(completer.promise);
completerSpy.spy("resolve").andCallFake(completer.resolve);
completerSpy.spy("reject").andCallFake(completer.reject);
return completerSpy;
}
it("should wait for asyncronous app initializers", it("should wait for asyncronous app initializers",
inject([AsyncTestCompleter, Injector], (async, injector) => { inject([AsyncTestCompleter, Injector], (async, injector) => {
let ref = new PlatformRef_(injector, null); let ref = new PlatformRef_(injector, null);
let completer = createSpyPromiseCompleter(); let completer: PromiseCompleter<any> = PromiseWrapper.completer();
let SYNC_PROVIDERS = [ let SYNC_PROVIDERS = [
new Provider(Bar, {useValue: new Bar()}), new Provider(Bar, {useValue: new Bar()}),
new Provider(APP_INITIALIZER, new Provider(APP_INITIALIZER,
@ -102,8 +90,7 @@ export function main() {
.then((appRef) => { .then((appRef) => {
expectProviders(appRef.injector, expectProviders(appRef.injector,
SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1)); SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1));
expect(completer.spy("resolve")).toHaveBeenCalled(); completer.promise.then((_) => async.done());
async.done();
}); });
})); }));
@ -111,13 +98,13 @@ export function main() {
inject([AsyncTestCompleter, Injector], (async, injector) => { inject([AsyncTestCompleter, Injector], (async, injector) => {
let ref = new PlatformRef_(injector, null); let ref = new PlatformRef_(injector, null);
let ASYNC_PROVIDERS = [new Provider(Foo, {useValue: new Foo()})]; let ASYNC_PROVIDERS = [new Provider(Foo, {useValue: new Foo()})];
let completer = createSpyPromiseCompleter(); let completer: PromiseCompleter<any> = PromiseWrapper.completer();
let SYNC_PROVIDERS = [ let SYNC_PROVIDERS = [
new Provider(Bar, {useValue: new Bar()}), new Provider(Bar, {useValue: new Bar()}),
new Provider(APP_INITIALIZER, new Provider(APP_INITIALIZER,
{ {
useFactory: (injector) => mockAsyncAppInitializer( useFactory: (injector) => mockAsyncAppInitializer(
completer, ASYNC_PROVIDERS, injector), <any>completer, ASYNC_PROVIDERS, injector),
multi: true, multi: true,
deps: [Injector] deps: [Injector]
}) })
@ -126,8 +113,7 @@ export function main() {
.then((appRef) => { .then((appRef) => {
expectProviders(appRef.injector, expectProviders(appRef.injector,
SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1)); SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1));
expect(completer.spy("resolve")).toHaveBeenCalled(); completer.promise.then((_) => async.done());
async.done();
}); });
})); }));
}); });

View File

@ -18,6 +18,7 @@ import {Compiler} from 'angular2/src/core/linker/compiler';
import {reflector, ReflectionInfo} from 'angular2/src/core/reflection/reflection'; import {reflector, ReflectionInfo} from 'angular2/src/core/reflection/reflection';
import {Compiler_} from "angular2/src/core/linker/compiler"; import {Compiler_} from "angular2/src/core/linker/compiler";
import {HostViewFactory} from 'angular2/src/core/linker/view'; import {HostViewFactory} from 'angular2/src/core/linker/view';
import {HostViewFactoryRef_} from 'angular2/src/core/linker/view_ref';
export function main() { export function main() {
describe('Compiler', () => { describe('Compiler', () => {
@ -31,11 +32,12 @@ export function main() {
})); }));
it('should read the template from an annotation', it('should read the template from an annotation',
inject([AsyncTestCompleter, Compiler], (async, compiler) => { inject([AsyncTestCompleter, Compiler], (async, compiler: Compiler) => {
compiler.compileInHost(SomeComponent) compiler.compileInHost(SomeComponent)
.then((hostViewFactoryRef) => { .then((hostViewFactoryRef: HostViewFactoryRef_) => {
expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory); expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory);
async.done(); async.done();
return null;
}); });
})); }));

View File

@ -113,7 +113,7 @@ class SomeDirectiveWithoutMetadata {}
export function main() { export function main() {
describe("DirectiveResolver", () => { describe("DirectiveResolver", () => {
var resolver; var resolver: DirectiveResolver;
beforeEach(() => { resolver = new DirectiveResolver(); }); beforeEach(() => { resolver = new DirectiveResolver(); });

View File

@ -34,7 +34,7 @@ export function main() {
describe("loading into a location", () => { describe("loading into a location", () => {
it('should work', it('should work',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => { (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView( tcb.overrideView(
MyComp, MyComp,
new ViewMetadata( new ViewMetadata(
@ -52,7 +52,7 @@ export function main() {
it('should return a disposable component ref', it('should return a disposable component ref',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => { (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView( tcb.overrideView(
MyComp, MyComp,
new ViewMetadata( new ViewMetadata(
@ -72,7 +72,7 @@ export function main() {
it('should allow to dispose even if the location has been removed', it('should allow to dispose even if the location has been removed',
inject( inject(
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => { (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({ tcb.overrideView(MyComp, new ViewMetadata({
template: '<child-cmp *ngIf="ctxBoolProp"></child-cmp>', template: '<child-cmp *ngIf="ctxBoolProp"></child-cmp>',
directives: [NgIf, ChildComp] directives: [NgIf, ChildComp]
@ -109,7 +109,7 @@ export function main() {
it('should update host properties', it('should update host properties',
inject( inject(
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => { (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView( tcb.overrideView(
MyComp, new ViewMetadata( MyComp, new ViewMetadata(
{template: '<location #loc></location>', directives: [Location]})) {template: '<location #loc></location>', directives: [Location]}))
@ -131,7 +131,7 @@ export function main() {
it('should leave the view tree in a consistent state if hydration fails', it('should leave the view tree in a consistent state if hydration fails',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => { (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({ tcb.overrideView(MyComp, new ViewMetadata({
template: '<div><location #loc></location></div>', template: '<div><location #loc></location></div>',
directives: [Location] directives: [Location]
@ -147,13 +147,14 @@ export function main() {
expect(error.message).toContain("ThrownInConstructor"); expect(error.message).toContain("ThrownInConstructor");
expect(() => tc.detectChanges()).not.toThrow(); expect(() => tc.detectChanges()).not.toThrow();
async.done(); async.done();
return null;
}); });
}); });
})); }));
it('should throw if the variable does not exist', it('should throw if the variable does not exist',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => { (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView( tcb.overrideView(
MyComp, MyComp,
new ViewMetadata( new ViewMetadata(
@ -169,7 +170,7 @@ export function main() {
it('should allow to pass projectable nodes', it('should allow to pass projectable nodes',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => { (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, tcb.overrideView(MyComp,
new ViewMetadata({template: '<div #loc></div>', directives: []})) new ViewMetadata({template: '<div #loc></div>', directives: []}))
.createAsync(MyComp) .createAsync(MyComp)
@ -187,7 +188,7 @@ export function main() {
it('should throw if not enough projectable nodes are passed in', it('should throw if not enough projectable nodes are passed in',
inject( inject(
[DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => { (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, tcb.overrideView(MyComp,
new ViewMetadata({template: '<div #loc></div>', directives: []})) new ViewMetadata({template: '<div #loc></div>', directives: []}))
.createAsync(MyComp) .createAsync(MyComp)
@ -199,6 +200,7 @@ export function main() {
expect(e.message).toContain( expect(e.message).toContain(
`The component ${stringify(DynamicallyLoadedWithNgContent)} has 1 <ng-content> elements, but only 0 slots were provided`); `The component ${stringify(DynamicallyLoadedWithNgContent)} has 1 <ng-content> elements, but only 0 slots were provided`);
async.done(); async.done();
return null;
}); });
}); });
})); }));
@ -208,7 +210,7 @@ export function main() {
describe("loading next to a location", () => { describe("loading next to a location", () => {
it('should work', it('should work',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => { (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({ tcb.overrideView(MyComp, new ViewMetadata({
template: '<div><location #loc></location></div>', template: '<div><location #loc></location></div>',
directives: [Location] directives: [Location]
@ -228,7 +230,7 @@ export function main() {
it('should return a disposable component ref', it('should return a disposable component ref',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => { (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({ tcb.overrideView(MyComp, new ViewMetadata({
template: '<div><location #loc></location></div>', template: '<div><location #loc></location></div>',
directives: [Location] directives: [Location]
@ -262,7 +264,7 @@ export function main() {
it('should update host properties', it('should update host properties',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => { (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({ tcb.overrideView(MyComp, new ViewMetadata({
template: '<div><location #loc></location></div>', template: '<div><location #loc></location></div>',
directives: [Location] directives: [Location]
@ -288,7 +290,7 @@ export function main() {
it('should allow to pass projectable nodes', it('should allow to pass projectable nodes',
inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter],
(loader, tcb: TestComponentBuilder, async) => { (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => {
tcb.overrideView(MyComp, new ViewMetadata({template: '', directives: [Location]})) tcb.overrideView(MyComp, new ViewMetadata({template: '', directives: [Location]}))
.createAsync(MyComp) .createAsync(MyComp)
.then((tc) => { .then((tc) => {
@ -309,7 +311,8 @@ export function main() {
describe('loadAsRoot', () => { describe('loadAsRoot', () => {
it('should allow to create, update and destroy components', it('should allow to create, update and destroy components',
inject([AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector], inject([AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector],
(async, loader, doc, injector) => { (async: AsyncTestCompleter, loader: DynamicComponentLoader, doc,
injector: Injector) => {
var rootEl = createRootElement(doc, 'child-cmp'); var rootEl = createRootElement(doc, 'child-cmp');
DOM.appendChild(doc.body, rootEl); DOM.appendChild(doc.body, rootEl);
loader.loadAsRoot(ChildComp, null, injector) loader.loadAsRoot(ChildComp, null, injector)
@ -338,7 +341,8 @@ export function main() {
it('should allow to pass projectable nodes', it('should allow to pass projectable nodes',
inject([AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector], inject([AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector],
(async, loader, doc, injector) => { (async: AsyncTestCompleter, loader: DynamicComponentLoader, doc,
injector: Injector) => {
var rootEl = createRootElement(doc, 'dummy'); var rootEl = createRootElement(doc, 'dummy');
DOM.appendChild(doc.body, rootEl); DOM.appendChild(doc.body, rootEl);
loader.loadAsRoot(DynamicallyLoadedWithNgContent, null, injector, null, loader.loadAsRoot(DynamicallyLoadedWithNgContent, null, injector, null,

View File

@ -818,7 +818,8 @@ function declareTests() {
tcb.createAsync(MyComp).then(root => { fixture = root; }); tcb.createAsync(MyComp).then(root => { fixture = root; });
tick(); tick();
var cmp = fixture.debugElement.children[0].getLocal('cmp'); var cmp: PushCmpWithAsyncPipe =
fixture.debugElement.children[0].getLocal('cmp');
fixture.detectChanges(); fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(1); expect(cmp.numberOfChecks).toEqual(1);
@ -1155,7 +1156,7 @@ function declareTests() {
.createAsync(MyComp) .createAsync(MyComp)
.then((fixture) => { .then((fixture) => {
var tc = fixture.debugElement.children[0].children[0]; var tc = fixture.debugElement.children[0].children[0];
var dynamicVp = tc.inject(DynamicViewport); var dynamicVp: DynamicViewport = tc.inject(DynamicViewport);
dynamicVp.done.then((_) => { dynamicVp.done.then((_) => {
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.debugElement.children[0].children[1].nativeElement) expect(fixture.debugElement.children[0].children[1].nativeElement)
@ -1549,7 +1550,7 @@ function declareTests() {
it('should support moving embedded views around', it('should support moving embedded views around',
inject([TestComponentBuilder, AsyncTestCompleter, ANCHOR_ELEMENT], inject([TestComponentBuilder, AsyncTestCompleter, ANCHOR_ELEMENT],
(tcb, async, anchorElement) => { (tcb: TestComponentBuilder, async, anchorElement) => {
tcb.overrideView(MyComp, new ViewMetadata({ tcb.overrideView(MyComp, new ViewMetadata({
template: '<div><div *someImpvp="ctxBoolProp">hello</div></div>', template: '<div><div *someImpvp="ctxBoolProp">hello</div></div>',
directives: [SomeImperativeViewport] directives: [SomeImperativeViewport]
@ -1950,7 +1951,7 @@ class SimpleImperativeViewComponent {
@Directive({selector: 'dynamic-vp'}) @Directive({selector: 'dynamic-vp'})
@Injectable() @Injectable()
class DynamicViewport { class DynamicViewport {
done; done: Promise<any>;
constructor(vc: ViewContainerRef, compiler: Compiler) { constructor(vc: ViewContainerRef, compiler: Compiler) {
var myService = new MyService(); var myService = new MyService();
myService.greeting = 'dynamic greet'; myService.greeting = 'dynamic greet';

View File

@ -286,7 +286,7 @@ export function main() {
// important as we are removing the ng-content element during compilation, // important as we are removing the ng-content element during compilation,
// which could skrew up text node indices. // which could skrew up text node indices.
it('should support text nodes after content tags', it('should support text nodes after content tags',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb, async) => { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
tcb.overrideView( tcb.overrideView(
MainComp, MainComp,
@ -307,7 +307,7 @@ export function main() {
// important as we are moving style tags around during compilation, // important as we are moving style tags around during compilation,
// which could skrew up text node indices. // which could skrew up text node indices.
it('should support text nodes after style tags', it('should support text nodes after style tags',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb, async) => { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
tcb.overrideView( tcb.overrideView(
MainComp, MainComp,

View File

@ -43,7 +43,7 @@ class SimpleClass {}
export function main() { export function main() {
describe("ViewResolver", () => { describe("ViewResolver", () => {
var resolver; var resolver: ViewResolver;
beforeEach(() => { resolver = new ViewResolver(); }); beforeEach(() => { resolver = new ViewResolver(); });

View File

@ -566,7 +566,7 @@ function commonTests() {
it('should call onTurnStart and onTurnDone for promises created outside of run body', it('should call onTurnStart and onTurnDone for promises created outside of run body',
inject([AsyncTestCompleter], (async) => { inject([AsyncTestCompleter], (async) => {
var promise; var promise: Promise<any>;
macroTask(() => { macroTask(() => {
_zone.runOutsideAngular(() => { _zone.runOutsideAngular(() => {

View File

@ -674,7 +674,7 @@ function commonTests() {
logOnTurnStart(); logOnTurnStart();
logOnTurnDone(); logOnTurnDone();
var promise; var promise: Promise<any>;
macroTask(() => { macroTask(() => {
_zone.runOutsideAngular(() => { _zone.runOutsideAngular(() => {

View File

@ -18,7 +18,7 @@ import {isBlank} from 'angular2/src/facade/lang';
export function main() { export function main() {
describe('MockViewResolver', () => { describe('MockViewResolver', () => {
var viewResolver; var viewResolver: MockViewResolver;
beforeEach(() => { viewResolver = new MockViewResolver(); }); beforeEach(() => { viewResolver = new MockViewResolver(); });

View File

@ -25,7 +25,7 @@ import {provide, Inject, Injector, PLATFORM_INITIALIZER, APP_INITIALIZER} from '
import {disposePlatform} from 'angular2/src/core/application_ref'; import {disposePlatform} from 'angular2/src/core/application_ref';
import {ExceptionHandler} from 'angular2/src/facade/exceptions'; import {ExceptionHandler} from 'angular2/src/facade/exceptions';
import {Testability, TestabilityRegistry} from 'angular2/src/core/testability/testability'; import {Testability, TestabilityRegistry} from 'angular2/src/core/testability/testability';
import {ComponentRef_} from "angular2/src/core/linker/dynamic_component_loader"; import {ComponentRef_, ComponentRef} from "angular2/src/core/linker/dynamic_component_loader";
@Component({selector: 'hello-app'}) @Component({selector: 'hello-app'})
@View({template: '{{greeting}} world!'}) @View({template: '{{greeting}} world!'})
@ -243,11 +243,11 @@ export function main() {
it('should register each application with the testability registry', it('should register each application with the testability registry',
inject([AsyncTestCompleter], (async) => { inject([AsyncTestCompleter], (async) => {
var refPromise1 = bootstrap(HelloRootCmp, testProviders); var refPromise1: Promise<ComponentRef> = bootstrap(HelloRootCmp, testProviders);
var refPromise2 = bootstrap(HelloRootCmp2, testProviders); var refPromise2: Promise<ComponentRef> = bootstrap(HelloRootCmp2, testProviders);
PromiseWrapper.all([refPromise1, refPromise2]) PromiseWrapper.all([refPromise1, refPromise2])
.then((refs: ApplicationRef[]) => { .then((refs: ComponentRef[]) => {
var registry = refs[0].injector.get(TestabilityRegistry); var registry = refs[0].injector.get(TestabilityRegistry);
var testabilities = var testabilities =
[refs[0].injector.get(Testability), refs[1].injector.get(Testability)]; [refs[0].injector.get(Testability), refs[1].injector.get(Testability)];

View File

@ -430,8 +430,8 @@ function syncRoutesWithSyncChildrenWithDefaultRoutesWithoutParams() {
} }
function syncRoutesWithDynamicComponents() { function syncRoutesWithDynamicComponents() {
var fixture; var fixture: ComponentFixture;
var tcb; var tcb: TestComponentBuilder;
var rtr: Router; var rtr: Router;
beforeEachProviders(() => TEST_ROUTER_PROVIDERS); beforeEachProviders(() => TEST_ROUTER_PROVIDERS);

View File

@ -56,11 +56,12 @@ export function main() {
var tcb: TestComponentBuilder; var tcb: TestComponentBuilder;
var fixture: ComponentFixture; var fixture: ComponentFixture;
var rtr; var rtr: Router;
beforeEachProviders(() => TEST_ROUTER_PROVIDERS); beforeEachProviders(() => TEST_ROUTER_PROVIDERS);
beforeEach(inject([TestComponentBuilder, Router], (tcBuilder, router) => { beforeEach(inject([TestComponentBuilder, Router],
(tcBuilder: TestComponentBuilder, router: Router) => {
tcb = tcBuilder; tcb = tcBuilder;
rtr = router; rtr = router;
cmpInstanceCount = 0; cmpInstanceCount = 0;

View File

@ -49,7 +49,8 @@ export function main() {
describe('routerLink directive', function() { describe('routerLink directive', function() {
var tcb: TestComponentBuilder; var tcb: TestComponentBuilder;
var fixture: ComponentFixture; var fixture: ComponentFixture;
var router, location; var router: Router;
var location: Location;
beforeEachProviders(() => [ beforeEachProviders(() => [
RouteRegistry, RouteRegistry,
@ -60,7 +61,8 @@ export function main() {
provide(TEMPLATE_TRANSFORMS, {useClass: RouterLinkTransform, multi: true}) provide(TEMPLATE_TRANSFORMS, {useClass: RouterLinkTransform, multi: true})
]); ]);
beforeEach(inject([TestComponentBuilder, Router, Location], (tcBuilder, rtr, loc) => { beforeEach(inject([TestComponentBuilder, Router, Location],
(tcBuilder, rtr: Router, loc: Location) => {
tcb = tcBuilder; tcb = tcBuilder;
router = rtr; router = rtr;
location = loc; location = loc;
@ -77,7 +79,7 @@ export function main() {
it('should generate absolute hrefs that include the base href', it('should generate absolute hrefs that include the base href',
inject([AsyncTestCompleter], (async) => { inject([AsyncTestCompleter], (async) => {
location.setBaseHref('/my/base'); (<SpyLocation>location).setBaseHref('/my/base');
compile('<a href="hello" [routerLink]="[\'./User\']"></a>') compile('<a href="hello" [routerLink]="[\'./User\']"></a>')
.then((_) => router.config( .then((_) => router.config(
[new Route({path: '/user', component: UserCmp, name: 'User'})])) [new Route({path: '/user', component: UserCmp, name: 'User'})]))
@ -345,7 +347,7 @@ export function main() {
// router navigation is async. // router navigation is async.
router.subscribe((_) => { router.subscribe((_) => {
expect(location.urlChanges).toEqual(['/user']); expect((<SpyLocation>location).urlChanges).toEqual(['/user']);
async.done(); async.done();
}); });
}); });
@ -353,7 +355,7 @@ export function main() {
it('should navigate to link hrefs in presence of base href', it('should navigate to link hrefs in presence of base href',
inject([AsyncTestCompleter], (async) => { inject([AsyncTestCompleter], (async) => {
location.setBaseHref('/base'); (<SpyLocation>location).setBaseHref('/base');
compile('<a href="hello" [routerLink]="[\'./User\']"></a>') compile('<a href="hello" [routerLink]="[\'./User\']"></a>')
.then((_) => router.config( .then((_) => router.config(
[new Route({path: '/user', component: UserCmp, name: 'User'})])) [new Route({path: '/user', component: UserCmp, name: 'User'})]))
@ -367,7 +369,7 @@ export function main() {
// router navigation is async. // router navigation is async.
router.subscribe((_) => { router.subscribe((_) => {
expect(location.urlChanges).toEqual(['/base/user']); expect((<SpyLocation>location).urlChanges).toEqual(['/base/user']);
async.done(); async.done();
}); });
}); });

View File

@ -25,7 +25,7 @@ import {
export function main() { export function main() {
describe('RouteRegistry', () => { describe('RouteRegistry', () => {
var registry; var registry: RouteRegistry;
beforeEach(() => { registry = new RouteRegistry(RootHostCmp); }); beforeEach(() => { registry = new RouteRegistry(RootHostCmp); });

View File

@ -30,10 +30,12 @@ import {
import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver'; import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';
import {provide} from 'angular2/core'; import {provide} from 'angular2/core';
import {RouterOutlet} from 'angular2/src/router/directives/router_outlet';
export function main() { export function main() {
describe('Router', () => { describe('Router', () => {
var router, location; var router: Router;
var location: Location;
beforeEachProviders(() => [ beforeEachProviders(() => [
RouteRegistry, RouteRegistry,
@ -44,7 +46,7 @@ export function main() {
]); ]);
beforeEach(inject([Router, Location], (rtr, loc) => { beforeEach(inject([Router, Location], (rtr: Router, loc: Location) => {
router = rtr; router = rtr;
location = loc; location = loc;
})); }));
@ -56,8 +58,8 @@ export function main() {
router.config([new Route({path: '/', component: DummyComponent})]) router.config([new Route({path: '/', component: DummyComponent})])
.then((_) => router.registerPrimaryOutlet(outlet)) .then((_) => router.registerPrimaryOutlet(outlet))
.then((_) => { .then((_) => {
expect(outlet.spy('activate')).toHaveBeenCalled(); expect((<any>outlet).spy('activate')).toHaveBeenCalled();
expect(location.urlChanges).toEqual([]); expect((<SpyLocation>location).urlChanges).toEqual([]);
async.done(); async.done();
}); });
})); }));
@ -70,8 +72,8 @@ export function main() {
.then((_) => router.config([new Route({path: '/a', component: DummyComponent})])) .then((_) => router.config([new Route({path: '/a', component: DummyComponent})]))
.then((_) => router.navigateByUrl('/a')) .then((_) => router.navigateByUrl('/a'))
.then((_) => { .then((_) => {
expect(outlet.spy('activate')).toHaveBeenCalled(); expect((<any>outlet).spy('activate')).toHaveBeenCalled();
expect(location.urlChanges).toEqual(['/a']); expect((<SpyLocation>location).urlChanges).toEqual(['/a']);
async.done(); async.done();
}); });
})); }));
@ -85,8 +87,8 @@ export function main() {
[new Route({path: '/a', component: DummyComponent, name: 'A'})])) [new Route({path: '/a', component: DummyComponent, name: 'A'})]))
.then((_) => router.navigate(['/A'])) .then((_) => router.navigate(['/A']))
.then((_) => { .then((_) => {
expect(outlet.spy('activate')).toHaveBeenCalled(); expect((<any>outlet).spy('activate')).toHaveBeenCalled();
expect(location.urlChanges).toEqual(['/a']); expect((<SpyLocation>location).urlChanges).toEqual(['/a']);
async.done(); async.done();
}); });
})); }));
@ -99,8 +101,8 @@ export function main() {
.then((_) => router.config([new Route({path: '/b', component: DummyComponent})])) .then((_) => router.config([new Route({path: '/b', component: DummyComponent})]))
.then((_) => router.navigateByUrl('/b', true)) .then((_) => router.navigateByUrl('/b', true))
.then((_) => { .then((_) => {
expect(outlet.spy('activate')).toHaveBeenCalled(); expect((<any>outlet).spy('activate')).toHaveBeenCalled();
expect(location.urlChanges).toEqual([]); expect((<SpyLocation>location).urlChanges).toEqual([]);
async.done(); async.done();
}); });
})); }));
@ -119,11 +121,11 @@ export function main() {
])) ]))
.then((_) => { .then((_) => {
router.subscribe((_) => { router.subscribe((_) => {
expect(location.urlChanges).toEqual(['hash: a', 'replace: /b']); expect((<SpyLocation>location).urlChanges).toEqual(['hash: a', 'replace: /b']);
async.done(); async.done();
}); });
location.simulateHashChange('a'); (<SpyLocation>location).simulateHashChange('a');
}); });
})); }));
@ -135,11 +137,11 @@ export function main() {
.then((_) => router.config([new Route({path: '/a', component: DummyComponent})])) .then((_) => router.config([new Route({path: '/a', component: DummyComponent})]))
.then((_) => { .then((_) => {
router.subscribe((_) => { router.subscribe((_) => {
expect(location.urlChanges).toEqual(['hash: a']); expect((<SpyLocation>location).urlChanges).toEqual(['hash: a']);
async.done(); async.done();
}); });
location.simulateHashChange('a'); (<SpyLocation>location).simulateHashChange('a');
}); });
})); }));
@ -149,11 +151,11 @@ export function main() {
router.registerPrimaryOutlet(outlet) router.registerPrimaryOutlet(outlet)
.then((_) => router.navigateByUrl('/a')) .then((_) => router.navigateByUrl('/a'))
.then((_) => { .then((_) => {
expect(outlet.spy('activate')).not.toHaveBeenCalled(); expect((<any>outlet).spy('activate')).not.toHaveBeenCalled();
return router.config([new Route({path: '/a', component: DummyComponent})]); return router.config([new Route({path: '/a', component: DummyComponent})]);
}) })
.then((_) => { .then((_) => {
expect(outlet.spy('activate')).toHaveBeenCalled(); expect((<any>outlet).spy('activate')).toHaveBeenCalled();
async.done(); async.done();
}); });
})); }));
@ -193,7 +195,7 @@ export function main() {
var instruction = router.generate(['/FirstCmp']); var instruction = router.generate(['/FirstCmp']);
router.navigateByInstruction(instruction) router.navigateByInstruction(instruction)
.then((_) => { .then((_) => {
expect(outlet.spy('activate')).toHaveBeenCalled(); expect((<any>outlet).spy('activate')).toHaveBeenCalled();
async.done(); async.done();
}); });
})); }));
@ -310,13 +312,13 @@ class DummyComponent {}
class DummyParentComp { class DummyParentComp {
} }
function makeDummyOutlet() { function makeDummyOutlet(): RouterOutlet {
var ref = new SpyRouterOutlet(); var ref = new SpyRouterOutlet();
ref.spy('canActivate').andCallFake((_) => PromiseWrapper.resolve(true)); ref.spy('canActivate').andCallFake((_) => PromiseWrapper.resolve(true));
ref.spy('routerCanReuse').andCallFake((_) => PromiseWrapper.resolve(false)); ref.spy('routerCanReuse').andCallFake((_) => PromiseWrapper.resolve(false));
ref.spy('routerCanDeactivate').andCallFake((_) => PromiseWrapper.resolve(true)); ref.spy('routerCanDeactivate').andCallFake((_) => PromiseWrapper.resolve(true));
ref.spy('activate').andCallFake((_) => PromiseWrapper.resolve(true)); ref.spy('activate').andCallFake((_) => PromiseWrapper.resolve(true));
return ref; return <any>ref;
} }
class AppCmp {} class AppCmp {}

View File

@ -21,6 +21,7 @@ import {isPresent, Type} from 'angular2/src/facade/lang';
import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {MouseEvent, KeyboardEvent} from 'angular2/src/facade/browser'; import {MouseEvent, KeyboardEvent} from 'angular2/src/facade/browser';
import {KeyCodes} from 'angular2_material/src/core/key_codes'; import {KeyCodes} from 'angular2_material/src/core/key_codes';
import {PromiseCompleter} from 'angular2/src/facade/promise';
// TODO(jelbourn): Opener of dialog can control where it is rendered. // TODO(jelbourn): Opener of dialog can control where it is rendered.
// TODO(jelbourn): body scrolling is disabled while dialog is open. // TODO(jelbourn): body scrolling is disabled while dialog is open.
@ -61,7 +62,7 @@ export class MdDialog {
// First, load the MdDialogContainer, into which the given component will be loaded. // First, load the MdDialogContainer, into which the given component will be loaded.
return this.componentLoader.loadNextToLocation(MdDialogContainer, elementRef) return this.componentLoader.loadNextToLocation(MdDialogContainer, elementRef)
.then(containerRef => { .then /*<ComponentRef>*/ ((containerRef: ComponentRef) => {
// TODO(tbosch): clean this up when we have custom renderers // TODO(tbosch): clean this up when we have custom renderers
// (https://github.com/angular/angular/issues/1807) // (https://github.com/angular/angular/issues/1807)
// TODO(jelbourn): Don't use direct DOM access. Need abstraction to create an element // TODO(jelbourn): Don't use direct DOM access. Need abstraction to create an element
@ -84,7 +85,7 @@ export class MdDialog {
// Now load the given component into the MdDialogContainer. // Now load the given component into the MdDialogContainer.
return this.componentLoader.loadNextToLocation(type, containerRef.instance.contentRef, return this.componentLoader.loadNextToLocation(type, containerRef.instance.contentRef,
bindings) bindings)
.then(contentRef => { .then((contentRef: ComponentRef) => {
// Wrap both component refs for the container and the content so that we can return // Wrap both component refs for the container and the content so that we can return
// the `instance` of the content but the dispose method of the container back to the // the `instance` of the content but the dispose method of the container back to the
@ -92,7 +93,7 @@ export class MdDialog {
dialogRef.contentRef = contentRef; dialogRef.contentRef = contentRef;
containerRef.instance.dialogRef = dialogRef; containerRef.instance.dialogRef = dialogRef;
backdropRefPromise.then(backdropRef => { backdropRefPromise.then((backdropRef: ComponentRef) => {
dialogRef.whenClosed.then((_) => { backdropRef.dispose(); }); dialogRef.whenClosed.then((_) => { backdropRef.dispose(); });
}); });
@ -104,7 +105,7 @@ export class MdDialog {
/** Loads the dialog backdrop (transparent overlay over the rest of the page). */ /** Loads the dialog backdrop (transparent overlay over the rest of the page). */
_openBackdrop(elementRef: ElementRef, bindings: ResolvedProvider[]): Promise<ComponentRef> { _openBackdrop(elementRef: ElementRef, bindings: ResolvedProvider[]): Promise<ComponentRef> {
return this.componentLoader.loadNextToLocation(MdBackdrop, elementRef, bindings) return this.componentLoader.loadNextToLocation(MdBackdrop, elementRef, bindings)
.then((componentRef) => { .then((componentRef: ComponentRef) => {
// TODO(tbosch): clean this up when we have custom renderers // TODO(tbosch): clean this up when we have custom renderers
// (https://github.com/angular/angular/issues/1807) // (https://github.com/angular/angular/issues/1807)
var backdropElement = componentRef.location.nativeElement; var backdropElement = componentRef.location.nativeElement;
@ -139,10 +140,10 @@ export class MdDialogRef {
isClosed: boolean; isClosed: boolean;
// Deferred resolved when the dialog is closed. The promise for this deferred is publicly exposed. // Deferred resolved when the dialog is closed. The promise for this deferred is publicly exposed.
whenClosedDeferred: any; whenClosedDeferred: PromiseCompleter<any>;
// Deferred resolved when the content ComponentRef is set. Only used internally. // Deferred resolved when the content ComponentRef is set. Only used internally.
contentRefDeferred: any; contentRefDeferred: PromiseCompleter<any>;
constructor() { constructor() {
this._contentRef = null; this._contentRef = null;

View File

@ -33,7 +33,9 @@ export class Runner {
this._defaultBindings = defaultBindings; this._defaultBindings = defaultBindings;
} }
sample({id, execute, prepare, microMetrics, bindings}): Promise<SampleState> { sample({id, execute, prepare, microMetrics, bindings}:
{id: string, execute?: any, prepare?: any, microMetrics?: any, bindings?: any}):
Promise<SampleState> {
var sampleBindings = [ var sampleBindings = [
_DEFAULT_PROVIDERS, _DEFAULT_PROVIDERS,
this._defaultBindings, this._defaultBindings,

View File

@ -62,8 +62,8 @@ export class Sampler {
return loop(new SampleState([], null)); return loop(new SampleState([], null));
} }
_iterate(lastState) { _iterate(lastState): Promise<SampleState> {
var resultPromise; var resultPromise: Promise<any>;
if (isPresent(this._prepare)) { if (isPresent(this._prepare)) {
resultPromise = this._driver.waitFor(this._prepare); resultPromise = this._driver.waitFor(this._prepare);
} else { } else {

View File

@ -39,7 +39,7 @@ export function main() {
captureFrames?: boolean, captureFrames?: boolean,
receivedData?: boolean, receivedData?: boolean,
requestCount?: boolean requestCount?: boolean
} = {}) { } = {}): Metric {
commandLog = []; commandLog = [];
if (isBlank(perfLogFeatures)) { if (isBlank(perfLogFeatures)) {
perfLogFeatures = perfLogFeatures =
@ -384,7 +384,7 @@ export function main() {
aggregate( aggregate(
[eventFactory.instant('frame', 4), eventFactory.markEnd('frameCapture', 5)], [eventFactory.instant('frame', 4), eventFactory.markEnd('frameCapture', 5)],
{captureFrames: true}), {captureFrames: true}),
(err) => { (err): any => {
expect(() => { throw err; }) expect(() => { throw err; })
.toThrowError('missing start event for frame capture'); .toThrowError('missing start event for frame capture');
async.done(); async.done();
@ -396,7 +396,7 @@ export function main() {
aggregate( aggregate(
[eventFactory.markStart('frameCapture', 3), eventFactory.instant('frame', 4)], [eventFactory.markStart('frameCapture', 3), eventFactory.instant('frame', 4)],
{captureFrames: true}), {captureFrames: true}),
(err) => { (err): any => {
expect(() => { throw err; }).toThrowError('missing end event for frame capture'); expect(() => { throw err; }).toThrowError('missing end event for frame capture');
async.done(); async.done();
}); });
@ -410,7 +410,7 @@ export function main() {
eventFactory.markStart('frameCapture', 4) eventFactory.markStart('frameCapture', 4)
], ],
{captureFrames: true}), {captureFrames: true}),
(err) => { (err): any => {
expect(() => { throw err; }) expect(() => { throw err; })
.toThrowError('can capture frames only once per benchmark run'); .toThrowError('can capture frames only once per benchmark run');
async.done(); async.done();
@ -424,12 +424,13 @@ export function main() {
.toThrowError( .toThrowError(
'found start event for frame capture, but frame capture was not requested in benchpress'); 'found start event for frame capture, but frame capture was not requested in benchpress');
async.done(); async.done();
return null;
}); });
})); }));
it('should throw if frame capture is enabled, but nothing is captured', it('should throw if frame capture is enabled, but nothing is captured',
inject([AsyncTestCompleter], (async) => { inject([AsyncTestCompleter], (async) => {
PromiseWrapper.catchError(aggregate([], {captureFrames: true}), (err) => { PromiseWrapper.catchError(aggregate([], {captureFrames: true}), (err): any => {
expect(() => { throw err; }) expect(() => { throw err; })
.toThrowError( .toThrowError(
'frame capture requested in benchpress, but no start event was found'); 'frame capture requested in benchpress, but no start event was found');

View File

@ -31,7 +31,7 @@ export function main() {
var injector: Injector; var injector: Injector;
var runner; var runner;
function createRunner(defaultBindings = null) { function createRunner(defaultBindings = null): Runner {
if (isBlank(defaultBindings)) { if (isBlank(defaultBindings)) {
defaultBindings = []; defaultBindings = [];
} }

View File

@ -31,7 +31,7 @@ export function main() {
var EMPTY_EXECUTE = () => {}; var EMPTY_EXECUTE = () => {};
describe('sampler', () => { describe('sampler', () => {
var sampler; var sampler: Sampler;
function createSampler({driver, metric, reporter, validator, prepare, execute}: { function createSampler({driver, metric, reporter, validator, prepare, execute}: {
driver?: any, driver?: any,

View File

@ -49,7 +49,7 @@ export function main() {
var normEvents = new TraceEventFactory('timeline', 'pid0'); var normEvents = new TraceEventFactory('timeline', 'pid0');
function createExtension(perfRecords = null, userAgent = null, function createExtension(perfRecords = null, userAgent = null,
messageMethod = 'Tracing.dataCollected') { messageMethod = 'Tracing.dataCollected'): WebDriverExtension {
if (isBlank(perfRecords)) { if (isBlank(perfRecords)) {
perfRecords = []; perfRecords = [];
} }
@ -85,7 +85,7 @@ export function main() {
it('should mark the timeline via console.timeEnd()', inject([AsyncTestCompleter], (async) => { it('should mark the timeline via console.timeEnd()', inject([AsyncTestCompleter], (async) => {
createExtension() createExtension()
.timeEnd('someName') .timeEnd('someName', null)
.then((_) => { .then((_) => {
expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]); expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]);
async.done(); async.done();
@ -467,7 +467,7 @@ export function main() {
benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats', benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats',
1100, {'data': {'frame_count': 2}}) 1100, {'data': {'frame_count': 2}})
]).readPerfLog(), ]).readPerfLog(),
(err) => { (err): any => {
expect(() => { throw err; }) expect(() => { throw err; })
.toThrowError('multi-frame render stats not supported'); .toThrowError('multi-frame render stats not supported');
async.done(); async.done();
@ -502,7 +502,7 @@ export function main() {
], ],
CHROME45_USER_AGENT, 'Tracing.bufferUsage') CHROME45_USER_AGENT, 'Tracing.bufferUsage')
.readPerfLog(), .readPerfLog(),
(err) => { (err): any => {
expect(() => { throw err; }) expect(() => { throw err; })
.toThrowError('The DevTools trace buffer filled during the test!'); .toThrowError('The DevTools trace buffer filled during the test!');
async.done(); async.done();

View File

@ -32,7 +32,7 @@ export function main() {
var normEvents = new TraceEventFactory('timeline', 'pid0'); var normEvents = new TraceEventFactory('timeline', 'pid0');
function createExtension(perfRecords = null) { function createExtension(perfRecords = null): WebDriverExtension {
if (isBlank(perfRecords)) { if (isBlank(perfRecords)) {
perfRecords = []; perfRecords = [];
} }
@ -61,7 +61,7 @@ export function main() {
it('should mark the timeline via console.timeEnd()', inject([AsyncTestCompleter], (async) => { it('should mark the timeline via console.timeEnd()', inject([AsyncTestCompleter], (async) => {
createExtension() createExtension()
.timeEnd('someName') .timeEnd('someName', null)
.then((_) => { .then((_) => {
expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]); expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]);
async.done(); async.done();

View File

@ -12,11 +12,12 @@ import {
import {Component, Directive, View, Host} from 'angular2/core'; import {Component, Directive, View, Host} from 'angular2/core';
import {RegExpWrapper, print, isPresent} from 'angular2/src/facade/lang'; import {RegExpWrapper, print, isPresent} from 'angular2/src/facade/lang';
import {AbstractControl} from 'angular2/common';
/** /**
* Custom validator. * Custom validator.
*/ */
function creditCardValidator(c): {[key: string]: boolean} { function creditCardValidator(c: AbstractControl): {[key: string]: boolean} {
if (isPresent(c.value) && RegExpWrapper.test(/^\d{16}$/g, c.value)) { if (isPresent(c.value) && RegExpWrapper.test(/^\d{16}$/g, c.value)) {
return null; return null;
} else { } else {

View File

@ -9,9 +9,9 @@ import {
RouteParams RouteParams
} from 'angular2/router'; } from 'angular2/router';
import * as db from './data'; import * as db from './data';
import {ObservableWrapper, PromiseWrapper} from 'angular2/src/facade/async'; import {PromiseWrapper} from 'angular2/src/facade/async';
import {ListWrapper} from 'angular2/src/facade/collection';
import {isPresent, DateWrapper} from 'angular2/src/facade/lang'; import {isPresent, DateWrapper} from 'angular2/src/facade/lang';
import {PromiseCompleter} from 'angular2/src/facade/promise';
class InboxRecord { class InboxRecord {
id: string = ''; id: string = '';
@ -60,31 +60,31 @@ class InboxRecord {
@Injectable() @Injectable()
class DbService { class DbService {
getData(): Promise<any[]> { getData(): Promise<any[]> {
var p = PromiseWrapper.completer(); var p = new PromiseCompleter<any[]>();
p.resolve(db.data); p.resolve(db.data);
return p.promise; return p.promise;
} }
drafts(): Promise<any[]> { drafts(): Promise<any[]> {
return PromiseWrapper.then(this.getData(), (data: any[]) => { return this.getData().then(
return data.filter(record => isPresent(record['draft']) && record['draft'] == true); (data: any[]): any[] =>
}); data.filter(record => isPresent(record['draft']) && record['draft'] == true));
} }
emails(): Promise<any[]> { emails(): Promise<any[]> {
return PromiseWrapper.then(this.getData(), (data: any[]) => { return this.getData().then((data: any[]): any[] =>
return data.filter(record => !isPresent(record['draft'])); data.filter(record => !isPresent(record['draft'])));
});
} }
email(id): Promise<any> { email(id): Promise<any> {
return PromiseWrapper.then(this.getData(), (data) => { return PromiseWrapper.then(this.getData(), (data: any[]) => {
for (var i = 0; i < data.length; i++) { for (var i = 0; i < data.length; i++) {
var entry = data[i]; var entry = data[i];
if (entry['id'] == id) { if (entry['id'] == id) {
return entry; return entry;
} }
} }
return null;
}); });
} }
} }
@ -109,13 +109,13 @@ class InboxCmp {
var sortType = params.get('sort'); var sortType = params.get('sort');
var sortEmailsByDate = isPresent(sortType) && sortType == "date"; var sortEmailsByDate = isPresent(sortType) && sortType == "date";
PromiseWrapper.then(db.emails(), emails => { PromiseWrapper.then(db.emails(), (emails: any[]) => {
this.ready = true; this.ready = true;
this.items = emails.map(data => new InboxRecord(data)); this.items = emails.map(data => new InboxRecord(data));
if (sortEmailsByDate) { if (sortEmailsByDate) {
ListWrapper.sort(this.items, this.items.sort((a: InboxRecord, b: InboxRecord) =>
(a, b) => DateWrapper.toMillis(DateWrapper.fromISOString(a.date)) < DateWrapper.toMillis(DateWrapper.fromISOString(a.date)) <
DateWrapper.toMillis(DateWrapper.fromISOString(b.date)) ? DateWrapper.toMillis(DateWrapper.fromISOString(b.date)) ?
-1 : -1 :
1); 1);
@ -131,7 +131,7 @@ class DraftsCmp {
ready: boolean = false; ready: boolean = false;
constructor(public router: Router, db: DbService) { constructor(public router: Router, db: DbService) {
PromiseWrapper.then(db.drafts(), (drafts) => { PromiseWrapper.then(db.drafts(), (drafts: any[]) => {
this.ready = true; this.ready = true;
this.items = drafts.map(data => new InboxRecord(data)); this.items = drafts.map(data => new InboxRecord(data));
}); });

View File

@ -8,7 +8,7 @@ import {Store, Todo, TodoFactory} from './services/TodoStore';
class TodoApp { class TodoApp {
todoEdit: Todo = null; todoEdit: Todo = null;
constructor(public todoStore: Store, public factory: TodoFactory) {} constructor(public todoStore: Store<Todo>, public factory: TodoFactory) {}
enterTodo(inputElement): void { enterTodo(inputElement): void {
this.addTodo(inputElement.value); this.addTodo(inputElement.value);

View File

@ -2,7 +2,7 @@ import {Injectable} from 'angular2/core';
import {ListWrapper, Predicate} from 'angular2/src/facade/collection'; import {ListWrapper, Predicate} from 'angular2/src/facade/collection';
// base model for RecordStore // base model for RecordStore
export class KeyModel { export abstract class KeyModel {
constructor(public key: number) {} constructor(public key: number) {}
} }
@ -23,19 +23,19 @@ export class TodoFactory {
// Store manages any generic item that inherits from KeyModel // Store manages any generic item that inherits from KeyModel
@Injectable() @Injectable()
export class Store { export class Store<T extends KeyModel> {
list: KeyModel[] = []; list: T[] = [];
add(record: KeyModel): void { this.list.push(record); } add(record: T): void { this.list.push(record); }
remove(record: KeyModel): void { this._spliceOut(record); } remove(record: T): void { this._spliceOut(record); }
removeBy(callback: Predicate<KeyModel>): void { removeBy(callback: Predicate<T>): void {
var records = this.list.filter(callback); var records = this.list.filter(callback);
ListWrapper.removeAll(this.list, records); ListWrapper.removeAll(this.list, records);
} }
private _spliceOut(record: KeyModel) { private _spliceOut(record: T) {
var i = this._indexFor(record); var i = this._indexFor(record);
if (i > -1) { if (i > -1) {
return ListWrapper.splice(this.list, i, 1)[0]; return ListWrapper.splice(this.list, i, 1)[0];
@ -43,5 +43,5 @@ export class Store {
return null; return null;
} }
private _indexFor(record: KeyModel) { return this.list.indexOf(record); } private _indexFor(record: T) { return this.list.indexOf(record); }
} }

View File

@ -225,7 +225,7 @@ class _CodegenState {
List<String> codes = []; List<String> codes = [];
_endOfBlockIdxs.clear(); _endOfBlockIdxs.clear();
ListWrapper.forEachWithIndex(eb.records, (_, i) { ListWrapper.forEachWithIndex(eb.records, (ProtoRecord _, int i) {
var code; var code;
var r = eb.records[i]; var r = eb.records[i];

View File

@ -1887,7 +1887,7 @@
"version": "4.0.1" "version": "4.0.1"
}, },
"dart-style": { "dart-style": {
"version": "0.2.6" "version": "0.2.7"
}, },
"dart2jsaas": { "dart2jsaas": {
"version": "0.0.16", "version": "0.0.16",
@ -5356,7 +5356,7 @@
} }
}, },
"ts2dart": { "ts2dart": {
"version": "0.7.24", "version": "0.7.31",
"dependencies": { "dependencies": {
"source-map": { "source-map": {
"version": "0.4.4" "version": "0.4.4"
@ -5839,5 +5839,5 @@
} }
}, },
"name": "angular-srcs", "name": "angular-srcs",
"version": "2.0.0-beta.6" "version": "2.0.0-beta.8"
} }

15
npm-shrinkwrap.json generated
View File

@ -1,6 +1,6 @@
{ {
"name": "angular-srcs", "name": "angular-srcs",
"version": "2.0.0-beta.6", "version": "2.0.0-beta.8",
"dependencies": { "dependencies": {
"abbrev": { "abbrev": {
"version": "1.0.7", "version": "1.0.7",
@ -2961,9 +2961,9 @@
"resolved": "https://registry.npmjs.org/dargs/-/dargs-4.0.1.tgz" "resolved": "https://registry.npmjs.org/dargs/-/dargs-4.0.1.tgz"
}, },
"dart-style": { "dart-style": {
"version": "0.2.6", "version": "0.2.7",
"from": "dart-style@>=0.2.6 <0.3.0", "from": "dart-style@>=0.2.6 <0.3.0",
"resolved": "https://registry.npmjs.org/dart-style/-/dart-style-0.2.6.tgz" "resolved": "https://registry.npmjs.org/dart-style/-/dart-style-0.2.7.tgz"
}, },
"dart2jsaas": { "dart2jsaas": {
"version": "0.0.16", "version": "0.0.16",
@ -8536,9 +8536,9 @@
} }
}, },
"ts2dart": { "ts2dart": {
"version": "0.7.24", "version": "0.7.31",
"from": "ts2dart@0.7.24", "from": "ts2dart@0.7.31",
"resolved": "https://registry.npmjs.org/ts2dart/-/ts2dart-0.7.24.tgz", "resolved": "https://registry.npmjs.org/ts2dart/-/ts2dart-0.7.31.tgz",
"dependencies": { "dependencies": {
"source-map": { "source-map": {
"version": "0.4.4", "version": "0.4.4",
@ -9310,7 +9310,8 @@
}, },
"zone.js": { "zone.js": {
"version": "0.5.15", "version": "0.5.15",
"from": "zone.js@0.5.15" "from": "zone.js@0.5.15",
"resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.5.15.tgz"
} }
} }
} }

View File

@ -112,7 +112,7 @@
"systemjs-builder": "^0.10.3", "systemjs-builder": "^0.10.3",
"through2": "^0.6.5", "through2": "^0.6.5",
"ts-api-guardian": "0.0.2", "ts-api-guardian": "0.0.2",
"ts2dart": "^0.7.22", "ts2dart": "^0.7.31",
"tsd": "^0.6.5-beta", "tsd": "^0.6.5-beta",
"tslint": "^3.2.1", "tslint": "^3.2.1",
"typescript": "^1.7.3", "typescript": "^1.7.3",

View File

@ -11,10 +11,10 @@ source $SCRIPT_DIR/env_dart.sh
cd $SCRIPT_DIR/../.. cd $SCRIPT_DIR/../..
# Variables # Variables
DDC_TOTAL_WARNING_CAP="1000" DDC_TOTAL_WARNING_CAP="210"
DDC_TOTAL_ERROR_CAP="11" DDC_TOTAL_ERROR_CAP="0"
DDC_DIR=`pwd`/tmp/dev_compiler DDC_DIR=`pwd`/tmp/dev_compiler
DDC_VERSION="0.1.14" DDC_VERSION="0.1.20"
# Get DDC # Get DDC
mkdir -p tmp mkdir -p tmp
@ -78,21 +78,27 @@ then
fi fi
cat $LOG_FILE cat $LOG_FILE
WARNING_COUNT=`cat $LOG_FILE | wc -l | sed -e 's/^[[:space:]]*//'` EXIT_CODE=0
# TODO remove `grep -v template.dart` after Tobias new compiler lands.
WARNING_COUNT=$(cat $LOG_FILE | grep -E '^warning.*' | grep -v template.dart | wc -l | sed -e 's/^[[:space:]]*//' || true)
ERROR_COUNT=$(cat $LOG_FILE | grep -E '^severe.*' | wc -l | sed -e 's/^[[:space:]]*//' || true)
if [[ "$ERROR_COUNT" -gt "$DDC_TOTAL_ERROR_CAP" ]]
then
echo "Found severe errors in angular2 package"
EXIT_CODE=1
fi
if [[ "$WARNING_COUNT" -gt "$DDC_TOTAL_WARNING_CAP" ]] if [[ "$WARNING_COUNT" -gt "$DDC_TOTAL_WARNING_CAP" ]]
then then
echo "Too many warnings: $WARNING_COUNT" echo "Too many warnings: $WARNING_COUNT"
exit 1 EXIT_CODE=1
else else
echo "Warning count ok" echo "Warning count ok"
fi fi
ERROR_COUNT=`cat $LOG_FILE | grep -E '^severe.*' | wc -l | sed -e 's/^[[:space:]]*//'`
if [[ "$ERROR_COUNT" -gt "$DDC_TOTAL_ERROR_CAP" ]]
then
echo "Found severe errors in angular2 package"
exit 1
fi
echo 'Dart DDC build finished' echo 'Dart DDC build finished'
exit $EXIT_CODE

View File

@ -66,12 +66,7 @@ if [[ -z $ENV_SET ]]; then
fi fi
fi fi
case "$PLATFORM" in export DART_SDK_LIB_SEARCH_PATH="$DART_SDK"
(Linux) export DART_SDK_LIB_SEARCH_PATH="$DART_SDK" ;;
(Darwin) export DART_SDK_LIB_SEARCH_PATH="$DART_SDK/libexec" ;;
(*) echo Unsupported platform $PLATFORM. Exiting ... >&2 ; exit 3 ;;
esac
export DART_SDK export DART_SDK
export DARTSDK export DARTSDK
export DART export DART

View File

@ -382,7 +382,7 @@ const CORE = [
'Reflector.isReflectionEnabled():boolean', 'Reflector.isReflectionEnabled():boolean',
'Reflector.listUnusedKeys():any[]', 'Reflector.listUnusedKeys():any[]',
'Reflector.method(name:string):MethodFn', 'Reflector.method(name:string):MethodFn',
'Reflector.parameters(typeOrFunc:any):any[]', 'Reflector.parameters(typeOrFunc:any):any[][]',
'Reflector.propMetadata(typeOrFunc:any):{[key:string]:any[]}', 'Reflector.propMetadata(typeOrFunc:any):{[key:string]:any[]}',
'Reflector.reflectionCapabilities:PlatformReflectionCapabilities', 'Reflector.reflectionCapabilities:PlatformReflectionCapabilities',
'Reflector.registerFunction(func:Function, funcInfo:ReflectionInfo):void', 'Reflector.registerFunction(func:Function, funcInfo:ReflectionInfo):void',
@ -555,7 +555,7 @@ const CORE = [
const COMMON = [ const COMMON = [
'AbstractControl', 'AbstractControl',
'AbstractControl.constructor(validator:Function, asyncValidator:Function)', 'AbstractControl.constructor(validator:ValidatorFn, asyncValidator:AsyncValidatorFn)',
'AbstractControl.dirty:boolean', 'AbstractControl.dirty:boolean',
'AbstractControl.errors:{[key:string]:any}', 'AbstractControl.errors:{[key:string]:any}',
'AbstractControl.find(path:Array<string|number>|string):AbstractControl', 'AbstractControl.find(path:Array<string|number>|string):AbstractControl',
@ -599,12 +599,12 @@ const COMMON = [
'CheckboxControlValueAccessor.registerOnTouched(fn:() => {}):void', 'CheckboxControlValueAccessor.registerOnTouched(fn:() => {}):void',
'CheckboxControlValueAccessor.writeValue(value:any):void', 'CheckboxControlValueAccessor.writeValue(value:any):void',
'Control', 'Control',
'Control.constructor(value:any, validator:Function, asyncValidator:Function)', 'Control.constructor(value:any, validator:ValidatorFn, asyncValidator:AsyncValidatorFn)',
'Control.registerOnChange(fn:Function):void', 'Control.registerOnChange(fn:Function):void',
'Control.updateValue(value:any, {onlySelf,emitEvent,emitModelToViewChange}:{onlySelf?:boolean, emitEvent?:boolean, emitModelToViewChange?:boolean}):void', 'Control.updateValue(value:any, {onlySelf,emitEvent,emitModelToViewChange}:{onlySelf?:boolean, emitEvent?:boolean, emitModelToViewChange?:boolean}):void',
'ControlArray', 'ControlArray',
'ControlArray.at(index:number):AbstractControl', 'ControlArray.at(index:number):AbstractControl',
'ControlArray.constructor(controls:AbstractControl[], validator:Function, asyncValidator:Function)', 'ControlArray.constructor(controls:AbstractControl[], validator:ValidatorFn, asyncValidator:AsyncValidatorFn)',
'ControlArray.insert(index:number, control:AbstractControl):void', 'ControlArray.insert(index:number, control:AbstractControl):void',
'ControlArray.length:number', 'ControlArray.length:number',
'ControlArray.push(control:AbstractControl):void', 'ControlArray.push(control:AbstractControl):void',
@ -615,7 +615,7 @@ const COMMON = [
'ControlContainer.path:string[]', 'ControlContainer.path:string[]',
'ControlGroup', 'ControlGroup',
'ControlGroup.addControl(name:string, control:AbstractControl):void', 'ControlGroup.addControl(name:string, control:AbstractControl):void',
'ControlGroup.constructor(controls:{[key:string]:AbstractControl}, optionals:{[key:string]:boolean}, validator:Function, asyncValidator:Function)', 'ControlGroup.constructor(controls:{[key:string]:AbstractControl}, optionals:{[key:string]:boolean}, validator:ValidatorFn, asyncValidator:AsyncValidatorFn)',
'ControlGroup.contains(controlName:string):boolean', 'ControlGroup.contains(controlName:string):boolean',
'ControlGroup.exclude(controlName:string):void', 'ControlGroup.exclude(controlName:string):void',
'ControlGroup.include(controlName:string):void', 'ControlGroup.include(controlName:string):void',
@ -647,8 +647,8 @@ const COMMON = [
'Form.removeControlGroup(dir:NgControlGroup):void', 'Form.removeControlGroup(dir:NgControlGroup):void',
'Form.updateModel(dir:NgControl, value:any):void', 'Form.updateModel(dir:NgControl, value:any):void',
'FormBuilder', 'FormBuilder',
'FormBuilder.array(controlsConfig:any[], validator:Function, asyncValidator:Function):ControlArray', 'FormBuilder.array(controlsConfig:any[], validator:ValidatorFn, asyncValidator:AsyncValidatorFn):ControlArray',
'FormBuilder.control(value:Object, validator:Function, asyncValidator:Function):Control', 'FormBuilder.control(value:Object, validator:ValidatorFn, asyncValidator:AsyncValidatorFn):Control',
'FormBuilder.group(controlsConfig:{[key:string]:any}, extra:{[key:string]:any}):ControlGroup', 'FormBuilder.group(controlsConfig:{[key:string]:any}, extra:{[key:string]:any}):ControlGroup',
'I18nPluralPipe', 'I18nPluralPipe',
'I18nPluralPipe.transform(value:number, args:any[]):string', 'I18nPluralPipe.transform(value:number, args:any[]):string',
@ -660,10 +660,10 @@ const COMMON = [
'LowerCasePipe.transform(value:string, args:any[]):string', 'LowerCasePipe.transform(value:string, args:any[]):string',
'MaxLengthValidator', 'MaxLengthValidator',
'MaxLengthValidator.constructor(maxLength:string)', 'MaxLengthValidator.constructor(maxLength:string)',
'MaxLengthValidator.validate(c:Control):{[key:string]:any}', 'MaxLengthValidator.validate(c:AbstractControl):{[key:string]:any}',
'MinLengthValidator', 'MinLengthValidator',
'MinLengthValidator.constructor(minLength:string)', 'MinLengthValidator.constructor(minLength:string)',
'MinLengthValidator.validate(c:Control):{[key:string]:any}', 'MinLengthValidator.validate(c:AbstractControl):{[key:string]:any}',
'NgClass', 'NgClass',
'NgClass.constructor(_iterableDiffers:IterableDiffers, _keyValueDiffers:KeyValueDiffers, _ngEl:ElementRef, _renderer:Renderer)', 'NgClass.constructor(_iterableDiffers:IterableDiffers, _keyValueDiffers:KeyValueDiffers, _ngEl:ElementRef, _renderer:Renderer)',
'NgClass.initialClasses=(v:string)', 'NgClass.initialClasses=(v:string)',
@ -671,22 +671,22 @@ const COMMON = [
'NgClass.ngOnDestroy():void', 'NgClass.ngOnDestroy():void',
'NgClass.rawClass=(v:string|string[]|Set<string>|{[key:string]:any})', 'NgClass.rawClass=(v:string|string[]|Set<string>|{[key:string]:any})',
'NgControl', 'NgControl',
'NgControl.asyncValidator:Function', 'NgControl.asyncValidator:AsyncValidatorFn',
'NgControl.name:string', 'NgControl.name:string',
'NgControl.validator:Function', 'NgControl.validator:ValidatorFn',
'NgControl.valueAccessor:ControlValueAccessor', 'NgControl.valueAccessor:ControlValueAccessor',
'NgControl.viewToModelUpdate(newValue:any):void', 'NgControl.viewToModelUpdate(newValue:any):void',
'NgControlGroup', 'NgControlGroup',
'NgControlGroup.asyncValidator:Function', 'NgControlGroup.asyncValidator:AsyncValidatorFn',
'NgControlGroup.constructor(parent:ControlContainer, _validators:any[], _asyncValidators:any[])', 'NgControlGroup.constructor(parent:ControlContainer, _validators:any[], _asyncValidators:any[])',
'NgControlGroup.control:ControlGroup', 'NgControlGroup.control:ControlGroup',
'NgControlGroup.formDirective:Form', 'NgControlGroup.formDirective:Form',
'NgControlGroup.ngOnDestroy():void', 'NgControlGroup.ngOnDestroy():void',
'NgControlGroup.ngOnInit():void', 'NgControlGroup.ngOnInit():void',
'NgControlGroup.path:string[]', 'NgControlGroup.path:string[]',
'NgControlGroup.validator:Function', 'NgControlGroup.validator:ValidatorFn',
'NgControlName', 'NgControlName',
'NgControlName.asyncValidator:Function', 'NgControlName.asyncValidator:AsyncValidatorFn',
'NgControlName.constructor(_parent:ControlContainer, _validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])', 'NgControlName.constructor(_parent:ControlContainer, _validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])',
'NgControlName.control:Control', 'NgControlName.control:Control',
'NgControlName.formDirective:any', 'NgControlName.formDirective:any',
@ -695,7 +695,7 @@ const COMMON = [
'NgControlName.ngOnDestroy():void', 'NgControlName.ngOnDestroy():void',
'NgControlName.path:string[]', 'NgControlName.path:string[]',
'NgControlName.update:any', 'NgControlName.update:any',
'NgControlName.validator:Function', 'NgControlName.validator:ValidatorFn',
'NgControlName.viewModel:any', 'NgControlName.viewModel:any',
'NgControlName.viewToModelUpdate(newValue:any):void', 'NgControlName.viewToModelUpdate(newValue:any):void',
'NgControlStatus', 'NgControlStatus',
@ -729,7 +729,7 @@ const COMMON = [
'NgForm.removeControlGroup(dir:NgControlGroup):void', 'NgForm.removeControlGroup(dir:NgControlGroup):void',
'NgForm.updateModel(dir:NgControl, value:any):void', 'NgForm.updateModel(dir:NgControl, value:any):void',
'NgFormControl', 'NgFormControl',
'NgFormControl.asyncValidator:Function', 'NgFormControl.asyncValidator:AsyncValidatorFn',
'NgFormControl.constructor(_validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])', 'NgFormControl.constructor(_validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])',
'NgFormControl.control:Control', 'NgFormControl.control:Control',
'NgFormControl.form:Control', 'NgFormControl.form:Control',
@ -737,7 +737,7 @@ const COMMON = [
'NgFormControl.ngOnChanges(changes:{[key:string]:SimpleChange}):void', 'NgFormControl.ngOnChanges(changes:{[key:string]:SimpleChange}):void',
'NgFormControl.path:string[]', 'NgFormControl.path:string[]',
'NgFormControl.update:any', 'NgFormControl.update:any',
'NgFormControl.validator:Function', 'NgFormControl.validator:ValidatorFn',
'NgFormControl.viewModel:any', 'NgFormControl.viewModel:any',
'NgFormControl.viewToModelUpdate(newValue:any):void', 'NgFormControl.viewToModelUpdate(newValue:any):void',
'NgFormModel', 'NgFormModel',
@ -761,14 +761,14 @@ const COMMON = [
'NgIf.constructor(_viewContainer:ViewContainerRef, _templateRef:TemplateRef)', 'NgIf.constructor(_viewContainer:ViewContainerRef, _templateRef:TemplateRef)',
'NgIf.ngIf=(newCondition:any)', 'NgIf.ngIf=(newCondition:any)',
'NgModel', 'NgModel',
'NgModel.asyncValidator:Function', 'NgModel.asyncValidator:AsyncValidatorFn',
'NgModel.constructor(_validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])', 'NgModel.constructor(_validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])',
'NgModel.control:Control', 'NgModel.control:Control',
'NgModel.model:any', 'NgModel.model:any',
'NgModel.ngOnChanges(changes:{[key:string]:SimpleChange}):any', 'NgModel.ngOnChanges(changes:{[key:string]:SimpleChange}):any',
'NgModel.path:string[]', 'NgModel.path:string[]',
'NgModel.update:any', 'NgModel.update:any',
'NgModel.validator:Function', 'NgModel.validator:ValidatorFn',
'NgModel.viewModel:any', 'NgModel.viewModel:any',
'NgModel.viewToModelUpdate(newValue:any):void', 'NgModel.viewToModelUpdate(newValue:any):void',
'NgSelectOption', 'NgSelectOption',
@ -786,7 +786,7 @@ const COMMON = [
'NumberPipe', 'NumberPipe',
'PatternValidator', 'PatternValidator',
'PatternValidator.constructor(pattern:string)', 'PatternValidator.constructor(pattern:string)',
'PatternValidator.validate(c:Control):{[key:string]:any}', 'PatternValidator.validate(c:AbstractControl):{[key:string]:any}',
'PercentPipe', 'PercentPipe',
'PercentPipe.transform(value:any, args:any[]):string', 'PercentPipe.transform(value:any, args:any[]):string',
'ReplacePipe', 'ReplacePipe',
@ -805,15 +805,15 @@ const COMMON = [
'UpperCasePipe', 'UpperCasePipe',
'UpperCasePipe.transform(value:string, args:any[]):string', 'UpperCasePipe.transform(value:string, args:any[]):string',
'Validator', 'Validator',
'Validator.validate(c:Control):{[key:string]:any}', 'Validator.validate(c:AbstractControl):{[key:string]:any}',
'Validators', 'Validators',
'Validators.compose(validators:Function[]):Function', 'Validators.compose(validators:ValidatorFn[]):ValidatorFn',
'Validators.composeAsync(validators:Function[]):Function', 'Validators.composeAsync(validators:AsyncValidatorFn[]):AsyncValidatorFn',
'Validators.maxLength(maxLength:number):Function', 'Validators.maxLength(maxLength:number):ValidatorFn',
'Validators.minLength(minLength:number):Function', 'Validators.minLength(minLength:number):ValidatorFn',
'Validators.nullValidator(c:any):{[key:string]:boolean}', 'Validators.nullValidator(c:AbstractControl):{[key:string]:boolean}',
'Validators.pattern(pattern:string):Function', 'Validators.pattern(pattern:string):ValidatorFn',
'Validators.required(control:Control):{[key:string]:boolean}', 'Validators.required(control:AbstractControl):{[key:string]:boolean}',
'RadioButtonState', 'RadioButtonState',
'RadioButtonState.constructor(checked:boolean, value:string)', 'RadioButtonState.constructor(checked:boolean, value:string)',
'const COMMON_DIRECTIVES:Type[][]', 'const COMMON_DIRECTIVES:Type[][]',