Merge branch 'master' into revert-3492-react-reactcomponent-type-insteadof-instance

This commit is contained in:
Vincent Siao
2015-01-23 17:50:44 -08:00
7 changed files with 919 additions and 649 deletions
+9
View File
@@ -0,0 +1,9 @@
/// <reference path="animation-frame.d.ts"/>
module AnimationFrameTests {
var animation = new AnimationFrame();
function frame() {
animation.request(frame);
}
animation.request(frame);
}
+12
View File
@@ -0,0 +1,12 @@
// Type definitions for animation-frame 0.1.7
// Project: https://github.com/kof/animation-frame
// Definitions by: Qinfeng Chen <https://github.com/qinfchen>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface AnimationFrame {
new(): AnimationFrame;
request(callback: () => void): void;
}
declare var AnimationFrame: AnimationFrame;
+79 -84
View File
@@ -1,8 +1,3 @@
// Type definitions for Breeze 1.4.1
// Project: http://www.breezejs.com/
// Definitions by: IdeaBlade <https://github.com/IdeaBlade/Breeze/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="breeze.d.ts" />
import core = breeze.core;
@@ -50,9 +45,9 @@ function test_entityAspect() {
var orderDateErrors = order.entityAspect.getValidationErrors("OrderDate");
var orderDateProperty = order.entityType.getProperty("OrderDate");
var orderDateErrors = order.entityAspect.getValidationErrors(orderDateProperty);
order.entityAspect.loadNavigationProperty("Orders").then(function (data) {
order.entityAspect.loadNavigationProperty("Orders").then(function (data: breeze.QueryResult) {
var orders = data.results;
}).fail(function (exception) { });
}).catch(function (exception) { });
order.entityAspect.rejectChanges();
order.entityAspect.setDeleted();
order.entityAspect.setModified();
@@ -109,7 +104,7 @@ function test_metadataStore() {
var ms = new breeze.MetadataStore();
ms.fetchMetadata("breeze/NorthwindIBModel")
.then(function (rawMetadata) { })
.fail(function (exception) { });
.catch(function (exception) { });
var odType = em1.metadataStore.getEntityType("OrderDetail");
var badType = em1.metadataStore.getEntityType("Foo", false);
var allTypes = em1.metadataStore.getEntityTypes();
@@ -172,14 +167,14 @@ function test_entityManager() {
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders");
em.executeQuery(query)
.then(function (data) {
.then(function (data: breeze.QueryResult) {
var orders = data.results;
}).fail(function (err) {
}).catch(function (err) {
});
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders");
em.executeQuery(query,
function (data) {
function (data: breeze.QueryResult) {
var orders = data.results;
},
function (err) {
@@ -187,9 +182,9 @@ function test_entityManager() {
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders").using(em);
query.execute()
.then(function (data) {
.then(function (data: breeze.QueryResult) {
var orders = data.results;
}).fail(function (err) {
}).catch(function (err) {
});
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders");
@@ -197,9 +192,9 @@ function test_entityManager() {
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders").using(breeze.FetchStrategy.FromLocalCache);
em.executeQuery(query)
.then(function (data) {
.then(function (data: breeze.QueryResult) {
var orders = data.results;
}).fail(function (err) {
}).catch(function (err) {
});
var bundle = em1.exportEntities();
window.localStorage.setItem("myEntityManager", bundle);
@@ -217,7 +212,7 @@ function test_entityManager() {
.then(function () {
var metadataStore = em1.metadataStore;
})
.fail(function (exception) {
.catch(function (exception) {
});
var employeeType = em1.metadataStore.getEntityType("Employee");
var employeeKey = new breeze.EntityKey(<breeze.EntityType> employeeType, 1);
@@ -228,7 +223,7 @@ function test_entityManager() {
var custumer = custType.createEntity();
var customerId = em.generateTempKeyValue(custumer);
em1.saveChanges()
.then(function (data) {
.then(function (data: breeze.SaveResult) {
var sameCust1 = data.entities[0];
});
var changedEntities = em1.getChanges();
@@ -263,22 +258,22 @@ function test_entityManager() {
metadataStore: em1.metadataStore
});
em2.importEntities(bundle);
var bundle = em1.exportEntities();
em2.importEntities(bundle, { mergeStrategy: breeze.MergeStrategy.PreserveChanges });
em.saveChanges().then(function (saveResult) {
var bundle2 = em1.exportEntities(null, { asString: true, includeMetadata: true });
em2.importEntities(bundle2, { mergeStrategy: breeze.MergeStrategy.PreserveChanges });
em.saveChanges().then(function (saveResult: breeze.SaveResult) {
var savedEntities = saveResult.entities;
var keyMappings = saveResult.keyMappings;
}).fail(function (e) {
}).catch(function (e) {
});
var saveOptions = new breeze.SaveOptions({ allowConcurrentSaves: true });
var entitiesToSave: breeze.Entity[];
em.saveChanges(entitiesToSave, saveOptions).then(function (saveResult) {
em.saveChanges(entitiesToSave, saveOptions).then(function (saveResult: breeze.SaveResult) {
var savedEntities = saveResult.entities;
var keyMappings = saveResult.keyMappings;
}).fail(function (e) {
}).catch(function (e) {
});
em.saveChanges(entitiesToSave, null,
function (saveResult) {
function (saveResult: breeze.SaveResult) {
var savedEntities = saveResult.entities;
var keyMappings = saveResult.keyMappings;
}, function (e) { }
@@ -307,21 +302,21 @@ function test_entityQuery() {
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders").using(em);
query.execute()
.then(function (data) { })
.fail(function (err) { });
.then(function (data: breeze.QueryResult) { })
.catch(function (err) { });
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders").using(em);
query.execute(
function (data) {
function (data: breeze.QueryResult) {
var orders = data.results;
},
function (err) { });
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders");
em.executeQuery(query)
.then(function (data) {
.then(function (data: breeze.QueryResult) {
var orders = data.results;
}).fail(function (err) {
}).catch(function (err) {
});
var query = new breeze.EntityQuery("Orders").using(em);
var orders = query.executeLocally();
@@ -409,6 +404,8 @@ function test_entityQuery() {
var query = new breeze.EntityQuery("Customers")
.where("toUpper(substring(CompanyName, 1, 2))", breeze.FilterQueryOp.Equals, "OM");
var q2 = query.toType("foo").orderBy("foo2");
var json = query.toJSON();
}
function test_entityState() {
@@ -487,55 +484,53 @@ function test_entityType() {
}
//function test_enum() {
// var prototype = {
// nextDay: function () {
// var nextIndex = (this.dayIndex + 1) % 7;
// return DayOfWeek.getSymbols()[nextIndex];
// }
// };
// var DayOfWeek = new core.Enum("DayOfWeek", prototype);
// DayOfWeek.Monday = DayOfWeek.addSymbol({ dayIndex: 0 });
// var symbol = DayOfWeek.Friday;
// if (DayOfWeek.contains(symbol)) { }
// var dayOfWeek = DayOfWeek.from("Thursday");
// var symbols = DayOfWeek.getNames();
// var symbols = DayOfWeek.getSymbols();
// if (core.Enum.isSymbol(DayOfWeek.Wednesday)) { };
// DayOfWeek.seal();
// var name = DayOfWeek.Monday.getName();
// var name = DayOfWeek.Monday.toString();
// var prototype = {
// nextDay: function () {
// var nextIndex = (this.dayIndex + 1) % 7;
// return DayOfWeek.getSymbols()[nextIndex];
// }
// };
// var DayOfWeek = new core.Enum("DayOfWeek", prototype);
// DayOfWeek.Monday = DayOfWeek.addSymbol({ dayIndex: 0 });
// var symbol = DayOfWeek.Friday;
// if (DayOfWeek.contains(symbol)) { }
// var dayOfWeek = DayOfWeek.from("Thursday");
// var symbols = DayOfWeek.getNames();
// var symbols = DayOfWeek.getSymbols();
// if (core.Enum.isSymbol(DayOfWeek.Wednesday)) { };
// DayOfWeek.seal();
// var name = DayOfWeek.Monday.getName();
// var name = DayOfWeek.Monday.toString();
// var prototype = {
// nextDay: function () {
// var nextIndex = (this.dayIndex + 1) % 7;
// return DayOfWeek.getSymbols()[nextIndex];
// }
// };
// var DayOfWeek = new core.Enum("DayOfWeek", prototype);
// DayOfWeek.Monday = DayOfWeek.addSymbol({ dayIndex: 0 });
// DayOfWeek.Tuesday = DayOfWeek.addSymbol({ dayIndex: 1 });
// DayOfWeek.Wednesday = DayOfWeek.addSymbol({ dayIndex: 2 });
// DayOfWeek.Thursday = DayOfWeek.addSymbol({ dayIndex: 3 });
// DayOfWeek.Friday = DayOfWeek.addSymbol({ dayIndex: 4 });
// DayOfWeek.Saturday = DayOfWeek.addSymbol({ dayIndex: 5, isWeekend: true });
// DayOfWeek.Sunday = DayOfWeek.addSymbol({ dayIndex: 6, isWeekend: true });
// DayOfWeek.seal();
// DayOfWeek.Monday.nextDay() === DayOfWeek.Tuesday;
// DayOfWeek.Sunday.nextDay() === DayOfWeek.Monday;
// DayOfWeek.Tuesday.isWeekend === undefined;
// DayOfWeek.Saturday.isWeekend == true;
// DayOfWeek instanceof core.Enum;
// core.Enum.isSymbol(DayOfWeek.Wednesday);
// DayOfWeek.contains(DayOfWeek.Thursday);
// DayOfWeek.Tuesday.parentEnum == DayOfWeek;
// DayOfWeek.getSymbols().length === 7;
// DayOfWeek.Friday.toString() === "Friday";
// var prototype = {
// nextDay: function () {
// var nextIndex = (this.dayIndex + 1) % 7;
// return DayOfWeek.getSymbols()[nextIndex];
// }
// };
// var DayOfWeek = new core.Enum("DayOfWeek", prototype);
// DayOfWeek.Monday = DayOfWeek.addSymbol({ dayIndex: 0 });
// DayOfWeek.Tuesday = DayOfWeek.addSymbol({ dayIndex: 1 });
// DayOfWeek.Wednesday = DayOfWeek.addSymbol({ dayIndex: 2 });
// DayOfWeek.Thursday = DayOfWeek.addSymbol({ dayIndex: 3 });
// DayOfWeek.Friday = DayOfWeek.addSymbol({ dayIndex: 4 });
// DayOfWeek.Saturday = DayOfWeek.addSymbol({ dayIndex: 5, isWeekend: true });
// DayOfWeek.Sunday = DayOfWeek.addSymbol({ dayIndex: 6, isWeekend: true });
// DayOfWeek.seal();
// DayOfWeek.Monday.nextDay() === DayOfWeek.Tuesday;
// DayOfWeek.Sunday.nextDay() === DayOfWeek.Monday;
// DayOfWeek.Tuesday.isWeekend === undefined;
// DayOfWeek.Saturday.isWeekend == true;
// DayOfWeek instanceof core.Enum;
// core.Enum.isSymbol(DayOfWeek.Wednesday);
// DayOfWeek.contains(DayOfWeek.Thursday);
// DayOfWeek.Tuesday.parentEnum == DayOfWeek;
// DayOfWeek.getSymbols().length === 7;
// DayOfWeek.Friday.toString() === "Friday";
//}
interface CustomEntityManager extends breeze.EntityManager
{
customTag: string;
interface CustomEntityManager extends breeze.EntityManager {
customTag: string;
}
function test_event() {
@@ -699,14 +694,12 @@ function test_validationOptions() {
var newOptions = validationOptions.using({ validateOnQuery: true, validateOnSave: false });
}
interface NumericRange
{
max: number;
interface NumericRange{
max: number;
min: number;
}
interface NumericRangeValidatorFunctionContext extends breeze.ValidatorFunctionContext, NumericRange
{
interface NumericRangeValidatorFunctionContext extends breeze.ValidatorFunctionContext, NumericRange {
}
function test_validator() {
@@ -726,7 +719,7 @@ function test_validator() {
var re = /^\d{5}([\-]\d{4})?$/;
return (re.test(value));
}
valFn = function (v: any) {
var valFn = function (v: any) {
if (v.getProperty("Country") === "USA") {
var postalCode = v.getProperty("PostalCode");
return isValidZipCode(postalCode);
@@ -799,7 +792,7 @@ function test_validator() {
var errMsg = result.errorMessage;
var context = result.context;
var sameValidator = result.validator;
valFn = function (v: any) {
var valFn = function (v: any) {
if (v == null) return true;
return (v.substr(0,2) === "US");
};
@@ -808,6 +801,8 @@ function test_validator() {
breeze.Validator.register(countryValidator);
breeze.Validator.registerFactory(() => countryValidator, "country");
var urlValidator = breeze.Validator.url({ messageTemplate: 'u got that wrong' });
}
function test_demo() {
@@ -817,7 +812,7 @@ function test_demo() {
var query = new breeze.EntityQuery()
.from("Employees");
manager.executeQuery(query).then(function (data) { });
manager.executeQuery(query).then(function (data: breeze.QueryResult) { });
}
function test_corefns() {
@@ -888,4 +883,4 @@ function test_config() {
config.registerType(f1, "myCtor");
s = config.stringifyPad;
o = config.typeRegistry;
}
}
+284 -102
View File
@@ -4,10 +4,12 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Updated Jan 14 2011 - Jay Traband ( www.ideablade.com).
// Updated March 27 2013 - John Lantz (www.ideablade.com).
// Updated Aug 13 2013 - Steve Schmitt ( www.ideablade.com).
/// <reference path="../q/Q.d.ts" />
// Updated Sep 26 2013 for Breeze 1.4.3 - Steve Schmitt ( www.ideablade.com).
// Updated Jul 22 2014 for Breeze 1.4.16 - Steve Schmitt ( www.ideablade.com)
// Updated Aug 22 2014 for Breeze 1.4.17 and removing Q dependency - Steve Schmitt ( www.ideablade.com)
// Updated Jan 16 2015 for Breeze 1.4.17 to add support for noimplicitany - Kevin Wilson ( www.kwilson.me.uk )
// Updated Jan 20 2015 for Breeze 1.5.2 and merging changes from DefinitelyTyped
declare module breeze.core {
@@ -23,7 +25,7 @@ declare module breeze.core {
}
class Enum implements IEnum {
constructor (name: string, methodObj?: any);
constructor(name: string, methodObj?: any);
addSymbol(propertiesObj?: any): EnumSymbol;
contains(object: any): boolean;
@@ -31,7 +33,7 @@ declare module breeze.core {
getNames(): string[];
getSymbols(): EnumSymbol[];
static isSymbol(object: any): boolean;
seal(): void;
resolveSymbols(): void;
}
class EnumSymbol {
@@ -42,7 +44,7 @@ declare module breeze.core {
}
class Event {
constructor (name: string, publisher: any, defaultErrorCallback?: ErrorCallback);
constructor(name: string, publisher: any, defaultErrorCallback?: ErrorCallback);
static enable(eventName: string, target: any): void;
static enable(eventName: string, target: any, isEnabled: boolean): void;
@@ -51,25 +53,26 @@ declare module breeze.core {
static isEnabled(eventName: string, target: any): boolean;
publish(data: any, publishAsync?: boolean, errorCallback?: ErrorCallback): void;
publishAsync(data: any, errorCallback?: ErrorCallback): void;
subscribe(callback?: (data: any) => void ): number;
subscribe(callback?: (data: any) => void): number;
unsubscribe(unsubKey: number): boolean;
clear(): void;
}
export function objectForEach(obj: Object, kvfn: (key:string, value:any) => void): void;
export function objectForEach(obj: Object, kvfn: (key: string, value: any) => void): void;
export function extend(target: Object, source: Object): Object;
export function propEq(propertyName: string, value: any): (obj: Object) => boolean;
export function pluck(propertyName: string): (obj: Object) => any;
export function arrayEquals(a1: any[], a2: any[], equalsFn: (e1:any, e2:any) => boolean): boolean;
export function arrayFirst(a1: any[], predicate: (e:any) => boolean): any;
export function arrayEquals(a1: any[], a2: any[], equalsFn: (e1: any, e2: any) => boolean): boolean;
export function arrayFirst(a1: any[], predicate: (e: any) => boolean): any;
export function arrayIndexOf(a1: any[], predicate: (e: any) => boolean): number;
export function arrayRemoveItem(array: any[], item: any, shouldRemoveMultiple: boolean): any;
export function arrayRemoveItem(array: any[], predicate: (e: any) => boolean, shouldRemoveMultiple: boolean): any;
export function arrayZip(a1: any[], a2: any[], callback: (e1:any, e2:any) => any): any[];
export function arrayZip(a1: any[], a2: any[], callback: (e1: any, e2: any) => any): any[];
export function requireLib(libnames: string, errMessage: string): Object;
export function using(obj: Object, property: string, tempValue: any, fn: () => any): any;
export function memoize(fn:Function): any;
export function memoize(fn: (...any: any[]) => any): any;
export function getUuid(): string;
export function durationToSeconds(duration: string): number;
@@ -147,7 +150,6 @@ declare module breeze {
concurrencyMode: string;
dataType: DataTypeSymbol;
defaultValue: any;
fixedLength: boolean;
isComplexProperty: boolean;
isDataProperty: boolean;
isInherited: boolean;
@@ -155,24 +157,26 @@ declare module breeze {
isNullable: boolean;
isPartOfKey: boolean;
isUnmapped: boolean;
maxLength: number;
name: string;
nameOnServer: string;
parentType: IStructuralType;
relatedNavigationProperty: NavigationProperty;
validators: Validator[];
constructor (config: DataPropertyOptions);
constructor(config: DataPropertyOptions);
}
interface DataPropertyOptions {
complexTypeName?: string;
concurrencyMode?: string;
custom?: any;
dataType?: DataTypeSymbol;
defaultValue?: any;
fixedLength?: boolean;
displayName?: string;
isNullable?: boolean;
isPartOfKey?: boolean;
isScalar?: boolean;
isUnmapped?: boolean;
maxLength?: number;
name?: string;
@@ -185,6 +189,7 @@ declare module breeze {
adapterName: string;
hasServerMetadata: boolean;
serviceName: string;
uriBuilderName: string;
jsonResultsAdapter: JsonResultsAdapter;
useJsonp: boolean;
constructor(config: DataServiceOptions);
@@ -194,17 +199,18 @@ declare module breeze {
interface DataServiceOptions {
serviceName?: string;
adapterName?: string;
uriBuilderName?: string;
hasServerMetadata?: boolean;
jsonResultsAdapter?: JsonResultsAdapter;
useJsonp?: boolean;
}
class DataServiceAdapter {
checkForRecomposition(interfaceInitializedArgs: { interfaceName: string; isDefault: boolean}): void;
checkForRecomposition(interfaceInitializedArgs: { interfaceName: string; isDefault: boolean }): void;
initialize(): void;
fetchMetadata(metadataStore: MetadataStore, dataService: DataService): Q.Promise<any>;
executeQuery(mappingContext: Object): Q.Promise<any>;
saveChanges(saveContext: { resourceName: string }, saveBundle: Object): Q.Promise<SaveResult>;
fetchMetadata(metadataStore: MetadataStore, dataService: DataService): breeze.promises.IPromise<any>;
executeQuery(mappingContext: { getUrl: () => string; query: EntityQuery; dataService: DataService }): breeze.promises.IPromise<any>;
saveChanges(saveContext: { resourceName: string; dataService: DataService }, saveBundle: Object): breeze.promises.IPromise<SaveResult>;
JsonResultsAdapter: JsonResultsAdapter;
}
@@ -232,9 +238,9 @@ declare module breeze {
}
class DataTypeSymbol extends breeze.core.EnumSymbol {
defaultValue: any;
isNumeric: boolean;
isDate: boolean;
defaultValue: any;
isNumeric: boolean;
isDate: boolean;
}
interface DataType extends breeze.core.IEnum {
Binary: DataTypeSymbol;
@@ -283,6 +289,7 @@ declare module breeze {
entityState: EntityStateSymbol;
isBeingSaved: boolean;
originalValues: Object;
extraMetadata: Object;
propertyChanged: PropertyChangedEvent;
validationErrorsChanged: ValidationErrorsChangedEvent;
@@ -299,8 +306,9 @@ declare module breeze {
isNavigationPropertyLoaded(navigationProperty: string): boolean;
isNavigationPropertyLoaded(navigationProperty: NavigationProperty): boolean;
loadNavigationProperty(navigationProperty: string, callback?: Function, errorCallback?: Function): Q.Promise<QueryResult>;
loadNavigationProperty(navigationProperty: NavigationProperty, callback?: Function, errorCallback?: Function): Q.Promise<QueryResult>;
loadNavigationProperty(navigationProperty: string, callback?: Function, errorCallback?: Function): breeze.promises.IPromise<QueryResult>;
loadNavigationProperty(navigationProperty: NavigationProperty, callback?: Function, errorCallback?: Function): breeze.promises.IPromise<QueryResult>;
rejectChanges(): void;
@@ -309,10 +317,14 @@ declare module breeze {
removeValidationError(validator: Validator, property: NavigationProperty): void;
removeValidationError(validationError: ValidationError): void;
/** Sets the entity to an EntityState of 'Added'. This is NOT the equivalent of calling {{#crossLink "EntityManager/addEntity"}}{{/crossLink}}
because no key generation will occur for autogenerated keys as a result of this operation. */
setAdded(): void;
setDeleted(): void;
setDetached(): void;
setModified(): void;
setUnchanged(): void;
setEntityState(entityState: EntityStateSymbol): void;
validateEntity(): boolean;
validateProperty(property: string, context?: any): boolean;
@@ -322,13 +334,15 @@ declare module breeze {
class PropertyChangedEventArgs {
entity: Entity;
property: IProperty;
propertyName: string;
oldValue: any;
newValue: any;
parent: any;
}
class PropertyChangedEvent extends breeze.core.Event {
subscribe(callback?: (data: PropertyChangedEventArgs) => void ): number;
subscribe(callback?: (data: PropertyChangedEventArgs) => void): number;
}
class ValidationErrorsChangedEventArgs {
@@ -338,12 +352,12 @@ declare module breeze {
}
class ValidationErrorsChangedEvent extends breeze.core.Event {
subscribe(callback?: (data: ValidationErrorsChangedEventArgs) => void ): number;
subscribe(callback?: (data: ValidationErrorsChangedEventArgs) => void): number;
}
class EntityKey {
constructor (entityType: EntityType, keyValue: any);
constructor (entityType: EntityType, keyValues: any[]);
constructor(entityType: EntityType, keyValue: any);
constructor(entityType: EntityType, keyValues: any[]);
equals(entityKey: EntityKey): boolean;
static equals(k1: EntityKey, k2: EntityKey): boolean;
@@ -356,6 +370,10 @@ declare module breeze {
entityKey: EntityKey;
fromCache: boolean;
}
interface ExportEntitiesOptions {
asString: boolean; // default true
includeMetadata: boolean; // default true
}
class EntityManager {
dataService: DataService;
@@ -370,26 +388,26 @@ declare module breeze {
hasChangesChanged: HasChangesChangedEvent;
validationErrorsChanged: ValidationErrorsChangedEvent;
constructor (config?: EntityManagerOptions);
constructor (config?: string);
constructor(config?: EntityManagerOptions);
constructor(config?: string);
addEntity(entity: Entity): Entity;
attachEntity(entity: Entity, entityState?: EntityStateSymbol): Entity;
attachEntity(entity: Entity, entityState?: EntityStateSymbol, mergeStrategy?: MergeStrategySymbol): Entity;
clear(): void;
createEmptyCopy(): EntityManager;
createEntity(typeName: string, config?: {}, entityState?: EntityStateSymbol) : Entity;
createEntity(typeName: string, config?: {}, entityState?: EntityStateSymbol, mergeStrategy?: StrategySymbol): Entity;
createEntity(entityType: EntityType, config?: {}, entityState?: EntityStateSymbol): Entity;
createEntity(typeName: string, config?: {}, entityState?: EntityStateSymbol, mergeStrategy?: MergeStrategySymbol): Entity;
createEntity(entityType: EntityType, config?: {}, entityState?: EntityStateSymbol, mergeStrategy?: MergeStrategySymbol): Entity;
detachEntity(entity: Entity): boolean;
executeQuery(query: string, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Q.Promise<QueryResult>;
executeQuery(query: EntityQuery, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Q.Promise<QueryResult>;
executeQuery(query: string, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): breeze.promises.IPromise<QueryResult>;
executeQuery(query: EntityQuery, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): breeze.promises.IPromise<QueryResult>;
executeQueryLocally(query: EntityQuery): Entity[];
exportEntities(entities?: Entity[], includeMetadata?: boolean): string;
fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: boolean): Q.Promise<EntityByKeyResult>;
fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: boolean): Q.Promise<EntityByKeyResult>;
fetchEntityByKey(entityKey: EntityKey, checkLocalCacheFirst?: boolean): Q.Promise<EntityByKeyResult>;
fetchMetadata(callback?: (schema: any) => void , errorCallback?: breeze.core.ErrorCallback): Q.Promise<any>;
exportEntities(entities?: Entity[], options?: ExportEntitiesOptions): any; // string | Object
fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: boolean): breeze.promises.IPromise<EntityByKeyResult>;
fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: boolean): breeze.promises.IPromise<EntityByKeyResult>;
fetchEntityByKey(entityKey: EntityKey): breeze.promises.IPromise<EntityByKeyResult>;
fetchMetadata(callback?: (schema: any) => void, errorCallback?: breeze.core.ErrorCallback): breeze.promises.IPromise<any>;
generateTempKeyValue(entity: Entity): any;
getChanges(): Entity[];
getChanges(entityTypeName: string): Entity[];
@@ -417,13 +435,13 @@ declare module breeze {
hasChanges(entityType: EntityType): boolean;
hasChanges(entityTypes: EntityType[]): boolean;
static importEntities(exportedString: string, config?: { mergeStrategy?: StrategySymbol; }): EntityManager;
static importEntities(exportedData: Object, config?: { mergeStrategy?: StrategySymbol; }): EntityManager;
importEntities(exportedString: string, config?: { mergeStrategy?: StrategySymbol; }): EntityManager;
importEntities(exportedData: Object, config?: { mergeStrategy?: StrategySymbol; }): EntityManager;
static importEntities(exportedString: string, config?: { mergeStrategy?: MergeStrategySymbol; metadataVersionFn?: (any: any) => void }): EntityManager;
static importEntities(exportedData: Object, config?: { mergeStrategy?: MergeStrategySymbol; metadataVersionFn?: (any: any) => void }): EntityManager;
importEntities(exportedString: string, config?: { mergeStrategy?: MergeStrategySymbol; metadataVersionFn?: (any: any) => void }): { entities: Entity[]; tempKeyMapping: { [key: string] : EntityKey } };
importEntities(exportedData: Object, config?: { mergeStrategy?: MergeStrategySymbol; metadataVersionFn?: (any: any) => void }): { entities: Entity[]; tempKeyMapping: { [key: string]: EntityKey } };
rejectChanges(): Entity[];
saveChanges(entities?: Entity[], saveOptions?: SaveOptions, callback?: SaveChangesSuccessCallback, errorCallback?: SaveChangesErrorCallback): Q.Promise<SaveResult>;
saveChanges(entities?: Entity[], saveOptions?: SaveOptions, callback?: SaveChangesSuccessCallback, errorCallback?: SaveChangesErrorCallback): breeze.promises.IPromise<SaveResult>;
setProperties(config: EntityManagerProperties): void;
}
@@ -451,15 +469,29 @@ declare module breeze {
}
interface ExecuteQueryErrorCallback {
(error: { query: EntityQuery; XHR: XMLHttpRequest; entityManager: EntityManager}): void;
(error: { query: EntityQuery; httpResponse: HttpResponse; entityManager: EntityManager; message?: string; stack?:string }): void;
}
interface SaveChangesSuccessCallback {
(saveResult: SaveResult): void;
}
interface EntityError {
entity: Entity;
errorMessage: string;
errorName: string;
isServerError: boolean;
propertyName: string;
}
interface SaveChangesErrorCallback {
(error: { XHR: XMLHttpRequest; }): void;
(error: {
entityErrors: EntityError[];
httpResponse: HttpResponse;
message: string;
stack?: string;
status?: number
}): void;
}
class EntityChangedEventArgs {
@@ -469,7 +501,7 @@ declare module breeze {
}
class EntityChangedEvent extends breeze.core.Event {
subscribe(callback?: (data: EntityChangedEventArgs) => void ): number;
subscribe(callback?: (data: EntityChangedEventArgs) => void): number;
}
class HasChangesChangedEventArgs {
@@ -478,7 +510,7 @@ declare module breeze {
}
class HasChangesChangedEvent extends breeze.core.Event {
subscribe(callback?: (data: HasChangesChangedEventArgs) => void ): number;
subscribe(callback?: (data: HasChangesChangedEventArgs) => void): number;
}
class EntityQuery {
@@ -492,9 +524,11 @@ declare module breeze {
takeCount: number;
wherePredicate: Predicate;
constructor (resourceName?: string);
constructor(resourceName?: string);
/** Create query from an expression tree */
constructor(tree: Object);
execute(callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Q.Promise<QueryResult>;
execute(callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): breeze.promises.IPromise<QueryResult>;
executeLocally(): Entity[];
expand(propertyPaths: string[]): EntityQuery;
expand(propertyPaths: string): EntityQuery;
@@ -505,9 +539,9 @@ declare module breeze {
static fromEntityKey(entityKey: EntityKey): EntityQuery;
static fromEntityNavigation(entity: Entity, navigationProperty: NavigationProperty): EntityQuery;
inlineCount(enabled?: boolean): EntityQuery;
noTracking(enabled: boolean): EntityQuery;
orderBy(propertyPaths: string): EntityQuery;
orderBy(propertyPaths: string[]): EntityQuery;
noTracking(enabled?: boolean): EntityQuery;
orderBy(propertyPaths: string, isDescending?: boolean): EntityQuery;
orderBy(propertyPaths: string[], isDescending?: boolean): EntityQuery;
orderByDesc(propertyPaths: string): EntityQuery;
orderByDesc(propertyPaths: string[]): EntityQuery;
select(propertyPaths: string): EntityQuery;
@@ -522,14 +556,18 @@ declare module breeze {
using(obj: DataService): EntityQuery;
using(obj: JsonResultsAdapter): EntityQuery;
using(obj: QueryOptions): EntityQuery;
using(obj: StrategySymbol): EntityQuery;
using(obj: MergeStrategySymbol): EntityQuery;
using(obj: FetchStrategySymbol): EntityQuery;
where(predicate: Predicate): EntityQuery;
where(property: string, operator: string, value: any): EntityQuery;
where(property: string, operator: FilterQueryOpSymbol, value: any): EntityQuery;
where(property: string, filterop: FilterQueryOpSymbol, property2: string, filterop2: FilterQueryOpSymbol, value: any): EntityQuery; // for any/all clauses
where(property: string, filterop: string, property2: string, filterop2: string, value: any): EntityQuery; // for any/all clauses
where(predicate: FilterQueryOpSymbol): EntityQuery;
where(property: string, filterop: FilterQueryOpSymbol, property2: string, filterop2: FilterQueryOpSymbol,value:any): EntityQuery;
withParameters(params: Object): EntityQuery;
toJSON(): string;
}
interface OrderByClause {
@@ -571,8 +609,8 @@ declare module breeze {
unmappedProperties: DataProperty[];
validators: Validator[];
constructor (config: MetadataStore);
constructor (config: EntityTypeOptions);
constructor(config: MetadataStore);
constructor(config: EntityTypeOptions);
addProperty(property: IProperty): void;
addValidator(validator: Validator, property?: IProperty): void;
@@ -601,10 +639,15 @@ declare module breeze {
interface EntityTypeProperties {
autoGeneratedKeyType?: AutoGeneratedKeyType;
defaultResourceName?: string;
}
serializerFn?: (dataProperty: DataProperty, value: any) => any;
}
class FetchStrategySymbol extends breeze.core.EnumSymbol {
private foo; // to distinguish this class from MergeStrategySymbol
}
interface FetchStrategy extends breeze.core.IEnum {
FromLocalCache: StrategySymbol;
FromServer: StrategySymbol;
FromLocalCache: FetchStrategySymbol;
FromServer: FetchStrategySymbol;
}
var FetchStrategy: FetchStrategy;
@@ -622,6 +665,7 @@ declare module breeze {
NotEquals: FilterQueryOpSymbol;
StartsWith: FilterQueryOpSymbol;
Any: FilterQueryOpSymbol;
All: FilterQueryOpSymbol;
}
var FilterQueryOp: FilterQueryOp;
@@ -629,16 +673,18 @@ declare module breeze {
static caseInsensitiveSQL: LocalQueryComparisonOptions;
static defaultInstance: LocalQueryComparisonOptions;
constructor (config: { name?: string; isCaseSensitive?: boolean; usesSql92CompliantStringComparison?: boolean; });
constructor(config: { name?: string; isCaseSensitive?: boolean; usesSql92CompliantStringComparison?: boolean; });
setAsDefault(): void;
}
class StrategySymbol extends breeze.core.EnumSymbol {
class MergeStrategySymbol extends breeze.core.EnumSymbol {
}
interface MergeStrategy extends breeze.core.IEnum {
OverwriteChanges: StrategySymbol;
PreserveChanges: StrategySymbol;
OverwriteChanges: MergeStrategySymbol;
PreserveChanges: MergeStrategySymbol;
SkipMerge: MergeStrategySymbol;
Disallowed: MergeStrategySymbol;
}
var MergeStrategy: MergeStrategy;
@@ -646,11 +692,11 @@ declare module breeze {
constructor();
constructor(config?: MetadataStoreOptions);
namingConvention: NamingConvention;
addDataService(dataService: DataService): void;
addDataService(dataService: DataService, shouldOverwrite?: boolean): void;
addEntityType(structuralType: IStructuralType): void;
exportMetadata(): string;
fetchMetadata(dataService: string, callback?: (data: any) => void , errorCallback?: breeze.core.ErrorCallback): Q.Promise<any>;
fetchMetadata(dataService: DataService, callback?: (data: any) => void , errorCallback?: breeze.core.ErrorCallback): Q.Promise<any>;
fetchMetadata(dataService: string, callback?: (data: any) => void, errorCallback?: breeze.core.ErrorCallback): breeze.promises.IPromise<any>;
fetchMetadata(dataService: DataService, callback?: (data: any) => void, errorCallback?: breeze.core.ErrorCallback): breeze.promises.IPromise<any>;
getDataService(serviceName: string): DataService;
getEntityType(entityTypeName: string, okIfNotFound?: boolean): IStructuralType;
getEntityTypes(): IStructuralType[];
@@ -658,11 +704,12 @@ declare module breeze {
static importMetadata(exportedString: string): MetadataStore;
importMetadata(exportedString: string, allowMerge?: boolean): MetadataStore;
isEmpty(): boolean;
registerEntityTypeCtor(entityTypeName: string, entityCtor: Function, initializationFn?: (entity: Entity) =>void ): void;
registerEntityTypeCtor(entityTypeName: string, entityCtor: Function, initializationFn?: (entity: Entity) => void, noTrackingFn?: (entity: Entity) => Entity): void;
trackUnmappedType(entityCtor: Function, interceptor?: Function): void;
setEntityTypeForResourceName(resourceName: string, entityType: EntityType): void;
setEntityTypeForResourceName(resourceName: string, entityTypeName: string): void;
getEntityTypeNameForResourceName(resourceName: string): string;
setProperties(config: { name?: string; serializerFn?: Function }): void;
}
interface MetadataStoreOptions {
@@ -675,7 +722,7 @@ declare module breeze {
static defaultInstance: NamingConvention;
static none: NamingConvention;
constructor (config: NamingConventionOptions);
constructor(config: NamingConventionOptions);
clientPropertyNameToServer(clientPropertyName: string): string;
clientPropertyNameToServer(clientPropertyName: string, property: IProperty): string;
@@ -704,7 +751,7 @@ declare module breeze {
relatedDataProperties: DataProperty[];
validators: Validator[];
constructor (config: NavigationPropertyOptions);
constructor(config: NavigationPropertyOptions);
}
interface NavigationPropertyOptions {
@@ -719,8 +766,12 @@ declare module breeze {
}
class Predicate {
constructor (property: string, operator: string, value: any, valueIsLiteral?: boolean);
constructor (property: string, operator: FilterQueryOpSymbol, value: any, valueIsLiteral?: boolean);
constructor(property: string, operator: string, value: any);
constructor(property: string, operator: FilterQueryOpSymbol, value: any);
constructor(property: string, operator: string, value: { value: any; isLiteral?: boolean; dataType?: breeze.DataType });
constructor(property: string, operator: FilterQueryOpSymbol, value: { value: any; isLiteral?: boolean; dataType?: breeze.DataType });
/** Create predicate from an expression tree */
constructor(tree: Object);
and: PredicateMethod;
static and: PredicateMethod;
@@ -738,6 +789,8 @@ declare module breeze {
toFunction(): Function;
toString(): string;
validate(entityType: EntityType): void;
toJSON(): string;
}
interface PredicateMethod {
@@ -749,37 +802,56 @@ declare module breeze {
class QueryOptions {
static defaultInstance: QueryOptions;
fetchStrategy: StrategySymbol;
mergeStrategy: StrategySymbol;
fetchStrategy: FetchStrategySymbol;
mergeStrategy: MergeStrategySymbol;
/** Whether query should return cached deleted entities (false by default) */
includeDeleted: boolean
constructor (config?: QueryOptionsConfiguration);
constructor(config?: QueryOptionsConfiguration);
setAsDefault(): void;
using(config: QueryOptionsConfiguration): QueryOptions;
using(config: StrategySymbol): QueryOptions;
using(config: MergeStrategySymbol): QueryOptions;
using(config: FetchStrategySymbol): QueryOptions;
}
interface QueryOptionsConfiguration {
fetchStrategy?: StrategySymbol;
mergeStrategy?: StrategySymbol;
fetchStrategy?: FetchStrategySymbol;
mergeStrategy?: MergeStrategySymbol;
}
interface HttpResponse {
config: any;
data: Entity[];
error?: any;
saveContext?: any;
status: number;
getHeaders(headerName: string): string
}
interface QueryResult {
/** Top level entities returned */
results: Entity[];
/** Query that was executed */
query: EntityQuery;
XHR: XMLHttpRequest;
/** Raw response from the server */
httpResponse: HttpResponse;
/** EntityManager that executed the query */
entityManager?: EntityManager;
inlineCount?: number
/** Total number of results available on the server */
inlineCount?: number;
/** All entities returned by the query. Differs from results when an expand is used. */
retrievedEntities?: Entity[]
}
class SaveOptions {
allowConcurrentSaves: boolean;
resourceName: string;
dataService: DataService;
tag: string;
tag: Object;
static defaultInstance: SaveOptions;
constructor (config?: { allowConcurrentSaves?: boolean; });
constructor(config?: { allowConcurrentSaves?: boolean; });
setAsDefault(): SaveOptions;
using(config: SaveOptionsConfiguration): SaveOptions;
@@ -789,7 +861,7 @@ declare module breeze {
allowConcurrentSaves?: boolean;
resourceName?: string;
dataService?: DataService;
tag?: string;
tag?: Object;
}
interface SaveResult {
@@ -807,7 +879,7 @@ declare module breeze {
validator: Validator;
getKey: (validator: Validator, property: string) => string;
constructor (validator: Validator, context: any, errorMessage: string, key: string);
constructor(validator: Validator, context: any, errorMessage: string, key: string);
}
class ValidationOptions {
@@ -817,7 +889,7 @@ declare module breeze {
validateOnQuery: boolean;
validateOnSave: boolean;
constructor (config?: ValidationOptionsConfiguration);
constructor(config?: ValidationOptionsConfiguration);
setAsDefault(): ValidationOptions;
using(config: ValidationOptionsConfiguration): ValidationOptions;
@@ -831,31 +903,65 @@ declare module breeze {
}
class Validator {
/** Map of standard error message templates keyed by validator name.*/
static messageTemplates: any;
context: any;
name: string;
constructor (name: string, validatorFn: ValidatorFunction, context?: any);
constructor(name: string, validatorFn: ValidatorFunction, context?: any);
static bool(): Validator;
static byte(): Validator;
/** integer between 0 and 255 inclusive */
static byte(context?: { messageTemplate?: string }): Validator;
static date(): Validator;
/** Returns a ISO 8601 duration string Validator. */
static duration(): Validator;
/** Validators number, double, and single are all the same */
static number(context?: { messageTemplate?: string }): Validator;
/** Validators number, double, and single are all the same */
static double(context?: { messageTemplate?: string }): Validator;
/** Validators number, double, and single are all the same */
static single(context?: { messageTemplate?: string }): Validator;
static guid(): Validator;
static int16(): Validator;
static int32(): Validator;
static int64(): Validator;
static maxLength(context: { maxLength: number; }): Validator;
static number(): Validator;
static required(): Validator;
static int16(context?: { messageTemplate?: string }): Validator;
static int32(context?: { messageTemplate?: string }): Validator;
static int64(context?: { messageTemplate?: string }): Validator;
/** Same as int64 */
static integer(context?: { messageTemplate?: string }): Validator;
static maxLength(context: { maxLength: number; messageTemplate?: string }): Validator;
static required(context?: { messageTemplate?: string }): Validator;
static string(): Validator;
static stringLength(context: { maxLength: number; minLength: number; }): Validator;
static register(validator: Validator): void;
static registerFactory(fn: () => Validator, name: string): void;
static stringLength(context: { maxLength: number; minLength: number; messageTemplate?: string }): Validator;
/** Returns a credit card number validator that performs a Luhn algorithm checksum test for plausability */
static creditCard(context?: { messageTemplate?: string }): Validator;
/** Returns a regular expression validator; the expression must be specified in the context parameter */
static regularExpression(context: { expression: RegExp; messageTemplate?: string }): Validator;
/** Returns the email address validator */
static emailAddress(context?: { messageTemplate?: string }): Validator;
/** Returns the phone validator, which handles prefix, country code, area code, and local number, with [-/. ] break characters. */
static phone(context?: { messageTemplate?: string }): Validator;
/** Returns the URL (protocol required) validator */
static url(context?: { messageTemplate?: string }): Validator;
/** Always returns true */
static none(): Validator;
/** Creates a validator instance from a JSON object or an array of instances from an array of JSON objects. */
static fromJSON(json: string): Validator;
/** Register a validator instance so that any deserialized metadata can reference it. */
static register(validator: Validator): void;
/** Register a validator factory so that any deserialized metadata can reference it. */
static registerFactory(fn: () => Validator, name: string): void;
/** Creates a regular expression validator with a fixed expression. */
static makeRegExpValidator(validatorName: string, expression: RegExp, defaultMessage: string, context?: any): Validator;
/** Run this validator against the specified value.
@param value {Object} Value to validate
@param additionalContext {Object} Any additional contextual information that the Validator can make use of.
@return {ValidationError|null} A ValidationError if validation fails, null otherwise */
validate(value: any, context?: any): ValidationError;
/** Returns the message generated by the most recent execution of this Validator. */
getMessage(): string;
}
@@ -881,18 +987,94 @@ declare module breeze.config {
var ajax: string;
var dataService: string;
var functionRegistry: Object;
export function getAdapter(interfaceName: string, adapterName: string): Object;
/**
Returns the ctor function used to implement a specific interface with a specific adapter name.
@method getAdapter
@param interfaceName {String} One of the following interface names "ajax", "dataService" or "modelLibrary"
@param [adapterName] {String} The name of any previously registered adapter. If this parameter is omitted then
this method returns the "default" adapter for this interface. If there is no default adapter, then a null is returned.
@return {Function|null} Returns either a ctor function or null.
**/
export function getAdapter(interfaceName: string, adapterName?: string): Function;
/**
Returns the adapter instance corresponding to the specified interface and adapter names.
@method getAdapterInstance
@param interfaceName {String} The name of the interface.
@param [adapterName] {String} - The name of a previously registered adapter. If this parameter is
omitted then the default implementation of the specified interface is returned. If there is
no defaultInstance of this interface, then the first registered instance of this interface is returned.
@return {an instance of the specified adapter}
**/
export function getAdapterInstance(interfaceName: string, adapterName?: string): Object;
export function initializeAdapterInstance(interfaceName: string, adapterName: string, isDefault: boolean): void;
export function initializeAdapterInstances(config: Object): void;
/**
Initializes a single adapter implementation. Initialization means either newing a instance of the
specified interface and then calling "initialize" on it or simply calling "initialize" on the instance
if it already exists.
@method initializeAdapterInstance
@param interfaceName {String} The name of the interface to which the adapter to initialize belongs.
@param adapterName {String} - The name of a previously registered adapter to initialize.
@param [isDefault=true] {Boolean} - Whether to make this the default "adapter" for this interface.
@return {an instance of the specified adapter}
**/
export function initializeAdapterInstance(interfaceName: string, adapterName: string, isDefault?: boolean): void;
/**
Initializes a collection of adapter implementations and makes each one the default for its corresponding interface.
@method initializeAdapterInstances
@param config {Object}
@param [config.ajax] {String} - the name of a previously registered "ajax" adapter
@param [config.dataService] {String} - the name of a previously registered "dataService" adapter
@param [config.modelLibrary] {String} - the name of a previously registered "modelLibrary" adapter
@param [config.uriBuilder] {String} - the name of a previously registered "uriBuilder" adapter
@return [array of instances]
**/
export function initializeAdapterInstances(config: Object): Object[];
var interfaceInitialized: Event;
var interfaceRegistry: Object;
var objectRegistry: Object;
/**
Method use to register implementations of standard breeze interfaces. Calls to this method are usually
made as the last step within an adapter implementation.
@method registerAdapter
@param interfaceName {String} - one of the following interface names "ajax", "dataService" or "modelLibrary"
@param adapterCtor {Function} - an ctor function that returns an instance of the specified interface.
**/
export function registerAdapter(interfaceName: string, adapterCtor: Function): void;
export function registerFunction(fn: Function, fnName: string): void;
export function registerType(ctor: Function, typeName: string): void;
//static setProperties(config: Object): void; //deprecated
/**
Set the promise implementation, if Q.js is not found.
@param q - implementation of promise. @see http://wiki.commonjs.org/wiki/Promises/A
*/
export function setQ(q: breeze.promises.IPromiseService): void;
var stringifyPad: string;
var typeRegistry: Object;
}
/** Promises interface used by Breeze. Usually implemented by Q (https://github.com/kriskowal/q) or angular.$q using breeze.config.setQ(impl) */
declare module breeze.promises {
interface IPromise<T> {
then<U>(onFulfill: (value: T) => U, onReject?: (reason: any) => U): IPromise<U>;
then<U>(onFulfill: (value: T) => IPromise<U>, onReject?: (reason: any) => U): IPromise<U>;
then<U>(onFulfill: (value: T) => U, onReject?: (reason: any) => IPromise<U>): IPromise<U>;
then<U>(onFulfill: (value: T) => IPromise<U>, onReject?: (reason: any) => IPromise<U>): IPromise<U>;
catch<U>(onRejected: (reason: any) => U): IPromise<U>;
catch<U>(onRejected: (reason: any) => IPromise<U>): IPromise<U>;
finally(finallyCallback: () => any): IPromise<T>;
}
interface IDeferred<T> {
promise: IPromise<T>;
resolve(value: T): void;
reject(reason: any): void;
}
interface IPromiseService {
defer<T>(): IDeferred<T>;
reject(reason?: any): IPromise<any>;
resolve<T>(object: T): IPromise<T>;
resolve<T>(object: IPromise<T>): IPromise<T>;
}
}
+72 -41
View File
@@ -1,9 +1,11 @@
# Meteor Type Definitions
These are the definitions for version 0.9.1 of Meteor. Although these definitions can be downloaded separately for use, the recommended way to use these
These are the definitions for version 1.0.3.1 of Meteor.
Although these definitions can be downloaded separately for use, the recommended way to use these
definitions in a Meteor application is by installing the [typescript-libs](https://atmosphere.meteor.com/package/typescript-libs) Meteor smart package.
The smart package contains TypeScript definitions forMeteor, common third-party libraries (e.g. jquery, underscore, d3 etc.), and common smart packages
(e.g. iron-router).
(e.g. iron-router, etc).
From within any Meteor application that is version 0.9.0 or later, install this package in the standard manner:
@@ -11,28 +13,42 @@ From within any Meteor application that is version 0.9.0 or later, install this
## Usage Overview
For most applications, there are 4 specific steps you will have to take to write your Meteor application in TypeScript using this package:
## Usage
1. [Reference the definitions] (#usage-type-definition-references)
2. [Declare functions for Templates in a special way] (#usage-templates)
3. [Declare Collections in a special way] (#usage-collections)
4. [Create custom definitions for code you write] (#usage-creating-definitions)
5. [Transpile your .ts files into .js files] (#usage-transpilation)
1. Add a symbolic link to the definitions from within some directory within your project (e.g. ".typescript" or "lib"). The definitions can be found somewhere
deep within `<project_root_dir>/.meteor/...`. The following will probably work:
$ ln -s ../.meteor/local/build/programs/server/assets/packages/meteortypescript_typescript-libs/definitions package_defs
If the definitions can't be found within the .meteor directory, you will have to manually pull down the definitions from github and add them to your project:
<https://github.com/meteor-typescript/meteor-typescript-libs>
## Usage: Type Definition References
Within any TypeScript file, you can reference the Meteor definition file with this line:
2. Install the [Typescript compiler for Meteor](https://github.com/meteor-typescript/meteor-typescript-compiler) or an [IDE which can transpile TypeScript to JavaScript](#transpiling-typescript).
3. From the typescript files, add references. Reference the definition files with a single line:
///<reference path="/path/to/packages/typescript-libs/meteor.d.ts" />
/// <reference path=".typescript/package_defs/all-definitions.d.ts" /> (substitute path in your project)
Or you can reference definition files individually:
## Usage: Templates
When specifying template functions, you will need to use "bracket notation" instead of "dot notation":
/// <reference path=".typescript/package_defs/meteor.d.ts" /> (substitue path in your project)
/// <reference path=".typescript/package_defs/underscore.d.ts" />
/// <reference path=".typescript/package_defs/jquery.d.ts" />
Template['myTemplateName']['rendered'] = function ( ) { ... }
4. Be aware of differences in coding styles when using TypeScript (see below)
## TypeScript/Meteor coding style
### References
Try to stay away from referencing *file.ts*, rather generate a *file.d.ts* using `tsc --reference file.ts`, and reference it in your file. Compilation will
be much faster and code cleaner - it's always better to split definition from implemention.
### Templates
When specifying template *helpers*, *events*, and functions for *created*, *rendered*, and *destroyed*, you will need to use a "bracket notation" instead of the "dot notation":
Template['myTemplateName']['helpers']({
foo: function () {
@@ -40,21 +56,28 @@ When specifying template functions, you will need to use "bracket notation" inst
}
});
Template['myTemplateName']['foo'] = function () {
return Session.get("foo");
};
Template['myTemplateName']['rendered'] = function ( ) { ... }
This is because TypeScript enforces typing and it will throw an error saying "myTemplateName" does not exist when using the dot notation.
For "dot" notation, TypeScript requires properties be specified on a variable (but not for bracket notation), and it will throw an error saying "myTemplateName"
does not exist on Template.
### Accessing a Form field
Trying to read a form field value? use `(<HTMLInputElement>evt.target).value`.
### Global variables
## Usage: Collections
The majority of extra work required to use TypeScript with Meteor is creating and maintaining the collection interfaces. However, doing so also provides the
Preface any global variable declarations with a TypeScript "declare var" statement:
declare var NavbarHelpers;
NavbarHelpers = {};
NavbarHelpers.someMethod = function() {...}
### Collections
The majority of extra work required to use TypeScript with Meteor is creating and maintaining the collection interfaces. However, doing so also provides the
additional benefit of succinctly documenting collection schema definitions (that are actually enforced).
To define collections, you will need to create an interface representing the collection, and then declare a Collection type variable with that interface type (as a generic):
To define collections, you will need to create an interface representing the collection and then declare a Collection type variable with that interface type (as a generic):
interface JobDAO {
_id?: string;
@@ -63,39 +86,47 @@ To define collections, you will need to create an interface representing the col
queuedAt?: string;
}
declare var Jobs: Meteor.Collection<JobDAO>;
Jobs = new Meteor.Collection<JobDAO>('jobs');
declare var Jobs: Mongo.Collection<JobDAO>;
Jobs = new Mongo.Collection<JobDAO>('jobs');
Finally, any TypeScript file using collections will need to contain a reference at the top pointing to the collection definitions:
/// <reference path="../packages/typescript-libs/meteor.d.ts"/>
/// <reference path="../packages/typescript-libs/underscore.d.ts"/>
/// <reference path="models/models.ts"/>
/// <reference path=".typescript/package_defs/meteor.d.ts"/>
/// <reference path=".typescript/custom_defs/collections.ts"/>
### Creating definition files
If you choose to define collections (using the code above) in a separate file (e.g. collections/models/models.ts) and then create a separate file per collection
with the methods and permissions for that collection (e.g. collections/jobs.ts), the collection definitions should be one directory deeper than the collection
method/permission declarations so that Meteor can find the variable declarations before use. (e.g. collections/models/models.ts).
## Usage: Creating Definitions
Here is a guide to creating definitions: <http://www.typescriptlang.org/Handbook#writing-dts-files>
If you have lots of custom definitions for a project, you can:
- Create multiple definition files and include individual references to each definition file.
- Create one huge monolithic definition file so you only have to refer to that file.
- Create multiple definition files, and create a definition file with references to the other definitions files so that you only have to maintain one reference
for all of you custom definitions. e.g. contents of ".typescript/custom_defs/custom-definitions.d.ts":
## Usage: Transpilation
WebStorm is good TypeScript-aware editor. It can automatically transpile your TypeScript code into JavaScript every time you save a file. To enable this
/// <reference path='collections.ts' />
/// <reference path='paraview_helpers.d.ts'/>
/// <reference path='handsontable.d.ts'/>
/// <reference path='utility_helpers.ts'/>
## Transpiling TypeScript
### Meteor plugin
One solution for transpiling typescript is to install the following meteor package [https://github.com/meteor-typescript/meteor-typescript-compiler](https://github.com/meteor-typescript/meteor-typescript-compiler)
### IDE/Editor Transpilation
WebStorm is a good TypeScript-aware editor. It can automatically transpile your TypeScript code into JavaScript every time you save a file. To enable this
feature in WebStorm on OSX, first install the TypeScript transpiler on your system:
$ [sudo -H] npm install -g typescript
Then, within WebStorm, go to Preferences -> File Watchers -> "+" symbol and add TypeScript.
If you are not using a TypeScript-aware editor, you can transpile the files using the [Meteor Typescript Compiler](https://github.com/orefalo/meteor-typescript-compiler).
### Command line
Last option, is to compile code from the command line. With node and the typescript compiler installed:
## Example/Reference Projects
* [TypeScript demos](https://github.com/orefalo/meteor-typescript-demos)
$ tsc *.ts
+8 -9
View File
@@ -124,7 +124,7 @@ Meteor.methods({
var you_want_to_throw_an_error = true;
if (you_want_to_throw_an_error)
throw new Meteor.Error(404, "Can't find my pants");
throw new Meteor.Error("404", "Can't find my pants");
return "some return value";
},
@@ -376,7 +376,7 @@ Accounts.ui.config({
Accounts.validateNewUser(function (user) {
if (user.username && user.username.length >= 3)
return true;
throw new Meteor.Error(403, "Username must have at least 3 characters");
throw new Meteor.Error("403", "Username must have at least 3 characters");
});
// Validate username, without a specific error message.
Accounts.validateNewUser(function (user) {
@@ -530,13 +530,6 @@ Meteor.methods({
// Let other method calls from the same client start running,
// without waiting for the email sending to complete.
this.unblock();
Email.send({
to: to,
from: from,
subject: subject,
text: text
});
}
});
@@ -561,3 +554,9 @@ Blaze.toHTMLWithData(testTemplate, {test: 1});
Blaze.toHTMLWithData(testTemplate, function() {});
Blaze.toHTMLWithData(testView, {test: 1});
Blaze.toHTMLWithData(testView, function() {});
var reactiveVar1 = new ReactiveVar('test value');
var reactiveVar2 = new ReactiveVar('test value', function(oldVal) { return true; });
var varValue: string = reactiveVar1.get();
reactiveVar1.set('new value');
+455 -413
View File
@@ -1,19 +1,86 @@
// Type definitions for Meteor 0.9.1
// Type definitions for Meteor 1.0.3.1
// Project: http://www.meteor.com/
// Definitions by: Dave Allen <https://github.com/fullflavedave>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* These are the modules and interfaces that can't be automatically generated from the Meteor api.js file
* These are the modules and interfaces that can't be automatically generated from the Meteor data.js file
*/
interface EJSON extends JSON {}
interface Template {
[templateName: string]: Meteor.Template;
}
declare module Match {
var Any;
var String;
var Integer;
var Boolean;
var undefined;
//function null(); // not allowed in TypeScript
var Object;
function Optional(pattern):boolean;
function ObjectIncluding(dico):boolean;
function OneOf(...patterns);
function Where(condition);
}
declare module Meteor {
interface EJSONObject extends Object {}
//interface EJSONObject extends Object {}
/** Start definitions for Template **/
// DA: "Template" needs to support these functions:
// Template.<your template name>.rendered
// Template.<your template name>.created
// Template.<your template name>.destroyed
// Template.<your template name>.helpers
// Template.<your template name>.events
// and
// Template.currentData
// Template.parentData, etc.
interface Event {
type:string;
target:HTMLElement;
currentTarget:HTMLElement;
which: number;
stopPropagation():void;
stopImmediatePropagation():void;
preventDefault():void;
isPropagationStopped():boolean;
isImmediatePropagationStopped():boolean;
isDefaultPrevented():boolean;
}
interface EventHandlerFunction extends Function {
(event?:Meteor.Event):any;
}
interface EventMap {
[id:string]:Meteor.EventHandlerFunction;
}
// Same definition as top-level Template Interface
interface TemplateBase {
[templateName: string]: Meteor.Template;
}
interface Template {
rendered: Function;
created: Function;
destroyed: Function;
events(eventMap:Meteor.EventMap): void;
helpers(helpers:{[id:string]: any}): void;
}
/** End definitions for Template **/
interface LoginWithExternalServiceOptions {
requestPermissions?: string[];
requestOfflineToken?: Boolean;
forceApprovalPrompt?: Boolean;
userEmail?: string;
loginStyle?: string;
}
function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void;
@@ -43,14 +110,6 @@ declare module Meteor {
ready(): boolean;
}
interface TemplateBase {
[templateName: string]: Meteor.Template;
}
interface RenderedTemplate extends Object {}
interface DataContext extends Object {}
interface Tinytest {
add(name:string, func:Function);
addAsync(name:string, func:Function);
@@ -81,31 +140,32 @@ declare module Meteor {
verifyEmail: Meteor.EmailFields;
}
interface AccountsBase {
EmailTemplates: {
from: string;
siteName: string;
resetPassword: Meteor.EmailFields;
enrollAccount: Meteor.EmailFields;
verifyEmail: Meteor.EmailFields;
}
loginServicesConfigured(): boolean;
interface Error {
error: number;
reason?: string;
details?: string;
}
interface MatchBase {
Any;
String;
Integer;
Boolean;
undefined;
null;
Object;
Optional(pattern):boolean;
ObjectIncluding(dico):boolean;
OneOf(...patterns);
Where(condition);
interface Connection {
id: string;
close: Function;
onClose: Function;
clientAddress: string;
httpHeaders: Object;
}
}
declare module Mongo {
interface Selector extends Object {}
interface Modifier {}
interface SortSpecifier {}
interface FieldSpecifier {
[id: string]: Number;
}
enum IdGenerationEnum {
STRING,
MONGO
}
interface AllowDenyOptions {
insert?: (userId:string, doc) => boolean;
update?: (userId, doc, fieldNames, modifier) => boolean;
@@ -113,95 +173,9 @@ declare module Meteor {
fetch?: string[];
transform?: Function;
}
interface Error {
error: number;
reason?: string;
details?: string;
}
}
declare module Mongo {
interface CollectionFieldSpecifier {
[id: string]: Number;
}
enum CollectionIdGenerationEnum {
STRING,
MONGO
}
// interface CollectionOptions {
// connection: Object;
// idGeneration: Mongo.CollectionIdGenerationEnum;
// transform?: (document)=>any;
// }
//
// function Collection<T>(name:string, options?: Mongo.CollectionOptions) : void;
}
declare module Tracker {
function Computation(): void;
interface Computation {
}
function Dependency(): void;
interface Dependency {
changed(): void;
depend(fromComputation: Tracker.Computation): boolean;
hasDependents(): boolean;
}
}
declare module Package {
function describe(metadata:PackageDescribeAPI);
function on_use(func:{(api:Api, where?:string[]):void});
function on_use(func:{(api:Api, where?:string):void});
function on_test(func:{(api:Api):void}) ;
function register_extension(extension:string, options:PackageRegisterExtensionOptions);
interface PackageRegisterExtensionOptions {(bundle:Bundle, source_path:string, serve_path:string, where?:string[]):void}
interface PackageDescribeAPI {
summary: string;
}
interface Api {
export(variable:string);
export(variables:string[]);
use(deps:string, where?:string[]);
use(deps:string, where?:string);
use(deps:string[], where?:string[]);
use(deps:string[], where?:string);
add_files(file:string, where?:string[]);
add_files(file:string, where?:string);
add_files(file:string[], where?:string[]);
add_files(file:string[], where?:string);
imply(package:string);
imply(packages:string[]);
}
interface BundleOptions {
type: string;
path: string;
data: any;
where: string[];
}
interface Bundle {
add_resource(options:BundleOptions);
error(diagnostics:string);
}
}
declare module Npm {
function require(module:string);
function depends(dependencies:{[id:string]:string});
}
declare module HTTP {
enum HTTPMethodEnum {
GET,
POST,
PUT,
DELETE
}
interface HTTPRequest {
content?:string;
data?:any;
@@ -259,6 +233,8 @@ declare module DDP {
}
declare module Random {
function id(numberOfChars?: number): string;
function secret(numberOfChars?: number): string;
function fraction():number;
function hexString(numberOfDigits:number):string; // @param numberOfDigits, @returns a random hex string of the given length
function choice(array:any[]):string; // @param array, @return a random element in array
@@ -292,339 +268,405 @@ declare module Blaze {
/**
* These modules and interfaces are automatically generated from the Meteor api.js file
*/
declare module Meteor {
var isClient: boolean;
var isServer: boolean;
var isCordova: boolean;
function startup(func: Function): void;
function wrapAsync(func: Function, context?: Object): any;
function absoluteUrl(path?: string, options?: {
secure?: Boolean;
replaceLocalhost?: Boolean;
rootUrl?: string;
}): string;
var settings: {[id:string]: any};
var release: string;
function publish(name: string, func: Function): void;
function subscribe(name, ...args): SubscriptionHandle;
function methods(methods: Object): void;
function Error(error, reason?, details?): void;
function call(name: string, ...params): void;
function apply(name: string, params, options?: {
wait?: Boolean;
onResultReceived?: Function;
}, asyncCallback?): void;
function status(): Meteor.StatusEnum;
function reconnect(): void;
function disconnect(): void;
function onConnection(callback: Function): void;
function user(): Meteor.User;
function userId(): string;
var users: Mongo.Collection<User>;
function loggingIn(): boolean;
function logout(callback?: Function): void;
function logoutOtherClients(callback?: Function): void;
function loginWithPassword(user: any, password: string, callback?: Function): void;
function loginWithExternalService(options?: {
requestPermissions?: string[];
requestOfflineToken?: Boolean;
forceApprovalPrompt?: Boolean;
userEmail?: string;
loginStyle?: string;
}, callback?: Function): void;
function setTimeout(func: Function, delay: number): number;
function setInterval(func: Function, delay: number): number;
function clearTimeout(id: number): void;
function clearInterval(id: number): void;
function EnvironmentVariable(): void;
function get(): string;
function withValue(value: any, func: Function): void;
function bindEnvironment(func: Function, onException: Function, _this: Object): Function;
declare module Accounts {
var ui: {
config(options: {
requestPermissions?: Object;
requestOfflineToken?: Object;
forceApprovalPrompt?: Object;
passwordSignupFields?: string;
}): void;
};
var emailTemplates: Meteor.EmailTemplates;
function config(options: {
sendVerificationEmail?: boolean;
forbidClientAccountCreation?: Boolean;
restrictCreationByEmailDomain?: string | Function;
loginExpirationInDays?: number;
oauthSecretKey?: string;
}): void;
function validateLoginAttempt(func: Function): {stop: Function};
function onLogin(func: Function): {stop: Function};
function onLoginFailure(func: Function): {stop: Function};
function onCreateUser(func: Function): void;
function validateNewUser(func: Function): void;
function onResetPasswordLink(callback: Function): void;
function onEmailVerificationLink(callback: Function): void;
function onEnrollmentLink(callback: Function): void;
function createUser(options: {
username?: string;
email?: string;
password?: string;
profile?: Object;
}, callback?: Function): string;
function changePassword(oldPassword: string, newPassword: string, callback?: Function): void;
function forgotPassword(options: {
email?: string;
}, callback?: Function): void;
function resetPassword(token: string, newPassword: string, callback?: Function): void;
function verifyEmail(token: string, callback?: Function): void;
function setPassword(userId: string, newPassword: string): void;
function sendResetPasswordEmail(userId: string, email?: string): void;
function sendEnrollmentEmail(userId: string, email?: string): void;
function sendVerificationEmail(userId: string, email?: string): void;
}
declare module Meteor {
interface EJSON {
parse(str: string): EJSON;
stringify(val: Meteor.EJSON, options?: {
indent?: any; // boolean, integer, or string
canonical?: Boolean;
}): string;
fromJSONValue(val: JSON): any;
toJSONValue(val: Meteor.EJSON): JSON;
equals(a: Meteor.EJSONObject, b: Meteor.EJSONObject, options?: {
keyOrderSensitive?: Boolean;
}): boolean;
clone<T>(v:T): T; /** TODO: add return value **/
newBinary(size: number): any;
isBinary(x): boolean;
addType(name: string, factory: Function): void;
declare module Blaze {
var currentView: Blaze.View;
function With(data: Object | Function, contentFunc: Function): Blaze.View;
function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View;
function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View;
function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View;
function isTemplate(value: any): boolean;
function render(templateOrView: Template | Blaze.View, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View;
function renderWithData(templateOrView: Template | Blaze.View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View;
function remove(renderedView: Blaze.View): void;
function toHTML(templateOrView: Template | Blaze.View): string;
function toHTMLWithData(templateOrView: Template | Blaze.View, data: Object | Function): string;
function getData(elementOrView?: HTMLElement | Blaze.View): Object;
function getView(element?: HTMLElement): Blaze.View;
function Template(viewName?: string, renderFunction?: Function): void;
function TemplateInstance(view: Blaze.View): void;
interface TemplateInstance {
data(): Object;
view(): Object;
firstNode(): Object;
lastNode(): Object;
$(selector: string): Node[];
findAll(selector: string): HTMLElement[];
find(selector?: string): HTMLElement;
autorun(runFunc: Function): Object;
}
function View(name?: string, renderFunction?: Function): void;
}
declare module Match {
function test(value: any, pattern: any): boolean;
}
declare module DDP {
function connect(url: string): DDP.DDPStatic;
}
declare module EJSON {
var newBinary: any;
function addType(name: string, factory: Function): void;
function toJSONValue(val: EJSON): JSON;
function fromJSONValue(val: JSON): any;
function stringify(val: EJSON, options?: {
indent?: boolean | number | string;
canonical?: Boolean;
}): string;
function parse(str: string): EJSON;
function isBinary(x: Object): boolean;
function equals(a: EJSON, b: EJSON, options?: {
keyOrderSensitive?: boolean;
}): boolean;
function clone<T>(val:T): T;
function CustomType(): void;
interface CustomType {
typeName(): string;
toJSONValue(): JSON;
clone(): EJSON.CustomType;
equals(other: Object): boolean;
}
}
declare module Meteor {
var users: Mongo.Collection<User>;
var isClient: boolean;
var isServer: boolean;
var settings: {[id:string]: any};
var isCordova: boolean;
var release: string;
function userId(): string;
function loggingIn(): boolean;
function user(): Meteor.User;
function logout(callback?: Function): void;
function logoutOtherClients(callback?: Function): void;
function loginWith<ExternalService>(options?: {
requestPermissions?: string[];
requestOfflineToken?: boolean;
forceApprovalPrompt?: Boolean;
userEmail?: string;
loginStyle?: string;
}, callback?: Function): void;
function loginWithPassword(user: Object | string, password: string, callback?: Function): void;
function subscribe(name: string, ...args): SubscriptionHandle;
function call(name: string, ...args): void;
function apply(name: string, args: EJSON[], options?: {
wait?: boolean;
onResultReceived?: Function;
}, asyncCallback?: Function): void;
function status(): Meteor.StatusEnum;
function reconnect(): void;
function disconnect(): void;
function onConnection(callback: Function): void;
function publish(name: string, func: Function): void;
function methods(methods: Object): void;
function wrapAsync(func: Function, context?: Object): any;
function startup(func: Function): void;
function setTimeout(func: Function, delay: number): number;
function setInterval(func: Function, delay: number): number;
function clearInterval(id: number): void;
function clearTimeout(id: number): void;
function absoluteUrl(path?: string, options?: {
secure?: boolean;
replaceLocalhost?: Boolean;
rootUrl?: string;
}): string;
function Error(error: string, reason?: string, details?: string): void;
}
declare module Mongo {
function Collection<T>(name: string, options?: {
connection?: Object;
idGeneration?: Mongo.CollectionIdGenerationEnum;
transform?: (document)=>any;
}): void;
function ObjectID(hexString: string): void;
}
declare module Mongo {
connection?: Object;
idGeneration?: string;
transform?: Function;
}): void;
interface Collection<T> {
find(selector?: any, options?: {
sort?: any;
skip?: number;
limit?: number;
fields?: Mongo.CollectionFieldSpecifier;
reactive?: Boolean;
transform?: (document)=>any;
}): Mongo.Cursor<T>;
findOne(selector?: any, options?: {
sort?: any;
skip?: number;
fields?: Mongo.CollectionFieldSpecifier;
reactive?: Boolean;
transform?: (document)=>any;
}): Meteor.EJSONObject;
insert(doc: Object, callback?: Function): string;
update(selector: any, modifier: any, options?: {
multi?: Boolean;
upsert?: Boolean;
}, callback?: Function): number;
upsert(selector: any, modifier: any, options?: {
multi?: Boolean;
}, callback?: Function): {numberAffected?: number; insertedId?: string;};
remove(selector: any, callback?: Function): void;
allow(options: Meteor.AllowDenyOptions): boolean;
deny(options: Meteor.AllowDenyOptions): boolean;
insert(doc: Object, callback?: Function): string;
update(selector: Mongo.Selector, modifier: Mongo.Modifier, options?: {
multi?: boolean;
upsert?: Boolean;
}, callback?: Function): number;
find(selector?: Mongo.Selector, options?: {
sort?: Mongo.SortSpecifier;
skip?: number;
limit?: number;
fields?: Mongo.FieldSpecifier;
reactive?: boolean;
transform?: Function;
}): Mongo.Cursor<T>;
findOne(selector?: Mongo.Selector, options?: {
sort?: Mongo.SortSpecifier;
skip?: number;
fields?: Mongo.FieldSpecifier;
reactive?: boolean;
transform?: Function;
}): T;
remove(selector: Mongo.Selector, callback?: Function): void;
upsert(selector: Mongo.Selector, modifier: Mongo.Modifier, options?: {
multi?: boolean;
}, callback?: Function): {numberAffected?: number; insertedId?: string;};
allow(options: {
insert?: (userId:string, doc) => boolean;
update?: (userId, doc, fieldNames, modifier) => boolean;
remove?: (userId, doc) => boolean;
fetch?: string[];
transform?: Function;
}): boolean;
deny(options: {
insert?: (userId:string, doc) => boolean;
update?: (userId, doc, fieldNames, modifier) => boolean;
remove?: (userId, doc) => boolean;
fetch?: string[];
transform?: Function;
}): boolean;
}
}
declare module Mongo {
function ObjectID(hexString: string): void;
function Cursor<T>(): void;
interface Cursor<T> {
count(): number;
fetch(): any[];
forEach(callback: Function, thisArg?: any): void;
forEach(callback: Function, thisArg?: any): void;
map(callback: Function, thisArg?: any): void;
fetch(): Array<T>;
count(): number;
observe(callbacks: Object): Meteor.LiveQueryHandle;
observeChanges(callbacks: Object): Meteor.LiveQueryHandle;
}
}
declare module Random {
function id(): string;
}
declare module Tracker {
function autorun(runFunc: Function): Tracker.Computation;
function flush(): void;
function nonreactive(func: Function): void;
var active: boolean;
var currentComputation: Tracker.Computation;
function Computation(): void;
interface Computation {
stopped(): boolean;
invalidated(): boolean;
firstRun(): boolean;
onInvalidate(callback: Function): void;
invalidate(): void;
stop(): void;
}
function flush(): void;
function autorun(runFunc: Function): Tracker.Computation;
function nonreactive(func: Function): void;
function onInvalidate(callback: Function): void;
function afterFlush(callback: Function): void;
}
declare module Tracker {
interface Computation {
stop(): void;
invalidate(): void;
onInvalidate(callback: Function): void;
stopped: boolean;
invalidated: boolean;
firstRun: boolean;
}
}
declare module Tracker {
function Dependency(): void;
interface Dependency {
depend(fromComputation?: Tracker.Computation): boolean
changed(): void;
depend(fromComputation?: Tracker.Computation): boolean;
hasDependents(): boolean;
hasDependents(): boolean
}
}
declare module Meteor {
interface Accounts extends Meteor.AccountsBase {
config(options: {
sendVerificationEmail?: Boolean;
forbidClientAccountCreation?: Boolean;
restrictCreationByEmailDomain?: any; // string or Function
loginExpirationInDays?: number;
oauthSecretKey?: string;
}): void;
ui: {
config(options: {
requestPermissions?: Object;
requestOfflineToken?: Object;
forceApprovalPrompt?: Boolean;
passwordSignupFields?: string;
}); /** TODO: add return value **/
}
validateNewUser(func: Function): void;
onCreateUser(func: Function): void;
validateLoginAttempt(func: Function); /** TODO: add return value **/
onLogin(func: Function); /** TODO: add return value **/
onLoginFailure(func: Function); /** TODO: add return value **/
createUser(options: {
username?: string;
email?: string;
password?: string;
profile?: Object;
}, callback?: Function): string;
changePassword(oldPassword: string, newPassword: string, callback?: Function): void;
forgotPassword(options: {
email?: string;
}, callback?: Function): void;
resetPassword(token: string, newPassword: string, callback?: Function): void;
setPassword(userId: string, newPassword: string): void;
verifyEmail(token: string, callback?: Function): void;
sendResetPasswordEmail(userId: string, email?: string): void;
sendEnrollmentEmail(userId: string, email?: string): void;
sendVerificationEmail(userId: string, email?: string): void;
emailTemplates: Meteor.EmailTemplates;
}
}
declare module Meteor {
interface Match extends Meteor.MatchBase {
test(value: any, pattern: any): boolean;
}
}
declare module Meteor {
interface Session {
set(key: string, value: any): void;
setDefault(key: string, value: any): void;
get(key: string): any;
equals(key: string, value: any): boolean;
}
}
declare module HTTP {
function call(method: string, url, options?: {
content?: string;
data?: Object;
query?: string;
params?: Object;
auth?: string;
headers?: Object;
timeout?: number;
followRedirects?: Boolean;
}, asyncCallback?): HTTP.HTTPResponse;
function get(url, options?: {
}, asyncCallback?): HTTP.HTTPResponse;
function post(url, options?: {
}, asyncCallback?): HTTP.HTTPResponse;
function put(url, options?: {
}, asyncCallback?): HTTP.HTTPResponse;
function del(url, options?: {
}, asyncCallback?): HTTP.HTTPResponse;
}
declare module Meteor {
interface Template {
rendered: Function;
created: Function;
destroyed: Function;
events(eventMap: {[id:string]: Function}): void;
helpers(helpers: Object): void;
findAll(selector: string); /** TODO: add return value **/
$(selector: string); /** TODO: add return value **/
find(selector?: string); /** TODO: add return value **/
firstNode; /** TODO: add return value **/
lastNode; /** TODO: add return value **/
data; /** TODO: add return value **/
autorun(runFunc: Function); /** TODO: add return value **/
view; /** TODO: add return value **/
registerHelper(name: string, func: Function); /** TODO: add return value **/
body; /** TODO: add return value **/
currentData(); /** TODO: add return value **/
instance(); /** TODO: add return value **/
parentData(numLevels: number); /** TODO: add return value **/
}
}
declare module Blaze {
function render(templateOrView: any, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View;
function renderWithData(templateOrView: any, data: any, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View;
function remove(renderedView: Blaze.View): void;
function With(data: any, contentFunc: Function); /** TODO: add return value **/
function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function); /** TODO: add return value **/
function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function); /** TODO: add return value **/
function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function); /** TODO: add return value **/
function getData(elementOrView?: any); /** TODO: add return value **/
var currentView; /** TODO: add return value **/
function getView(element?: HTMLElement); /** TODO: add return value **/
function toHTML(templateOrView: any): string;
function toHTMLWithData(templateOrView: any, data: any): string;
function View(name?: string, renderFunction?: Function): void;
function Template(viewName?: string, renderFunction?: Function): void;
function isTemplate(value: any): boolean;
}
declare module Meteor {
interface ReactiveVar {
get(); /** TODO: add return value **/
set(newValue: any); /** TODO: add return value **/
}
}
declare module Email {
function send(options: {
from?: string;
to?: any; // string or string[]
cc?: any; // string or string[]
bcc?: any; // string or string[]
replyTo?: any; // string or string[]
subject?: string;
text?: string;
html?: string;
headers?: Object;
}): void;
}
declare module Assets {
function getText(assetPath: string, asyncCallback?: Function): string;
function getBinary(assetPath: string, asyncCallback?: Function): Meteor.EJSON;
function getBinary(assetPath: string, asyncCallback?: Function): EJSON;
}
declare module Meteor {
interface Package {
describe(options: {
summary?: string;
version?: string;
name?: string;
git?: string;
}); /** TODO: add return value **/
onUse(f: Function); /** TODO: add return value **/
onTest(f: Function); /** TODO: add return value **/
describe(options: {
}); /** TODO: add return value **/
}
declare module App {
function info(options: {
id?: string;
version?: string;
name?: string;
description?: string;
author?: string;
email?: string;
website?: string;
}): void;
function setPreference(name: string, value: string): void;
function configurePlugin(pluginName: string, config: Object): void;
function icons(icons: Object): void;
function launchScreens(launchScreens: Object): void;
}
declare module Meteor {
interface Api {
use(packageNameAndVersion?: string, architecture?: string, options?: {
weak?: Boolean;
unordered?: Boolean;
}); /** TODO: add return value **/
versionsFrom(meteorversion: string); /** TODO: add return value **/
imply(packagespecOrpackagespecs: any); /** TODO: add return value **/
export(exportedObject: string, architecture?: string); /** TODO: add return value **/
addFiles(filenameOrfilenames: any); /** TODO: add return value **/
}
declare module Package {
function describe(options: {
summary?: string;
version?: string;
name?: string;
git?: string;
documentation?: string;
}): void;
function onUse(func: Function): void;
function onTest(func: Function): void;
function registerBuildPlugin(options?: {
name?: string;
use?: string | string[];
sources?: string[];
npmDependencies?: Object;
}): void;
}
declare module Npm {
function depends(dependencies:{[id:string]:string}): void;
function require(name: string): void;
}
declare module Cordova {
function depends(dependencies:{[id:string]:string}): void;
}
declare module Session {
function set(key: string, value: EJSON | any /** Undefined **/): void;
function setDefault(key: string, value: EJSON | any /** Undefined **/): void;
function get(key: string): any;
function equals(key: string, value: string | number | boolean | any /** Null **/ | any /** Undefined **/): boolean;
}
declare module HTTP {
function call(method: string, url: string, options?: {
content?: string;
data?: Object;
query?: string;
params?: Object;
auth?: string;
headers?: Object;
timeout?: number;
followRedirects?: boolean;
}, asyncCallback?: Function): HTTP.HTTPResponse;
function get(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse;
function post(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse;
function put(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse;
function del(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse;
}
declare module Email {
function send(options: {
from?: string;
to?: string | string[];
cc?: string | string[];
bcc?: string | string[];
replyTo?: string | string[];
subject?: string;
text?: string;
html?: string;
headers?: Object;
}): void;
}
declare function Subscription(): void;
declare module Subscription {
var connection: Meteor.Connection;
var userId: string;
function error(error: Error): void;
function stop(): void;
function onStop(func: Function): void;
function added(collection: string, id: string, fields: Object): void;
function changed(collection: string, id: string, fields: Object): void;
function removed(collection: string, id: string): void;
function ready(): void;
}
declare function ReactiveVar(initialValue: any, equalsFunc?: (oldVal:any, newVal:any)=>boolean): void;
declare module ReactiveVar {
function get(): any;
function set(newValue: any): void;
}
declare function Template(): void;
declare module Template {
var onCreated; /** TODO: add return value **/
var onRendered; /** TODO: add return value **/
var onDestroyed; /** TODO: add return value **/
var created: Function;
var rendered: Function;
var destroyed: Function;
var body: Meteor.TemplateBase;
function helpers(helpers:{[id:string]: any}): void;
function events(eventMap: {[actions: string]: Function}): void;
function instance(): Blaze.TemplateInstance;
function currentData(): {};
function parentData(numLevels?: number): {};
function registerHelper(name: string, helperFunction: Function): void;
}
declare function CompileStep(): void;
declare module CompileStep {
var inputSize; /** TODO: add return value **/
var inputPath; /** TODO: add return value **/
var fullInputPath; /** TODO: add return value **/
var pathForSourceMap; /** TODO: add return value **/
var packageName; /** TODO: add return value **/
var rootOutputPath; /** TODO: add return value **/
var arch; /** TODO: add return value **/
var fileOptions; /** TODO: add return value **/
var declaredExports; /** TODO: add return value **/
function read(n?: number); /** TODO: add return value **/
function addHtml(options: {
section?: string;
data?: string;
}); /** TODO: add return value **/
function addStylesheet(options: {
}, path: string, data: string, sourceMap: string); /** TODO: add return value **/
function addJavaScript(options: {
path?: string;
data?: string;
sourcePath?: string;
}); /** TODO: add return value **/
function addAsset(options: {
}, path: string, data: any /** Buffer **/ | string); /** TODO: add return value **/
function error(options: {
}, message: string, sourcePath?: string, line?: number, func?: string); /** TODO: add return value **/
}
declare function PackageAPI(): void;
declare module PackageAPI {
function use(packageNames: string | string[], architecture?: string, options?: {
weak?: boolean;
unordered?: Boolean;
}): void;
function imply(packageSpecs: string | string[]): void;
function addFiles(filename: string | string[], architecture?: string): void;
function versionsFrom(meteorRelease: string | string[]): void;
// function export(exportedObject: string, architecture?: string): void;
}
declare var Template: Meteor.TemplateBase;
declare var Session: Meteor.Session;
declare var Accounts: Meteor.Accounts;
declare var Match: Meteor.Match;
declare var EJSON: Meteor.EJSON;
declare var Tinytest: Meteor.Tinytest;