From 34b2fc23d8d72d11ff1a77bd9436a76816ba1acd Mon Sep 17 00:00:00 2001 From: Martin D Date: Tue, 27 Oct 2015 16:43:24 -0400 Subject: [PATCH 01/86] IconOptions to accept arrays and point objects All Leaflet methods and options that accept Point objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent: http://leafletjs.com/reference.html#point --- leaflet/leaflet.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 110bdd6f7..04f2da409 100755 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1088,7 +1088,7 @@ declare namespace L { /** * Size of the icon image in pixels. */ - iconSize?: Point; + iconSize?: Point|number[]; /** * The coordinates of the "tip" of the icon (relative to its top left corner). @@ -1096,7 +1096,7 @@ declare namespace L { * location. Centered by default if size is specified, also can be set in CSS * with negative margins. */ - iconAnchor?: Point; + iconAnchor?: Point|number[]; /** * The URL to the icon shadow image. If not specified, no shadow image will be @@ -1113,19 +1113,19 @@ declare namespace L { /** * Size of the shadow image in pixels. */ - shadowSize?: Point; + shadowSize?: Point|number[]; /** * The coordinates of the "tip" of the shadow (relative to its top left corner) * (the same as iconAnchor if not specified). */ - shadowAnchor?: Point; + shadowAnchor?: Point|number[]; /** * The coordinates of the point from which popups will "open", relative to the * icon anchor. */ - popupAnchor?: Point; + popupAnchor?: Point|number[]; /** * A custom class name to assign to both icon and shadow images. Empty by default. From 7464746d91f97560fc0975abc497bf745fd7cd36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Poul=20Kjeldager=20S=C3=B8rensen?= Date: Thu, 29 Oct 2015 12:31:11 +0100 Subject: [PATCH 02/86] Create three-FirstPersonControls.d.ts --- threejs/three-FirstPersonControls.d.ts | 33 ++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 threejs/three-FirstPersonControls.d.ts diff --git a/threejs/three-FirstPersonControls.d.ts b/threejs/three-FirstPersonControls.d.ts new file mode 100644 index 000000000..355ce1e69 --- /dev/null +++ b/threejs/three-FirstPersonControls.d.ts @@ -0,0 +1,33 @@ +Source : https://github.com/NTaylorMullen/CycleR/blob/master/CycleR/CycleR.Game.Client/Client/Interfaces/ThreeJS/Cameras/FirstPersonControls.d.ts + +interface IFirstPersonControls { + object: IObject3D; + target: IVector3; + domElement: HTMLCanvasElement; + movementSpeed: number; + lookSpeed: number; + noFly: bool; + lookVertical: bool; + autoForward: bool; + activeLook: bool; + heightSpeed: bool; + heightCoef: number; + heightMin: number; + constrainVertical: bool; + verticalMin: number; + verticalMax: number; + autoSpeedFactor: number; + mouseX: number; + mouseY: number; + lat: number; + lon: number; + phi: number; + theta: number; + moveForward: bool; + moveBackward: bool; + moveLeft: bool; + moveRight: bool; + freeze: bool; + mouseDragOn: bool; + update(delta?: number): void; +} From f55e5666a28ecee6941dda592a903b1ff5aa0c9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Poul=20Kjeldager=20S=C3=B8rensen?= Date: Thu, 29 Oct 2015 12:38:34 +0100 Subject: [PATCH 03/86] fixed build errors from copied source --- threejs/three-FirstPersonControls.d.ts | 37 ++++++++++++++------------ 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/threejs/three-FirstPersonControls.d.ts b/threejs/three-FirstPersonControls.d.ts index 355ce1e69..b5c1f7e1e 100644 --- a/threejs/three-FirstPersonControls.d.ts +++ b/threejs/three-FirstPersonControls.d.ts @@ -1,19 +1,22 @@ -Source : https://github.com/NTaylorMullen/CycleR/blob/master/CycleR/CycleR.Game.Client/Client/Interfaces/ThreeJS/Cameras/FirstPersonControls.d.ts +//Source : https://github.com/NTaylorMullen/CycleR/blob/master/CycleR/CycleR.Game.Client/Client/Interfaces/ThreeJS/Cameras/FirstPersonControls.d.ts +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// interface IFirstPersonControls { - object: IObject3D; - target: IVector3; + object: Object3D; + target: Vector3; domElement: HTMLCanvasElement; movementSpeed: number; lookSpeed: number; - noFly: bool; - lookVertical: bool; - autoForward: bool; - activeLook: bool; - heightSpeed: bool; - heightCoef: number; - heightMin: number; - constrainVertical: bool; + noFly: boolean; + lookVertical: boolean; + autoForward: boolean; + activeLook: boolean; + heightSpeed: boolean; + heightCoef: boolean; + heightMin: boolean; + constrainVertical: boolean; verticalMin: number; verticalMax: number; autoSpeedFactor: number; @@ -23,11 +26,11 @@ interface IFirstPersonControls { lon: number; phi: number; theta: number; - moveForward: bool; - moveBackward: bool; - moveLeft: bool; - moveRight: bool; - freeze: bool; - mouseDragOn: bool; + moveForward: boolean; + moveBackward: boolean; + moveLeft: boolean; + moveRight: boolean; + freeze: boolean; + mouseDragOn: boolean; update(delta?: number): void; } From 1df845d46b911d23abde00af0ebe5de3e181a93b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Poul=20Kjeldager=20S=C3=B8rensen?= Date: Thu, 29 Oct 2015 12:54:38 +0100 Subject: [PATCH 04/86] changed interface to class declaration --- threejs/three-FirstPersonControls.d.ts | 67 ++++++++++++++------------ 1 file changed, 35 insertions(+), 32 deletions(-) diff --git a/threejs/three-FirstPersonControls.d.ts b/threejs/three-FirstPersonControls.d.ts index b5c1f7e1e..32d9b6791 100644 --- a/threejs/three-FirstPersonControls.d.ts +++ b/threejs/three-FirstPersonControls.d.ts @@ -1,36 +1,39 @@ -//Source : https://github.com/NTaylorMullen/CycleR/blob/master/CycleR/CycleR.Game.Client/Client/Interfaces/ThreeJS/Cameras/FirstPersonControls.d.ts +// Type definitions for three.js // Definitions: https://github.com/borisyankov/DefinitelyTyped +//Source : https://github.com/NTaylorMullen/CycleR/blob/master/CycleR/CycleR.Game.Client/Client/Interfaces/ThreeJS/Cameras/FirstPersonControls.d.ts /// - -interface IFirstPersonControls { - object: Object3D; - target: Vector3; - domElement: HTMLCanvasElement; - movementSpeed: number; - lookSpeed: number; - noFly: boolean; - lookVertical: boolean; - autoForward: boolean; - activeLook: boolean; - heightSpeed: boolean; - heightCoef: boolean; - heightMin: boolean; - constrainVertical: boolean; - verticalMin: number; - verticalMax: number; - autoSpeedFactor: number; - mouseX: number; - mouseY: number; - lat: number; - lon: number; - phi: number; - theta: number; - moveForward: boolean; - moveBackward: boolean; - moveLeft: boolean; - moveRight: boolean; - freeze: boolean; - mouseDragOn: boolean; - update(delta?: number): void; +declare module THREE { + class FirstPersonControls { + constructor(object: Camera, domElement?: HTMLElement); + object: THREE.Object3D; + target: THREE.Vector3; + domElement: HTMLCanvasElement; + movementSpeed: number; + lookSpeed: number; + noFly: boolean; + lookVertical: boolean; + autoForward: boolean; + activeLook: boolean; + heightSpeed: boolean; + heightCoef: boolean; + heightMin: boolean; + constrainVertical: boolean; + verticalMin: number; + verticalMax: number; + autoSpeedFactor: number; + mouseX: number; + mouseY: number; + lat: number; + lon: number; + phi: number; + theta: number; + moveForward: boolean; + moveBackward: boolean; + moveLeft: boolean; + moveRight: boolean; + freeze: boolean; + mouseDragOn: boolean; + update(delta?: number): void; + } } From 37dc9544a2afc14bb76745d61a7903125c3696d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Poul=20Kjeldager=20S=C3=B8rensen?= Date: Thu, 29 Oct 2015 14:21:50 +0100 Subject: [PATCH 05/86] fixed header --- threejs/three-FirstPersonControls.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/threejs/three-FirstPersonControls.d.ts b/threejs/three-FirstPersonControls.d.ts index 32d9b6791..d59fd3459 100644 --- a/threejs/three-FirstPersonControls.d.ts +++ b/threejs/three-FirstPersonControls.d.ts @@ -1,4 +1,6 @@ // Type definitions for three.js +// Project: http://mrdoob.github.com/three.js/ +// Definitions by: Poul Kjeldager Sørensen // Definitions: https://github.com/borisyankov/DefinitelyTyped //Source : https://github.com/NTaylorMullen/CycleR/blob/master/CycleR/CycleR.Game.Client/Client/Interfaces/ThreeJS/Cameras/FirstPersonControls.d.ts From 5fa991766aa3b0d7ca3ead189993252ff7231ebf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Poul=20Kjeldager=20S=C3=B8rensen?= Date: Thu, 29 Oct 2015 14:26:40 +0100 Subject: [PATCH 06/86] fixed name --- threejs/three-FirstPersonControls.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/threejs/three-FirstPersonControls.d.ts b/threejs/three-FirstPersonControls.d.ts index d59fd3459..3e34b9e45 100644 --- a/threejs/three-FirstPersonControls.d.ts +++ b/threejs/three-FirstPersonControls.d.ts @@ -1,6 +1,6 @@ // Type definitions for three.js // Project: http://mrdoob.github.com/three.js/ -// Definitions by: Poul Kjeldager Sørensen +// Definitions by: Poul Kjeldager Sørensen // Definitions: https://github.com/borisyankov/DefinitelyTyped //Source : https://github.com/NTaylorMullen/CycleR/blob/master/CycleR/CycleR.Game.Client/Client/Interfaces/ThreeJS/Cameras/FirstPersonControls.d.ts From b5f4a47c028a5cee5b38389eddb46f75d73c1e98 Mon Sep 17 00:00:00 2001 From: Eric Nicholson Date: Thu, 29 Oct 2015 09:54:55 -0400 Subject: [PATCH 07/86] Fixed existing definitions for SQS and added missing definitions --- aws-sdk/aws-sdk-tests.ts | 253 ++++++++++++++++++++++++++++- aws-sdk/aws-sdk-tests.ts.tscparams | 1 + aws-sdk/aws-sdk.d.ts | 211 +++++++++++++++++------- 3 files changed, 405 insertions(+), 60 deletions(-) create mode 100644 aws-sdk/aws-sdk-tests.ts.tscparams diff --git a/aws-sdk/aws-sdk-tests.ts b/aws-sdk/aws-sdk-tests.ts index 8a3464a6d..7411beb93 100644 --- a/aws-sdk/aws-sdk-tests.ts +++ b/aws-sdk/aws-sdk-tests.ts @@ -1,13 +1,256 @@ /// -import awsSdk = require('aws-sdk'); +import AWS = require('aws-sdk'); var str: string; -var creds: awsSdk.Credentials; +var creds: AWS.Credentials; -creds = new awsSdk.Credentials(str, str); -creds = new awsSdk.Credentials(str, str, str); +creds = new AWS.Credentials(str, str); +creds = new AWS.Credentials(str, str, str); str = creds.accessKeyId; -// more + +/* + * SQS + */ +var sqs:AWS.SQS + +//Default constructor +sqs = new AWS.SQS(); + +//Locking the API Version +sqs = new AWS.SQS({apiVersion: '2012-11-05'}); + +// Locking the API Version Globally +AWS.config.apiVersions = { + sqs: '2012-11-05', + // other service API versions +}; + +sqs.addPermission({ + AWSAccountIds: [ /* required */ + 'STRING_VALUE', + /* more items */ + ], + Actions: [ /* required */ + 'STRING_VALUE', + /* more items */ + ], + Label: 'STRING_VALUE', /* required */ + QueueUrl: 'STRING_VALUE' /* required */ + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.changeMessageVisibility({ + QueueUrl: 'STRING_VALUE', /* required */ + ReceiptHandle: 'STRING_VALUE', /* required */ + VisibilityTimeout: 0 /* required */ + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.changeMessageVisibilityBatch({ + Entries: [ /* required */ + { + Id: 'STRING_VALUE', /* required */ + ReceiptHandle: 'STRING_VALUE', /* required */ + VisibilityTimeout: 0 + }, + /* more items */ + ], + QueueUrl: 'STRING_VALUE' /* required */ + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.createQueue({ + QueueName: 'STRING_VALUE', /* required */ + Attributes: { + someKey: 'STRING_VALUE', + /* anotherKey: ... */ + } + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.deleteMessage({ + QueueUrl: 'STRING_VALUE', /* required */ + ReceiptHandle: 'STRING_VALUE' /* required */ + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.deleteMessageBatch({ + Entries: [ /* required */ + { + Id: 'STRING_VALUE', /* required */ + ReceiptHandle: 'STRING_VALUE' /* required */ + }, + /* more items */ + ], + QueueUrl: 'STRING_VALUE' /* required */ + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.deleteQueue({ + QueueUrl: 'STRING_VALUE' /* required */ + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.getQueueAttributes({ + QueueUrl: 'STRING_VALUE', /* required */ + AttributeNames: [ + 'Policy | VisibilityTimeout | MaximumMessageSize | MessageRetentionPeriod | ApproximateNumberOfMessages | ApproximateNumberOfMessagesNotVisible | CreatedTimestamp | LastModifiedTimestamp | QueueArn | ApproximateNumberOfMessagesDelayed | DelaySeconds | ReceiveMessageWaitTimeSeconds | RedrivePolicy', + /* more items */ + ] + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.getQueueUrl({ + QueueName: 'STRING_VALUE', /* required */ + QueueOwnerAWSAccountId: 'STRING_VALUE' + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.listDeadLetterSourceQueues({ + QueueUrl: 'STRING_VALUE' /* required */ + }, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.listQueues({ + QueueNamePrefix: 'STRING_VALUE' + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.purgeQueue({ + QueueUrl: 'STRING_VALUE' /* required */ + }, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.receiveMessage({ + QueueUrl: 'STRING_VALUE', /* required */ + AttributeNames: [ + 'Policy | VisibilityTimeout | MaximumMessageSize | MessageRetentionPeriod | ApproximateNumberOfMessages | ApproximateNumberOfMessagesNotVisible | CreatedTimestamp | LastModifiedTimestamp | QueueArn | ApproximateNumberOfMessagesDelayed | DelaySeconds | ReceiveMessageWaitTimeSeconds | RedrivePolicy', + /* more items */ + ], + MaxNumberOfMessages: 0, + MessageAttributeNames: [ + 'STRING_VALUE', + /* more items */ + ], + VisibilityTimeout: 0, + WaitTimeSeconds: 0 + }, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.removePermission({ + Label: 'STRING_VALUE', /* required */ + QueueUrl: 'STRING_VALUE' /* required */ + }, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.sendMessage({ + MessageBody: 'STRING_VALUE', /* required */ + QueueUrl: 'STRING_VALUE', /* required */ + DelaySeconds: 0, + MessageAttributes: { + someKey: { + DataType: 'STRING_VALUE', /* required */ + BinaryListValues: [ + new Buffer('...') || 'STRING_VALUE', + /* more items */ + ], + BinaryValue: new Buffer('...') || 'STRING_VALUE', + StringListValues: [ + 'STRING_VALUE', + /* more items */ + ], + StringValue: 'STRING_VALUE' + }, + /* anotherKey: ... */ + } + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.sendMessageBatch({ + Entries: [ /* required */ + { + Id: 'STRING_VALUE', /* required */ + MessageBody: 'STRING_VALUE', /* required */ + DelaySeconds: 0, + MessageAttributes: { + someKey: { + DataType: 'STRING_VALUE', /* required */ + BinaryListValues: [ + new Buffer('...') , + /* more items */ + ], + BinaryValue: new Buffer('...'), + StringListValues: [ + 'STRING_VALUE', + /* more items */ + ], + StringValue: 'STRING_VALUE' + }, + /* anotherKey: ... */ + } + }, + /* more items */ + ], + QueueUrl: 'STRING_VALUE' /* required */ + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +sqs.setQueueAttributes({ + Attributes: { /* required */ + someKey: 'STRING_VALUE', + /* anotherKey: ... */ + }, + QueueUrl: 'STRING_VALUE' /* required */ + }, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + + \ No newline at end of file diff --git a/aws-sdk/aws-sdk-tests.ts.tscparams b/aws-sdk/aws-sdk-tests.ts.tscparams new file mode 100644 index 000000000..70401a77e --- /dev/null +++ b/aws-sdk/aws-sdk-tests.ts.tscparams @@ -0,0 +1 @@ +--noImplicitAny --module commonjs --target es5 \ No newline at end of file diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 3a500bbbb..128341729 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -30,6 +30,16 @@ declare module "aws-sdk" { xhrAsync?: boolean; xhrWithCredentials?: boolean; } + + export class Endpoint { + constructor(endpoint:string); + + host:string; + hostname:string; + href:string; + port:number; + protocol:string; + } export interface Services { autoscaling?: any; @@ -99,7 +109,25 @@ declare module "aws-sdk" { export class SQS { constructor(options?: any); - public client: Sqs.Client; + endpoint:Endpoint; + + addPermission(params: SQS.AddPermissionParams, callback: (err:Error, data:any) => void): void; + changeMessageVisibility(params: SQS.ChangeMessageVisibilityParams, callback: (err:Error, data:any) => void): void; + changeMessageVisibilityBatch(params: SQS.ChangeMessageVisibilityBatchParams, callback: (err:Error, data:SQS.ChangeMessageVisibilityBatchResponse) => void): void; + createQueue(params: SQS.CreateQueueParams, callback: (err: Error, data: SQS.CreateQueueResult) => void): void; + deleteMessage(params: SQS.DeleteMessageParams, callback: (err: Error, data: any) => void): void; + deleteMessageBatch(params: SQS.DeleteMessageBatchParams, callback: (err: Error, data: SQS.DeleteMessageBatchResult) => void): void; + deleteQueue(params: { QueueUrl: string; }, callback: (err: Error, data: any) => void): void; + getQueueAttributes(params: SQS.GetQueueAttributesParams, callback: (err: Error, data: SQS.GetQueueAttributesResult) => void): void; + getQueueUrl(params: SQS.GetQueueUrlParams, callback: (err: Error, data: { QueueUrl: string; }) => void): void; + listDeadLetterSourceQueues(params: {QueueUrl:string}, callback: (err: Error, data: {queueUrls: string[]}) => void): void; + listQueues(params: {QueueNamePrefix?:string}, callback: (err: Error, data: {QueueUrls: string[]}) => void): void; + purgeQueue(params: {QueueUrl: string}, callback: (err: Error, data: any) => void): void; + receiveMessage(params: SQS.ReceiveMessageParams, callback: (err: Error, data: SQS.ReceiveMessageResult) => void): void; + removePermission(params: {QueueUrl: string, Label: string}, callback: (err: Error, data: any) => void): void; + sendMessage(params: SQS.SendMessageParams, callback: (err: Error, data: SQS.SendMessageResult) => void): void; + sendMessageBatch(params: SQS.SendMessageBatchParams, callback: (err: Error, data: SQS.SendMessageBatchResult) => void): void; + setQueueAttributes(params: SQS.SetQueueAttributesParams, callback: (err: Error, data: any) => void): void; } export class SES { @@ -126,36 +154,77 @@ declare module "aws-sdk" { constructor(options?: any); } - export module Sqs { - - export interface Client { - config: ClientConfig; - - sendMessage(params: SendMessageRequest, callback: (err: any, data: SendMessageResult) => void): void; - sendMessageBatch(params: SendMessageBatchRequest, callback: (err: any, data: SendMessageBatchResult) => void): void; - receiveMessage(params: ReceiveMessageRequest, callback: (err: any, data: ReceiveMessageResult) => void): void; - deleteMessage(params: DeleteMessageRequest, callback: (err: any, data: any) => void): void; - deleteMessageBatch(params: DeleteMessageBatchRequest, callback: (err: any, data: DeleteMessageBatchResult) => void): void; - createQueue(params: CreateQueueRequest, callback: (err: any, data: CreateQueueResult) => void): void; - deleteQueue(params: DeleteQueueRequest, callback: (err: any, data: any) => void): void; + export module SQS { + + export interface SqsOptions { + params?: any; + endpoint?: string; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: Credentials; + credentials?: Credentials; + credentialProvider?: any; + region?: string; + maxRetries?: number; + maxRedirects?: number; + sslEnabled?: boolean; + paramValidation?: boolean; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + correctClockSkew?: boolean; + s3ForcePathStyle?: boolean; + s3BucketEndpoint?: boolean; + httpOptions?: HttpOptions; + apiVersion?: string; + apiVersions?: { [serviceName:string]: string}; + logger?: Logger; + systemClockOffset?: number; + signatureVersion?: string; + signatureCache?: boolean; + } + + export interface AddPermissionParams { + QueueUrl: string; + Label: string; + AWSAccountIds:string[]; + Actions:string[]; + } + + export interface ChangeMessageVisibilityParams { + QueueUrl: string, + ReceiptHandle: string, + VisibilityTimeout: number + } + + export interface ChangeMessageVisibilityBatchParams { + QueueUrl: string, + Entries: { Id: string; ReceiptHandle: string; VisibilityTimeout?: number; }[] + } + + export interface ChangeMessageVisibilityBatchResponse { + Successful: { Id:string }[]; + Failed: BatchResultErrorEntry[]; } - export interface SendMessageRequest { - QueueUrl?: string; - MessageBody?: string; + export interface SendMessageParams { + QueueUrl: string; + MessageBody: string; DelaySeconds?: number; + MessageAttributes?: { [name:string]: MessageAttribute; } } - export interface ReceiveMessageRequest { - QueueUrl?: string; + export interface ReceiveMessageParams { + QueueUrl: string; MaxNumberOfMessages?: number; VisibilityTimeout?: number; AttributeNames?: string[]; + MessageAttributeNames?: string[]; + WaitTimeSeconds?:number; } - export interface DeleteMessageBatchRequest { - QueueUrl?: string; - Entries?: DeleteMessageBatchRequestEntry[]; + export interface DeleteMessageBatchParams { + QueueUrl: string; + Entries: DeleteMessageBatchRequestEntry[]; } export interface DeleteMessageBatchRequestEntry { @@ -163,85 +232,117 @@ declare module "aws-sdk" { ReceiptHandle: string; } - export interface DeleteMessageRequest { - QueueUrl?: string; - ReceiptHandle?: string; + export interface DeleteMessageParams { + QueueUrl: string; + ReceiptHandle: string; } - export class Attribute { - Name: string; - Value: string; + export interface SendMessageBatchParams { + QueueUrl: string; + Entries: SendMessageBatchRequestEntry[]; } - export interface SendMessageBatchRequest { - QueueUrl?: string; - Entries?: SendMessageBatchRequestEntry[]; - } - - export class SendMessageBatchRequestEntry { + export interface SendMessageBatchRequestEntry { Id: string; MessageBody: string; - DelaySeconds: number; - } - - export interface CreateQueueRequest { - QueueName?: string; - DefaultVisibilityTimeout?: number; DelaySeconds?: number; - Attributes?: Attribute[]; + MessageAttributes?: { [name:string]: MessageAttribute; } } - export interface DeleteQueueRequest { - QueueUrl?: string; + export interface CreateQueueParams { + QueueName: string; + Attributes: QueueAttributes; } - - export class SendMessageResult { + + export interface QueueAttributes { + [name:string]: any; + DelaySeconds?: number; + MaximumMessageSize?: number; + MessageRetentionPeriod?: number; + Policy?: any; + ReceiveMessageWaitTimeSeconds?: number; + VisibilityTimeout?: number; + RedrivePolicy?: any; + } + + export interface GetQueueAttributesParams { + QueueUrl: string; + AttributeNames: string[]; + } + + export interface GetQueueAttributesResult { + Attributes: {[name:string]: string}; + } + + export interface GetQueueUrlParams { + QueueName: string; + QueueOwnerAWSAccountId?: string; + } + + export interface SendMessageResult { MessageId: string; MD5OfMessageBody: string; + MD5OfMessageAttributes: string; } - export class ReceiveMessageResult { + export interface ReceiveMessageResult { Messages: Message[]; } - export class Message { + export interface Message { MessageId: string; ReceiptHandle: string; MD5OfBody: string; Body: string; - Attributes: Attribute[]; + Attributes: { [name:string]:any }; + MD5OfMessageAttributes:string; + MessageAttributes: { [name:string]: MessageAttribute; } } - export class DeleteMessageBatchResult { + export interface MessageAttribute { + StringValue?: string; + BinaryValue?: any; //(Buffer, Typed Array, Blob, String) + StringListValues?: string[]; + BinaryListValues?: any[]; + DataType: string; + } + + export interface DeleteMessageBatchResult { Successful: DeleteMessageBatchResultEntry[]; Failed: BatchResultErrorEntry[]; } - export class DeleteMessageBatchResultEntry { + export interface DeleteMessageBatchResultEntry { Id: string; } - export class BatchResultErrorEntry { + export interface BatchResultErrorEntry { Id: string; Code: string; - Message: string; - SenderFault: string; + Message?: string; + SenderFault: boolean; } - export class SendMessageBatchResult { + export interface SendMessageBatchResult { Successful: SendMessageBatchResultEntry[]; Failed: BatchResultErrorEntry[]; } - export class SendMessageBatchResultEntry { + export interface SendMessageBatchResultEntry { Id: string; MessageId: string; MD5OfMessageBody: string; + MD5OfMessageAttributes:string; } - export class CreateQueueResult { + export interface CreateQueueResult { QueueUrl: string; } + + export interface SetQueueAttributesParams { + QueueUrl: string; + Attributes: QueueAttributes; + } } From edc40d8db0533f5133662645d27045a5b340f28c Mon Sep 17 00:00:00 2001 From: kwiateusz Date: Tue, 3 Nov 2015 09:14:55 +0100 Subject: [PATCH 08/86] Update of ScrollToParameterOptions in mCustomScrollbar.d.ts --- mCustomScrollbar/mCustomScrollbar.d.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/mCustomScrollbar/mCustomScrollbar.d.ts b/mCustomScrollbar/mCustomScrollbar.d.ts index f41aca00a..6ce44b23c 100644 --- a/mCustomScrollbar/mCustomScrollbar.d.ts +++ b/mCustomScrollbar/mCustomScrollbar.d.ts @@ -132,10 +132,18 @@ declare module MCustomScrollbar { */ scrollInertia?: number; /** ++ * Scroll-to animation easing, values: "linear", "easeOut", "easeInOut". ++ */ ++ scrollEasing?: string; ++ /** * Scroll scrollbar dragger (instead of content) to a number of pixels, values: true, false */ moveDragger?: boolean; /** ++ * Set a timeout for the method (the default timeout is 60 ms in order to work with automatic scrollbar update), value in milliseconds. ++ */ ++ timeout?: number; + /** * Trigger user defined callback after scroll-to completes, value: true, false */ callbacks?: boolean; @@ -163,4 +171,4 @@ interface JQuery { * @param options Override default options */ mCustomScrollbar(options?: MCustomScrollbar.CustomScrollbarOptions): JQuery; -} \ No newline at end of file +} From 7ca9b69f1cdff8bb1807210e86273da958783bb9 Mon Sep 17 00:00:00 2001 From: Julien Evano Date: Tue, 3 Nov 2015 19:43:16 +1100 Subject: [PATCH 09/86] ionic framework: static ionic.Platform utility Add the static ionic.Platform utility according to the API documentation (http://ionicframework.com/docs/api/utility/ionic.Platform/) --- ionic/ionic-tests.ts | 55 +++++++++++++++++++++++------ ionic/ionic.d.ts | 82 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+), 11 deletions(-) diff --git a/ionic/ionic-tests.ts b/ionic/ionic-tests.ts index 45d8c2d66..34dfade4a 100644 --- a/ionic/ionic-tests.ts +++ b/ionic/ionic-tests.ts @@ -102,7 +102,7 @@ class IonicTestController { } private testGesture(): void { var gesture: ionic.gestures.IonicGesture = this.$ionicGesture.on( - 'eventType', + 'eventType', (e)=>{ return e; }, angular.element("body"), {} @@ -226,7 +226,7 @@ class IonicTestController { cssClass: "cssClass", template: "template", templateUrl: "templateUrl", - okText: "OK", + okText: "OK", okType: "okType" }).then(() => console.log("popover shown")) this.$ionicPopup.alert({ @@ -235,7 +235,7 @@ class IonicTestController { cssClass: "cssClass", template: "template", templateUrl: "templateUrl", - okText: "OK", + okText: "OK", okType: "okType" }).close(); @@ -245,9 +245,9 @@ class IonicTestController { cssClass: "cssClass", template: "template", templateUrl: "templateUrl", - okText: "OK", + okText: "OK", okType: "okType", - cancelText: "Cancel", + cancelText: "Cancel", cancelType: "cancelType" }).then(() => console.log("popover shown")) this.$ionicPopup.confirm({ @@ -256,9 +256,9 @@ class IonicTestController { cssClass: "cssClass", template: "template", templateUrl: "templateUrl", - okText: "OK", + okText: "OK", okType: "okType", - cancelText: "Cancel", + cancelText: "Cancel", cancelType: "cancelType" }).close(); @@ -268,9 +268,9 @@ class IonicTestController { cssClass: "cssClass", template: "template", templateUrl: "templateUrl", - okText: "OK", + okText: "OK", okType: "okType", - cancelText: "Cancel", + cancelText: "Cancel", cancelType: "cancelType", inputType: "text", inputPlaceholder: "Type some text..." @@ -281,9 +281,9 @@ class IonicTestController { cssClass: "cssClass", template: "template", templateUrl: "templateUrl", - okText: "OK", + okText: "OK", okType: "okType", - cancelText: "Cancel", + cancelText: "Cancel", cancelType: "cancelType", inputType: "text", inputPlaceholder: "Type some text..." @@ -359,6 +359,39 @@ class IonicTestController { var {top: number, left: number, width: number, height: number} = this.$ionicPositionService.position(angular.element("body")); var {top: number, left: number, width: number, height: number} = this.$ionicPositionService.offset(angular.element("body")); } + + /** + * ionic.version + */ + private testStaticVersion(): void { + var version: string = ionic.version; + } + + /** + * ionic.Platform + */ + private testStaticPlaform(): void { + var ready: void = ionic.Platform.ready(function() { + }); + var setGrade: void = ionic.Platform.setGrade('iOS'); + var deviceInformation: string = ionic.Platform.device(); + var isWebView: boolean = ionic.Platform.isWebView(); + var isIPad: boolean = ionic.Platform.isIPad(); + var isIOS: boolean = ionic.Platform.isIOS(); + var isAndroid: boolean = ionic.Platform.isAndroid(); + var isWindowsPhone: boolean = ionic.Platform.isWindowsPhone(); + var currentPlatform: string = ionic.Platform.platform(); + var currentPlatformVersion: number = ionic.Platform.version(); + var exitApp: void = ionic.Platform.exitApp(); + var showStatusBar: void = ionic.Platform.showStatusBar(true); + var showStatusBar: void = ionic.Platform.fullScreen(); + showStatusBar = ionic.Platform.fullScreen(true); + showStatusBar = ionic.Platform.fullScreen(true, true); + var isReady: boolean = ionic.Platform.isReady; + var isFullScreen: boolean = ionic.Platform.isFullScreen; + var platforms: Array = ionic.Platform.platforms; + var grade: string = ionic.Platform.grade; + } } testIonic.controller('ionicTestController', IonicTestController); diff --git a/ionic/ionic.d.ts b/ionic/ionic.d.ts index 239f775c5..774102c95 100644 --- a/ionic/ionic.d.ts +++ b/ionic/ionic.d.ts @@ -6,7 +6,89 @@ /// interface IonicStatic { + /** + * What Ionic package version is. + */ version: string; + Platform: { + /** + * Trigger a callback once the device is ready, or immediately + * if the device is already ready. This method can be run from + * anywhere and does not need to be wrapped by any additonal methods. + * When the app is within a WebView (Cordova), it’ll fire + * the callback once the device is ready. If the app is within + * a web browser, it’ll fire the callback after window.load. + * Please remember that Cordova features (Camera, FileSystem, etc) still + * will not work in a web browser. + */ + ready(callback: ()=>void): void; + /** + * Set the grade of the device: ‘a’, ‘b’, or ‘c’. ‘a’ is the best + * (most css features enabled), ‘c’ is the worst. By default, sets the grade + * depending on the current device. + */ + setGrade(grade: string): void; + /** + * Return the current device (given by cordova). + */ + device(): any; + /** + * Check if we are running within a WebView (such as Cordova). + */ + isWebView(): boolean; + /** + * Whether we are running on iPad. + */ + isIPad(): boolean; + /** + * Whether we are running on iOS. + */ + isIOS(): boolean; + /** + * Whether we are running on Android. + */ + isAndroid(): boolean; + /** + * Whether we are running on Windows Phone. + */ + isWindowsPhone(): boolean; + /** + * The name of the current platform. + */ + platform(): string; + /** + * The version of the current device platform. + */ + version(): number; + /** + * Exit the app. + */ + exitApp(): void; + /** + * Shows or hides the device status bar (in Cordova). Requires cordova plugin add org.apache.cordova.statusbar + */ + showStatusBar(shouldShow: boolean): void; + /** + * Sets whether the app is fullscreen or not (in Cordova). + */ + fullScreen(showFullScreen?: boolean, showStatusBar?: boolean): void; + /** + * Whether the device is ready. + */ + isReady: boolean; + /** + * Whether the device is fullscreen. + */ + isFullScreen: boolean; + /** + * An array of all platforms found. + */ + platforms: Array; + /** + * What grade the current platform is. + */ + grade: string; + }; } declare var ionic: IonicStatic; From bba57a40b89062582a9a23248e625c75db0392c6 Mon Sep 17 00:00:00 2001 From: Julien Evano Date: Tue, 3 Nov 2015 19:46:56 +1100 Subject: [PATCH 10/86] style(ionic framework): adjust 4 spaces identation --- ionic/ionic-tests.ts | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/ionic/ionic-tests.ts b/ionic/ionic-tests.ts index 34dfade4a..e6e8ab0d5 100644 --- a/ionic/ionic-tests.ts +++ b/ionic/ionic-tests.ts @@ -364,33 +364,33 @@ class IonicTestController { * ionic.version */ private testStaticVersion(): void { - var version: string = ionic.version; + var version: string = ionic.version; } /** * ionic.Platform */ private testStaticPlaform(): void { - var ready: void = ionic.Platform.ready(function() { - }); - var setGrade: void = ionic.Platform.setGrade('iOS'); - var deviceInformation: string = ionic.Platform.device(); - var isWebView: boolean = ionic.Platform.isWebView(); - var isIPad: boolean = ionic.Platform.isIPad(); - var isIOS: boolean = ionic.Platform.isIOS(); - var isAndroid: boolean = ionic.Platform.isAndroid(); - var isWindowsPhone: boolean = ionic.Platform.isWindowsPhone(); - var currentPlatform: string = ionic.Platform.platform(); - var currentPlatformVersion: number = ionic.Platform.version(); - var exitApp: void = ionic.Platform.exitApp(); - var showStatusBar: void = ionic.Platform.showStatusBar(true); - var showStatusBar: void = ionic.Platform.fullScreen(); - showStatusBar = ionic.Platform.fullScreen(true); - showStatusBar = ionic.Platform.fullScreen(true, true); - var isReady: boolean = ionic.Platform.isReady; - var isFullScreen: boolean = ionic.Platform.isFullScreen; - var platforms: Array = ionic.Platform.platforms; - var grade: string = ionic.Platform.grade; + var ready: void = ionic.Platform.ready(function() { + }); + var setGrade: void = ionic.Platform.setGrade('iOS'); + var deviceInformation: string = ionic.Platform.device(); + var isWebView: boolean = ionic.Platform.isWebView(); + var isIPad: boolean = ionic.Platform.isIPad(); + var isIOS: boolean = ionic.Platform.isIOS(); + var isAndroid: boolean = ionic.Platform.isAndroid(); + var isWindowsPhone: boolean = ionic.Platform.isWindowsPhone(); + var currentPlatform: string = ionic.Platform.platform(); + var currentPlatformVersion: number = ionic.Platform.version(); + var exitApp: void = ionic.Platform.exitApp(); + var showStatusBar: void = ionic.Platform.showStatusBar(true); + var showStatusBar: void = ionic.Platform.fullScreen(); + showStatusBar = ionic.Platform.fullScreen(true); + showStatusBar = ionic.Platform.fullScreen(true, true); + var isReady: boolean = ionic.Platform.isReady; + var isFullScreen: boolean = ionic.Platform.isFullScreen; + var platforms: Array = ionic.Platform.platforms; + var grade: string = ionic.Platform.grade; } } From 0d3e55398e5f631856ea20b73fda270ff0f00350 Mon Sep 17 00:00:00 2001 From: James O'Cull Date: Tue, 3 Nov 2015 15:46:39 -0500 Subject: [PATCH 11/86] Added optional type information for the Sequelize's import define function --- sequelize/sequelize.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index a0a567eca..3a80498c0 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -5442,8 +5442,11 @@ declare module "sequelize" { * * @param path The path to the file that holds the model you want to import. If the part is relative, it * will be resolved relatively to the calling file + * + * @param defineFunction An optional function that provides model definitions. Useful if you do not + * want to use the module root as the define function */ - import( path : string ) : Model; + import( path : string, defineFunction? : (Sequelize, DataTypes) => Model ) : Model; /** * Execute a query on the DB, with the posibility to bypass all the sequelize goodness. From 0e217b947f9d1f2702777ed629de750952220df8 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Wed, 4 Nov 2015 09:28:26 -0700 Subject: [PATCH 12/86] Expose interfaces in BrowserSync.d.ts --- browser-sync/browser-sync-tests.ts | 4 +- browser-sync/browser-sync.d.ts | 791 +++++++++++++++-------------- 2 files changed, 398 insertions(+), 397 deletions(-) diff --git a/browser-sync/browser-sync-tests.ts b/browser-sync/browser-sync-tests.ts index 50042410f..98151772f 100644 --- a/browser-sync/browser-sync-tests.ts +++ b/browser-sync/browser-sync-tests.ts @@ -78,8 +78,8 @@ bs.init({ }); bs.reload(); - -function browserSyncInit() { + +function browserSyncInit(): browserSync.BrowserSyncInstance { var browser = browserSync.create(); browser.init(); console.log(browser.name); diff --git a/browser-sync/browser-sync.d.ts b/browser-sync/browser-sync.d.ts index 03b751fab..77ae2ce35 100644 --- a/browser-sync/browser-sync.d.ts +++ b/browser-sync/browser-sync.d.ts @@ -11,404 +11,405 @@ declare module "browser-sync" { import fs = require("fs"); import http = require("http"); - interface Options { - /** - * Browsersync includes a user-interface that is accessed via a separate port. The UI allows to controls - * all devices, push sync updates and much more. - * - * port - Default: 3001 - * weinre.port - Default: 8080 - * Note: requires at least version 2.0.0 - */ - ui?: UIOptions; - /** - * Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS - * & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob - * patterns. - * Default: false - */ - files?: string | string[]; - /** - * File watching options that get passed along to Chokidar. Check their docs for available options - * Default: undefined - * Note: requires at least version 2.6.0 - */ - watchOptions?: ChokidarOptions; - /** - * Use the built-in static server for basic HTML/JS/CSS websites. - * Default: false - */ - server?: ServerOptions; - /** - * Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site. - * target - Default: undefined - * ws - Default: undefined - * middleware - Default: undefined - * reqHeaders - Default: undefined - * proxyRes - Default: undefined - */ - proxy?: string | boolean | ProxyOptions; - /** - * Use a specific port (instead of the one auto-detected by Browsersync) - * Default: 3000 - */ - port?: number; - /** - * Add additional directories from which static files should be served. - * Should only be used in proxy or snippet mode. - * Default: [] - * Note: requires at least version 2.8.0 - */ - serveStatic?: string[]; - /** - * Enable https for localhost development. - * Note - this is not needed for proxy option as it will be inferred from your target url. - * Note: requires at least version 1.3.0 - */ - https?: boolean; - /** - * Clicks, Scrolls & Form inputs on any device will be mirrored to all others. - * clicks - Default: true - * scroll - Default: true - * forms - Default: true - */ - ghostMode?: GhostOptions | boolean; - /** - * Can be either "info", "debug", "warn", or "silent" - * Default: info - */ - logLevel?: string; - /** - * Change the console logging prefix. Useful if you're creating your own project based on Browsersync - * Default: BS - * Note: requires at least version 1.5.1 - */ - logPrefix?: string; - /** - * Whether or not to log connections - * Default: false - */ - logConnections?: boolean; - /** - * Whether or not to log information about changed files - * Default: false - */ - logFileChanges?: boolean; - /** - * Log the snippet to the console when you're in snippet mode (no proxy/server) - * Default: true - * Note: requires at least version 1.5.2 - */ - logSnippet?: boolean; - /** - * You can control how the snippet is injected onto each page via a custom regex + function. - * You can also provide patterns for certain urls that should be ignored from the snippet injection. - * Note: requires at least version 2.0.0 - */ - snippetOptions?: SnippetOptions; - /** - * Add additional HTML rewriting rules. - * Default: false - * Note: requires at least version 2.4.0 - */ - rewriteRules?: boolean | RewriteRules[]; - /** - * Tunnel the Browsersync server through a random Public URL - * Default: null - */ - tunnel?: string | boolean; - /** - * Some features of Browsersync (such as xip & tunnel) require an internet connection, but if you're - * working offline, you can reduce start-up time by setting this option to false - */ - online?: boolean; - /** - * Default: true - * Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. - * Can be true, local, external, ui, ui-external, tunnel or false - */ - open?: string | boolean; - /** - * The browser(s) to open - * Default: default - */ - browser?: string | string[]; - /** - * Requires an internet connection - useful for services such as Typekit as it allows you to configure - * domains such as *.xip.io in your kit settings - * Default: false - */ - xip?: boolean; - /** - * Reload each browser when Browsersync is restarted. - * Default: false - */ - reloadOnRestart?: boolean; - /** - * The small pop-over notifications in the browser are not always needed/wanted. - * Default: true - */ - notify?: boolean; - /** - * scrollProportionally: false // Sync viewports to TOP position - * Default: true - */ - scrollProportionally?: boolean - /** - * How often to send scroll events - * Default: 0 - */ - scrollThrottle?: number; - /** - * Decide which technique should be used to restore scroll position following a reload. - * Can be window.name or cookie - * Default: 'window.name' - */ - scrollRestoreTechnique?: string; - /** - * Sync the scroll position of any element on the page. Add any amount of CSS selectors - * Default: [] - * Note: requires at least version 2.9.0 - */ - scrollElements?: string[]; - /** - * Default: [] - * Note: requires at least version 2.9.0 - * Sync the scroll position of any element on the page - where any scrolled element will cause - * all others to match scroll position. This is helpful when a breakpoint alters which element - * is actually scrolling - */ - scrollElementMapping?: string[]; - /** - * Time, in milliseconds, to wait before instructing the browser to reload/inject following a file change event - * Default: 0 - */ - reloadDelay?: number; - /** - * Restrict the frequency in which browser:reload events can be emitted to connected clients - * Default: 0 - * Note: requires at least version 2.6.0 - */ - reloadDebounce?: number; - /** - * User provided plugins - * Default: [] - * Note: requires at least version 2.6.0 - */ - plugins?: any[]; - /** - * Whether to inject changes (rather than a page refresh) - * Default: true - */ - injectChanges?: boolean; - /** - * The initial path to load - */ - startPath?: string; - /** - * Whether to minify the client script - * Default: true - */ - minify?: boolean; - /** - * Override host detection if you know the correct IP to use - */ - host?: string; - /** - * Send file-change events to the browser - * Default: true - */ - codeSync?: boolean; - /** - * Append timestamps to injected files - * Default: true - */ - timestamps?: boolean; - /** - * Alter the script path for complete control over where the Browsersync Javascript is served - * from. Whatever you return from this function will be used as the script path. - * Note: requires at least version 1.5.0 - */ - scriptPath?: (path: string) => string; - /** - * Configure the Socket.IO path and namespace & domain to avoid collisions. - * path - Default: "/browser-sync/socket.io" - * clientPath - Default: "/browser-sync" - * namespace - Default: "/browser-sync" - * domain - Default: undefined - * port - Default: undefined - * clients.heartbeatTimeout - Default: 5000 - * Note: requires at least version 1.6.2 - */ - socket?: SocketOptions; - } - - interface Hash { - [path: string]: T; - } - - interface ChokidarOptions { - interval?: number; - debounceDelay?: number; - mode?: string; - cwd?: string; - } - - interface UIOptions { - /** set the default port */ - port?: number; - /** set the default weinre port */ - weinre?: { + namespace browserSync { + interface Options { + /** + * Browsersync includes a user-interface that is accessed via a separate port. The UI allows to controls + * all devices, push sync updates and much more. + * + * port - Default: 3001 + * weinre.port - Default: 8080 + * Note: requires at least version 2.0.0 + */ + ui?: UIOptions; + /** + * Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS + * & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob + * patterns. + * Default: false + */ + files?: string | string[]; + /** + * File watching options that get passed along to Chokidar. Check their docs for available options + * Default: undefined + * Note: requires at least version 2.6.0 + */ + watchOptions?: ChokidarOptions; + /** + * Use the built-in static server for basic HTML/JS/CSS websites. + * Default: false + */ + server?: ServerOptions; + /** + * Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site. + * target - Default: undefined + * ws - Default: undefined + * middleware - Default: undefined + * reqHeaders - Default: undefined + * proxyRes - Default: undefined + */ + proxy?: string | boolean | ProxyOptions; + /** + * Use a specific port (instead of the one auto-detected by Browsersync) + * Default: 3000 + */ port?: number; - }; - } - - interface ServerOptions { - /** set base directory */ - baseDir?: string | string[]; - /** enable directory listing */ - directory?: boolean; - /** set index filename */ - index?: string; - /** - * key-value object hash, where the key is the url to match, - * and the value is the folder to serve (relative to your working directory) - * */ - routes?: Hash; - /** configure custom middleware */ - middleware?: MiddlewareHandler[]; - } + /** + * Add additional directories from which static files should be served. + * Should only be used in proxy or snippet mode. + * Default: [] + * Note: requires at least version 2.8.0 + */ + serveStatic?: string[]; + /** + * Enable https for localhost development. + * Note - this is not needed for proxy option as it will be inferred from your target url. + * Note: requires at least version 1.3.0 + */ + https?: boolean; + /** + * Clicks, Scrolls & Form inputs on any device will be mirrored to all others. + * clicks - Default: true + * scroll - Default: true + * forms - Default: true + */ + ghostMode?: GhostOptions | boolean; + /** + * Can be either "info", "debug", "warn", or "silent" + * Default: info + */ + logLevel?: string; + /** + * Change the console logging prefix. Useful if you're creating your own project based on Browsersync + * Default: BS + * Note: requires at least version 1.5.1 + */ + logPrefix?: string; + /** + * Whether or not to log connections + * Default: false + */ + logConnections?: boolean; + /** + * Whether or not to log information about changed files + * Default: false + */ + logFileChanges?: boolean; + /** + * Log the snippet to the console when you're in snippet mode (no proxy/server) + * Default: true + * Note: requires at least version 1.5.2 + */ + logSnippet?: boolean; + /** + * You can control how the snippet is injected onto each page via a custom regex + function. + * You can also provide patterns for certain urls that should be ignored from the snippet injection. + * Note: requires at least version 2.0.0 + */ + snippetOptions?: SnippetOptions; + /** + * Add additional HTML rewriting rules. + * Default: false + * Note: requires at least version 2.4.0 + */ + rewriteRules?: boolean | RewriteRules[]; + /** + * Tunnel the Browsersync server through a random Public URL + * Default: null + */ + tunnel?: string | boolean; + /** + * Some features of Browsersync (such as xip & tunnel) require an internet connection, but if you're + * working offline, you can reduce start-up time by setting this option to false + */ + online?: boolean; + /** + * Default: true + * Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. + * Can be true, local, external, ui, ui-external, tunnel or false + */ + open?: string | boolean; + /** + * The browser(s) to open + * Default: default + */ + browser?: string | string[]; + /** + * Requires an internet connection - useful for services such as Typekit as it allows you to configure + * domains such as *.xip.io in your kit settings + * Default: false + */ + xip?: boolean; + /** + * Reload each browser when Browsersync is restarted. + * Default: false + */ + reloadOnRestart?: boolean; + /** + * The small pop-over notifications in the browser are not always needed/wanted. + * Default: true + */ + notify?: boolean; + /** + * scrollProportionally: false // Sync viewports to TOP position + * Default: true + */ + scrollProportionally?: boolean + /** + * How often to send scroll events + * Default: 0 + */ + scrollThrottle?: number; + /** + * Decide which technique should be used to restore scroll position following a reload. + * Can be window.name or cookie + * Default: 'window.name' + */ + scrollRestoreTechnique?: string; + /** + * Sync the scroll position of any element on the page. Add any amount of CSS selectors + * Default: [] + * Note: requires at least version 2.9.0 + */ + scrollElements?: string[]; + /** + * Default: [] + * Note: requires at least version 2.9.0 + * Sync the scroll position of any element on the page - where any scrolled element will cause + * all others to match scroll position. This is helpful when a breakpoint alters which element + * is actually scrolling + */ + scrollElementMapping?: string[]; + /** + * Time, in milliseconds, to wait before instructing the browser to reload/inject following a file change event + * Default: 0 + */ + reloadDelay?: number; + /** + * Restrict the frequency in which browser:reload events can be emitted to connected clients + * Default: 0 + * Note: requires at least version 2.6.0 + */ + reloadDebounce?: number; + /** + * User provided plugins + * Default: [] + * Note: requires at least version 2.6.0 + */ + plugins?: any[]; + /** + * Whether to inject changes (rather than a page refresh) + * Default: true + */ + injectChanges?: boolean; + /** + * The initial path to load + */ + startPath?: string; + /** + * Whether to minify the client script + * Default: true + */ + minify?: boolean; + /** + * Override host detection if you know the correct IP to use + */ + host?: string; + /** + * Send file-change events to the browser + * Default: true + */ + codeSync?: boolean; + /** + * Append timestamps to injected files + * Default: true + */ + timestamps?: boolean; + /** + * Alter the script path for complete control over where the Browsersync Javascript is served + * from. Whatever you return from this function will be used as the script path. + * Note: requires at least version 1.5.0 + */ + scriptPath?: (path: string) => string; + /** + * Configure the Socket.IO path and namespace & domain to avoid collisions. + * path - Default: "/browser-sync/socket.io" + * clientPath - Default: "/browser-sync" + * namespace - Default: "/browser-sync" + * domain - Default: undefined + * port - Default: undefined + * clients.heartbeatTimeout - Default: 5000 + * Note: requires at least version 1.6.2 + */ + socket?: SocketOptions; + } - interface ProxyOptions { - target?: string; - middleware?: MiddlewareHandler; - ws: boolean; - reqHeaders: (config: any) => Hash; - proxyRes: (res: http.ServerResponse, req: http.ServerRequest, next: Function) => any; + interface Hash { + [path: string]: T; + } + + interface ChokidarOptions { + interval?: number; + debounceDelay?: number; + mode?: string; + cwd?: string; + } + + interface UIOptions { + /** set the default port */ + port?: number; + /** set the default weinre port */ + weinre?: { + port?: number; + }; + } + + interface ServerOptions { + /** set base directory */ + baseDir?: string | string[]; + /** enable directory listing */ + directory?: boolean; + /** set index filename */ + index?: string; + /** + * key-value object hash, where the key is the url to match, + * and the value is the folder to serve (relative to your working directory) + * */ + routes?: Hash; + /** configure custom middleware */ + middleware?: MiddlewareHandler[]; + } + + interface ProxyOptions { + target?: string; + middleware?: MiddlewareHandler; + ws: boolean; + reqHeaders: (config: any) => Hash; + proxyRes: (res: http.ServerResponse, req: http.ServerRequest, next: Function) => any; + } + + interface MiddlewareHandler { + (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; + } + + interface GhostOptions { + clicks?: boolean; + scroll?: boolean; + forms?: boolean; + } + + interface SnippetOptions { + ignorePaths?: string; + rule?: {match?: RegExp; fn?: (snippet: string, match: string) => any}; + } + + interface SocketOptions { + path?: string; + clientPath?: string; + namespace?: string; + domain?: string; + port?: number; + clients?: { heartbeatTimeout?: number; }; + } + + interface RewriteRules { + match: RegExp; + fn: (match: string) => string; + } + + interface BrowserSyncStatic extends BrowserSyncInstance { + /** + * Start the Browsersync service. This will launch a server, proxy or start the snippet mode + * depending on your use-case. + */ + (config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; + /** + * Create a Browsersync instance + * @param name an identifier that can used for retrieval later + */ + create(name?: string): BrowserSyncInstance; + /** + * Get a single instance by name. This is useful if you have your build scripts in separate files + * @param name the identifier used for retrieval + */ + get(name: string): BrowserSyncInstance; + } + + interface BrowserSyncInstance { + /** the name of this instance of browser-sync */ + name: string; + /** + * Start the Browsersync service. This will launch a server, proxy or start the snippet mode + * depending on your use-case. + */ + init(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; + /** + * Reload the browser + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(): void; + /** + * Reload a single file + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(file: string): void; + /** + * Reload multiple files + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(files: string[]): void; + /** + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(options: {stream: boolean}): NodeJS.ReadWriteStream; + /** + * The stream method returns a transform stream and can act once or on many files. + * @param opts Configuration for the stream method + */ + stream(opts: {once: boolean}): NodeJS.ReadWriteStream; + /** + * Helper method for browser notifications + * @param message Can be a simple message such as 'Connected' or HTML + * @param timeout How long the message will remain in the browser. @since 1.3.0 + */ + notify(message: string, timeout?: number): void; + /** + * This method will close any running server, stop file watching & exit the current process. + */ + exit(): void; + /** + * Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system + */ + watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any) + : NodeJS.EventEmitter; + /** + * Method to pause file change events + */ + pause(): void; + /** + * Method to resume paused watchers + */ + resume(): void; + /** + * The internal Event Emitter used by the running Browsersync instance (if there is one). You can use + * this to emit your own events, such as changed files, logging etc. + */ + emitter: NodeJS.EventEmitter; + /** + * A simple true/false flag that you can use to determine if there's a currently-running Browsersync instance. + */ + active: boolean; + /** + * A simple true/false flag to determine if the current instance is paused + */ + paused: boolean; + } } - interface MiddlewareHandler { - (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; - } - - interface GhostOptions { - clicks?: boolean; - scroll?: boolean; - forms?: boolean; - } - - interface SnippetOptions { - ignorePaths?: string; - rule?: {match?: RegExp; fn?: (snippet: string, match: string) => any}; - } - - interface SocketOptions { - path?: string; - clientPath?: string; - namespace?: string; - domain?: string; - port?: number; - clients?: { heartbeatTimeout?: number; }; - } - - interface RewriteRules { - match: RegExp; - fn: (match: string) => string; - } - - interface BrowserSyncStatic extends BrowserSyncInstance { - /** - * Start the Browsersync service. This will launch a server, proxy or start the snippet mode - * depending on your use-case. - */ - (config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; - /** - * Create a Browsersync instance - * @param name an identifier that can used for retrieval later - */ - create(name?: string): BrowserSyncInstance; - /** - * Get a single instance by name. This is useful if you have your build scripts in separate files - * @param name the identifier used for retrieval - */ - get(name: string): BrowserSyncInstance; - } - - interface BrowserSyncInstance { - /** the name of this instance of browser-sync */ - name: string; - /** - * Start the Browsersync service. This will launch a server, proxy or start the snippet mode - * depending on your use-case. - */ - init(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; - /** - * Reload the browser - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(): void; - /** - * Reload a single file - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(file: string): void; - /** - * Reload multiple files - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(files: string[]): void; - /** - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(options: {stream: boolean}): NodeJS.ReadWriteStream; - /** - * The stream method returns a transform stream and can act once or on many files. - * @param opts Configuration for the stream method - */ - stream(opts: {once: boolean}): NodeJS.ReadWriteStream; - /** - * Helper method for browser notifications - * @param message Can be a simple message such as 'Connected' or HTML - * @param timeout How long the message will remain in the browser. @since 1.3.0 - */ - notify(message: string, timeout?: number): void; - /** - * This method will close any running server, stop file watching & exit the current process. - */ - exit(): void; - /** - * Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system - */ - watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any) - : NodeJS.EventEmitter; - /** - * Method to pause file change events - */ - pause(): void; - /** - * Method to resume paused watchers - */ - resume(): void; - /** - * The internal Event Emitter used by the running Browsersync instance (if there is one). You can use - * this to emit your own events, such as changed files, logging etc. - */ - emitter: NodeJS.EventEmitter; - /** - * A simple true/false flag that you can use to determine if there's a currently-running Browsersync instance. - */ - active: boolean; - /** - * A simple true/false flag to determine if the current instance is paused - */ - paused: boolean; - } - - const browserSync: BrowserSyncStatic; - + const browserSync: browserSync.BrowserSyncStatic; export = browserSync; } From 2ac42e05b99d8c5632b3401d4e36653de519b671 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Wed, 4 Nov 2015 10:59:27 -0700 Subject: [PATCH 13/86] Add tests to ensure interfaces are being exposed; reformatted comments --- browser-sync/browser-sync-tests.ts | 7 + browser-sync/browser-sync.d.ts | 441 +++++++++++++++-------------- 2 files changed, 228 insertions(+), 220 deletions(-) diff --git a/browser-sync/browser-sync-tests.ts b/browser-sync/browser-sync-tests.ts index 98151772f..210a8cf1b 100644 --- a/browser-sync/browser-sync-tests.ts +++ b/browser-sync/browser-sync-tests.ts @@ -1,6 +1,13 @@ /// import browserSync = require("browser-sync"); +(() => { + //make sure that the interfaces are correctly exposed + var bsInstance: browserSync.BrowserSyncInstance; + var bsStatic: browserSync.BrowserSyncStatic; + var opts: browserSync.Options; +})(); + browserSync({ server: { baseDir: "./" diff --git a/browser-sync/browser-sync.d.ts b/browser-sync/browser-sync.d.ts index 77ae2ce35..00c242942 100644 --- a/browser-sync/browser-sync.d.ts +++ b/browser-sync/browser-sync.d.ts @@ -14,256 +14,257 @@ declare module "browser-sync" { namespace browserSync { interface Options { /** - * Browsersync includes a user-interface that is accessed via a separate port. The UI allows to controls - * all devices, push sync updates and much more. - * - * port - Default: 3001 - * weinre.port - Default: 8080 - * Note: requires at least version 2.0.0 - */ + * Browsersync includes a user-interface that is accessed via a separate port. The UI allows to controls + * all devices, push sync updates and much more. + * + * port - Default: 3001 + * weinre.port - Default: 8080 + * Note: requires at least version 2.0.0 + */ ui?: UIOptions; /** - * Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS - * & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob - * patterns. - * Default: false - */ + * Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS + * & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob + * patterns. + * Default: false + */ files?: string | string[]; /** - * File watching options that get passed along to Chokidar. Check their docs for available options - * Default: undefined - * Note: requires at least version 2.6.0 - */ + * File watching options that get passed along to Chokidar. Check their docs for available options + * Default: undefined + * Note: requires at least version 2.6.0 + */ watchOptions?: ChokidarOptions; /** - * Use the built-in static server for basic HTML/JS/CSS websites. - * Default: false - */ + * Use the built-in static server for basic HTML/JS/CSS websites. + * Default: false + */ server?: ServerOptions; /** - * Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site. - * target - Default: undefined - * ws - Default: undefined - * middleware - Default: undefined - * reqHeaders - Default: undefined - * proxyRes - Default: undefined - */ + * Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site. + * target - Default: undefined + * ws - Default: undefined + * middleware - Default: undefined + * reqHeaders - Default: undefined + * proxyRes - Default: undefined + */ proxy?: string | boolean | ProxyOptions; /** - * Use a specific port (instead of the one auto-detected by Browsersync) - * Default: 3000 - */ + * Use a specific port (instead of the one auto-detected by Browsersync) + * Default: 3000 + */ port?: number; /** - * Add additional directories from which static files should be served. - * Should only be used in proxy or snippet mode. - * Default: [] - * Note: requires at least version 2.8.0 - */ + * Add additional directories from which static files should be served. + * Should only be used in proxy or snippet mode. + * Default: [] + * Note: requires at least version 2.8.0 + */ serveStatic?: string[]; /** - * Enable https for localhost development. - * Note - this is not needed for proxy option as it will be inferred from your target url. - * Note: requires at least version 1.3.0 - */ + * Enable https for localhost development. + * Note - this is not needed for proxy option as it will be inferred from your target url. + * Note: requires at least version 1.3.0 + */ https?: boolean; /** - * Clicks, Scrolls & Form inputs on any device will be mirrored to all others. - * clicks - Default: true - * scroll - Default: true - * forms - Default: true - */ + * Clicks, Scrolls & Form inputs on any device will be mirrored to all others. + * clicks - Default: true + * scroll - Default: true + * forms - Default: true + */ ghostMode?: GhostOptions | boolean; /** - * Can be either "info", "debug", "warn", or "silent" - * Default: info - */ + * Can be either "info", "debug", "warn", or "silent" + * Default: info + */ logLevel?: string; /** - * Change the console logging prefix. Useful if you're creating your own project based on Browsersync - * Default: BS - * Note: requires at least version 1.5.1 - */ + * Change the console logging prefix. Useful if you're creating your own project based on Browsersync + * Default: BS + * Note: requires at least version 1.5.1 + */ logPrefix?: string; /** - * Whether or not to log connections - * Default: false - */ + * Whether or not to log connections + * Default: false + */ logConnections?: boolean; /** - * Whether or not to log information about changed files - * Default: false - */ + * Whether or not to log information about changed files + * Default: false + */ logFileChanges?: boolean; /** - * Log the snippet to the console when you're in snippet mode (no proxy/server) - * Default: true - * Note: requires at least version 1.5.2 - */ + * Log the snippet to the console when you're in snippet mode (no proxy/server) + * Default: true + * Note: requires at least version 1.5.2 + */ logSnippet?: boolean; /** - * You can control how the snippet is injected onto each page via a custom regex + function. - * You can also provide patterns for certain urls that should be ignored from the snippet injection. - * Note: requires at least version 2.0.0 - */ + * You can control how the snippet is injected onto each page via a custom regex + function. + * You can also provide patterns for certain urls that should be ignored from the snippet injection. + * Note: requires at least version 2.0.0 + */ snippetOptions?: SnippetOptions; /** - * Add additional HTML rewriting rules. - * Default: false - * Note: requires at least version 2.4.0 - */ + * Add additional HTML rewriting rules. + * Default: false + * Note: requires at least version 2.4.0 + */ rewriteRules?: boolean | RewriteRules[]; /** - * Tunnel the Browsersync server through a random Public URL - * Default: null - */ + * Tunnel the Browsersync server through a random Public URL + * Default: null + */ tunnel?: string | boolean; /** - * Some features of Browsersync (such as xip & tunnel) require an internet connection, but if you're - * working offline, you can reduce start-up time by setting this option to false - */ + * Some features of Browsersync (such as xip & tunnel) require an internet connection, but if you're + * working offline, you can reduce start-up time by setting this option to false + */ online?: boolean; /** - * Default: true - * Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. - * Can be true, local, external, ui, ui-external, tunnel or false - */ + * Default: true + * Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. + * Can be true, local, external, ui, ui-external, tunnel or false + */ open?: string | boolean; /** - * The browser(s) to open - * Default: default - */ + * The browser(s) to open + * Default: default + */ browser?: string | string[]; /** - * Requires an internet connection - useful for services such as Typekit as it allows you to configure - * domains such as *.xip.io in your kit settings - * Default: false - */ + * Requires an internet connection - useful for services such as Typekit as it allows you to configure + * domains such as *.xip.io in your kit settings + * Default: false + */ xip?: boolean; /** - * Reload each browser when Browsersync is restarted. - * Default: false - */ + * Reload each browser when Browsersync is restarted. + * Default: false + */ reloadOnRestart?: boolean; /** - * The small pop-over notifications in the browser are not always needed/wanted. - * Default: true - */ + * The small pop-over notifications in the browser are not always needed/wanted. + * Default: true + */ notify?: boolean; /** - * scrollProportionally: false // Sync viewports to TOP position - * Default: true - */ + * scrollProportionally: false // Sync viewports to TOP position + * Default: true + */ scrollProportionally?: boolean /** - * How often to send scroll events - * Default: 0 - */ + * How often to send scroll events + * Default: 0 + */ scrollThrottle?: number; /** - * Decide which technique should be used to restore scroll position following a reload. - * Can be window.name or cookie - * Default: 'window.name' - */ + * Decide which technique should be used to restore scroll position following a reload. + * Can be window.name or cookie + * Default: 'window.name' + */ scrollRestoreTechnique?: string; /** - * Sync the scroll position of any element on the page. Add any amount of CSS selectors - * Default: [] - * Note: requires at least version 2.9.0 - */ + * Sync the scroll position of any element on the page. Add any amount of CSS selectors + * Default: [] + * Note: requires at least version 2.9.0 + */ scrollElements?: string[]; /** - * Default: [] - * Note: requires at least version 2.9.0 - * Sync the scroll position of any element on the page - where any scrolled element will cause - * all others to match scroll position. This is helpful when a breakpoint alters which element - * is actually scrolling - */ + * Default: [] + * Note: requires at least version 2.9.0 + * Sync the scroll position of any element on the page - where any scrolled element will cause + * all others to match scroll position. This is helpful when a breakpoint alters which element + * is actually scrolling + */ scrollElementMapping?: string[]; /** - * Time, in milliseconds, to wait before instructing the browser to reload/inject following a file change event - * Default: 0 - */ + * Time, in milliseconds, to wait before instructing the browser to reload/inject following a file + * change event + * Default: 0 + */ reloadDelay?: number; /** - * Restrict the frequency in which browser:reload events can be emitted to connected clients - * Default: 0 - * Note: requires at least version 2.6.0 - */ + * Restrict the frequency in which browser:reload events can be emitted to connected clients + * Default: 0 + * Note: requires at least version 2.6.0 + */ reloadDebounce?: number; /** - * User provided plugins - * Default: [] - * Note: requires at least version 2.6.0 - */ + * User provided plugins + * Default: [] + * Note: requires at least version 2.6.0 + */ plugins?: any[]; /** - * Whether to inject changes (rather than a page refresh) - * Default: true - */ + * Whether to inject changes (rather than a page refresh) + * Default: true + */ injectChanges?: boolean; /** - * The initial path to load - */ + * The initial path to load + */ startPath?: string; /** - * Whether to minify the client script - * Default: true - */ + * Whether to minify the client script + * Default: true + */ minify?: boolean; /** - * Override host detection if you know the correct IP to use - */ + * Override host detection if you know the correct IP to use + */ host?: string; /** - * Send file-change events to the browser - * Default: true - */ + * Send file-change events to the browser + * Default: true + */ codeSync?: boolean; /** - * Append timestamps to injected files - * Default: true - */ + * Append timestamps to injected files + * Default: true + */ timestamps?: boolean; /** - * Alter the script path for complete control over where the Browsersync Javascript is served - * from. Whatever you return from this function will be used as the script path. - * Note: requires at least version 1.5.0 - */ + * Alter the script path for complete control over where the Browsersync Javascript is served + * from. Whatever you return from this function will be used as the script path. + * Note: requires at least version 1.5.0 + */ scriptPath?: (path: string) => string; /** - * Configure the Socket.IO path and namespace & domain to avoid collisions. - * path - Default: "/browser-sync/socket.io" - * clientPath - Default: "/browser-sync" - * namespace - Default: "/browser-sync" - * domain - Default: undefined - * port - Default: undefined - * clients.heartbeatTimeout - Default: 5000 - * Note: requires at least version 1.6.2 - */ + * Configure the Socket.IO path and namespace & domain to avoid collisions. + * path - Default: "/browser-sync/socket.io" + * clientPath - Default: "/browser-sync" + * namespace - Default: "/browser-sync" + * domain - Default: undefined + * port - Default: undefined + * clients.heartbeatTimeout - Default: 5000 + * Note: requires at least version 1.6.2 + */ socket?: SocketOptions; } - + interface Hash { [path: string]: T; } - + interface ChokidarOptions { interval?: number; debounceDelay?: number; mode?: string; cwd?: string; } - + interface UIOptions { /** set the default port */ port?: number; /** set the default weinre port */ - weinre?: { + weinre?: { port?: number; - }; + }; } - + interface ServerOptions { /** set base directory */ baseDir?: string | string[]; @@ -272,14 +273,14 @@ declare module "browser-sync" { /** set index filename */ index?: string; /** - * key-value object hash, where the key is the url to match, - * and the value is the folder to serve (relative to your working directory) - * */ + * key-value object hash, where the key is the url to match, + * and the value is the folder to serve (relative to your working directory) + */ routes?: Hash; /** configure custom middleware */ middleware?: MiddlewareHandler[]; } - + interface ProxyOptions { target?: string; middleware?: MiddlewareHandler; @@ -287,22 +288,22 @@ declare module "browser-sync" { reqHeaders: (config: any) => Hash; proxyRes: (res: http.ServerResponse, req: http.ServerRequest, next: Function) => any; } - + interface MiddlewareHandler { (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; } - + interface GhostOptions { clicks?: boolean; scroll?: boolean; forms?: boolean; } - + interface SnippetOptions { ignorePaths?: string; - rule?: {match?: RegExp; fn?: (snippet: string, match: string) => any}; + rule?: { match?: RegExp; fn?: (snippet: string, match: string) => any }; } - + interface SocketOptions { path?: string; clientPath?: string; @@ -311,101 +312,101 @@ declare module "browser-sync" { port?: number; clients?: { heartbeatTimeout?: number; }; } - + interface RewriteRules { match: RegExp; fn: (match: string) => string; } - + interface BrowserSyncStatic extends BrowserSyncInstance { /** - * Start the Browsersync service. This will launch a server, proxy or start the snippet mode - * depending on your use-case. - */ + * Start the Browsersync service. This will launch a server, proxy or start the snippet mode + * depending on your use-case. + */ (config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; /** - * Create a Browsersync instance - * @param name an identifier that can used for retrieval later - */ + * Create a Browsersync instance + * @param name an identifier that can used for retrieval later + */ create(name?: string): BrowserSyncInstance; /** - * Get a single instance by name. This is useful if you have your build scripts in separate files - * @param name the identifier used for retrieval - */ + * Get a single instance by name. This is useful if you have your build scripts in separate files + * @param name the identifier used for retrieval + */ get(name: string): BrowserSyncInstance; } - + interface BrowserSyncInstance { /** the name of this instance of browser-sync */ name: string; /** - * Start the Browsersync service. This will launch a server, proxy or start the snippet mode - * depending on your use-case. - */ + * Start the Browsersync service. This will launch a server, proxy or start the snippet mode + * depending on your use-case. + */ init(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; /** - * Reload the browser - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ + * Reload the browser + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ reload(): void; /** - * Reload a single file - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ + * Reload a single file + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ reload(file: string): void; /** - * Reload multiple files - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ + * Reload multiple files + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ reload(files: string[]): void; /** - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(options: {stream: boolean}): NodeJS.ReadWriteStream; + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(options: { stream: boolean }): NodeJS.ReadWriteStream; /** - * The stream method returns a transform stream and can act once or on many files. - * @param opts Configuration for the stream method - */ - stream(opts: {once: boolean}): NodeJS.ReadWriteStream; + * The stream method returns a transform stream and can act once or on many files. + * @param opts Configuration for the stream method + */ + stream(opts: { once: boolean }): NodeJS.ReadWriteStream; /** - * Helper method for browser notifications - * @param message Can be a simple message such as 'Connected' or HTML - * @param timeout How long the message will remain in the browser. @since 1.3.0 - */ + * Helper method for browser notifications + * @param message Can be a simple message such as 'Connected' or HTML + * @param timeout How long the message will remain in the browser. @since 1.3.0 + */ notify(message: string, timeout?: number): void; /** - * This method will close any running server, stop file watching & exit the current process. - */ + * This method will close any running server, stop file watching & exit the current process. + */ exit(): void; /** - * Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system - */ + * Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system + */ watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any) : NodeJS.EventEmitter; /** - * Method to pause file change events - */ + * Method to pause file change events + */ pause(): void; /** - * Method to resume paused watchers - */ + * Method to resume paused watchers + */ resume(): void; /** - * The internal Event Emitter used by the running Browsersync instance (if there is one). You can use - * this to emit your own events, such as changed files, logging etc. - */ + * The internal Event Emitter used by the running Browsersync instance (if there is one). You can use + * this to emit your own events, such as changed files, logging etc. + */ emitter: NodeJS.EventEmitter; /** - * A simple true/false flag that you can use to determine if there's a currently-running Browsersync instance. - */ + * A simple true/false flag that you can use to determine if there's a currently-running Browsersync instance. + */ active: boolean; /** - * A simple true/false flag to determine if the current instance is paused - */ + * A simple true/false flag to determine if the current instance is paused + */ paused: boolean; } } From 28ae4945726ded87dd070961eb2e33a35b83c96d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elis=C3=A9e=20Maurer?= Date: Wed, 4 Nov 2015 19:38:56 +0100 Subject: [PATCH 14/86] three: Update as much as possible to r73 --- .../canvas/canvas_camera_orthographic.ts | 2 +- .../tests/canvas/canvas_lights_pointlights.ts | 2 +- threejs/tests/canvas/canvas_materials.ts | 4 +- threejs/tests/webgl/webgl_materials.ts | 6 +- threejs/three.d.ts | 606 +++++++----------- 5 files changed, 236 insertions(+), 384 deletions(-) diff --git a/threejs/tests/canvas/canvas_camera_orthographic.ts b/threejs/tests/canvas/canvas_camera_orthographic.ts index c4f932820..21cade450 100644 --- a/threejs/tests/canvas/canvas_camera_orthographic.ts +++ b/threejs/tests/canvas/canvas_camera_orthographic.ts @@ -54,7 +54,7 @@ // Cubes var geometry2 = new THREE.BoxGeometry(50, 50, 50); - var material2 = new THREE.MeshLambertMaterial({ color: 0xffffff, shading: THREE.FlatShading, overdraw: 0.5 }); + var material2 = new THREE.MeshLambertMaterial({ color: 0xffffff, overdraw: 0.5 }); for (var i = 0; i < 100; i++) { diff --git a/threejs/tests/canvas/canvas_lights_pointlights.ts b/threejs/tests/canvas/canvas_lights_pointlights.ts index 8ca0bc22b..e9cb61cf1 100644 --- a/threejs/tests/canvas/canvas_lights_pointlights.ts +++ b/threejs/tests/canvas/canvas_lights_pointlights.ts @@ -54,7 +54,7 @@ loader = new THREE.JSONLoader(); loader.load('obj/WaltHeadLo.js', function (geometry) { - mesh = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ color: 0xffffff, shading: THREE.FlatShading, overdraw: 0.5 })); + mesh = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ color: 0xffffff, overdraw: 0.5 })); scene.add(mesh); }); diff --git a/threejs/tests/canvas/canvas_materials.ts b/threejs/tests/canvas/canvas_materials.ts index d5aa8bc65..e14178564 100644 --- a/threejs/tests/canvas/canvas_materials.ts +++ b/threejs/tests/canvas/canvas_materials.ts @@ -52,8 +52,8 @@ new THREE.MeshBasicMaterial({ color: 0x00ffff, wireframe: true, side: THREE.DoubleSide }), new THREE.MeshBasicMaterial({ color: 0xff0000, blending: THREE.AdditiveBlending }), - new THREE.MeshLambertMaterial({ color: 0xffffff, shading: THREE.FlatShading, overdraw: 0.5 }), - new THREE.MeshLambertMaterial({ color: 0xffffff, shading: THREE.SmoothShading, overdraw: 0.5 }), + new THREE.MeshLambertMaterial({ color: 0xffffff, overdraw: 0.5 }), + new THREE.MeshLambertMaterial({ color: 0xffffff, overdraw: 0.5 }), new THREE.MeshDepthMaterial({ overdraw: 0.5 }), new THREE.MeshNormalMaterial({ overdraw: 0.5 }), new THREE.MeshBasicMaterial({ map: THREE.ImageUtils.loadTexture('textures/land_ocean_ice_cloud_2048.jpg') }), diff --git a/threejs/tests/webgl/webgl_materials.ts b/threejs/tests/webgl/webgl_materials.ts index 9509768a6..a78ae152a 100644 --- a/threejs/tests/webgl/webgl_materials.ts +++ b/threejs/tests/webgl/webgl_materials.ts @@ -54,20 +54,20 @@ texture.needsUpdate = true; materials.push(new THREE.MeshLambertMaterial({ map: texture, transparent: true })); - materials.push(new THREE.MeshLambertMaterial({ color: 0xdddddd, shading: THREE.FlatShading })); + materials.push(new THREE.MeshLambertMaterial({ color: 0xdddddd })); materials.push(new THREE.MeshPhongMaterial({ color: 0xdddddd, specular: 0x009900, shininess: 30, shading: THREE.FlatShading })); materials.push(new THREE.MeshNormalMaterial()); materials.push(new THREE.MeshBasicMaterial({ color: 0xffaa00, transparent: true, blending: THREE.AdditiveBlending })); //materials.push( new THREE.MeshBasicMaterial( { color: 0xff0000, blending: THREE.SubtractiveBlending } ) ); - materials.push(new THREE.MeshLambertMaterial({ color: 0xdddddd, shading: THREE.SmoothShading })); + materials.push(new THREE.MeshLambertMaterial({ color: 0xdddddd })); materials.push(new THREE.MeshPhongMaterial({ color: 0xdddddd, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, map: texture, transparent: true })); materials.push(new THREE.MeshNormalMaterial({ shading: THREE.SmoothShading })); materials.push(new THREE.MeshBasicMaterial({ color: 0xffaa00, wireframe: true })); materials.push(new THREE.MeshDepthMaterial()); - materials.push(new THREE.MeshLambertMaterial({ color: 0x666666, emissive: 0xff0000, shading: THREE.SmoothShading })); + materials.push(new THREE.MeshLambertMaterial({ color: 0x666666, emissive: 0xff0000 })); materials.push(new THREE.MeshPhongMaterial({ color: 0x000000, specular: 0x666666, emissive: 0xff0000, shininess: 10, shading: THREE.SmoothShading, opacity: 0.9, transparent: true })); materials.push(new THREE.MeshBasicMaterial({ map: texture, transparent: true })); diff --git a/threejs/three.d.ts b/threejs/three.d.ts index fd165f936..ec353c507 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1,15 +1,13 @@ -// Type definitions for three.js r71 +// Type definitions for three.js r73 // Project: http://mrdoob.github.com/three.js/ // Definitions by: Kon , Satoru Kimura // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface WebGLRenderingContext {} - declare module THREE { export var REVISION: string; // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button - export enum MOUSE {LEFT, MIDDLE, RIGHT} + export enum MOUSE { LEFT, MIDDLE, RIGHT } // GL STATE CONSTANTS export enum CullFace { } @@ -531,14 +529,17 @@ declare module THREE { name: string; type: string; attributes: BufferAttribute|InterleavedBufferAttribute[]; - attributesKeys: string[]; /** Deprecated. Use groups instead. */ drawcalls: { start: number; count: number; index: number; }[]; /** Deprecated. Use groups instead. */ offsets: { start: number; count: number; index: number; }[]; - groups: {start: number, count: number, materialIndex?: number}[] + groups: { start: number, count: number, materialIndex?: number }[]; boundingBox: Box3; boundingSphere: BoundingSphere; + + addIndex(index: BufferAttribute): void; + setIndex(index: BufferAttribute): void; + /** Deprecated. This overloaded method is deprecated. */ addAttribute(name: string, array: any, itemSize: number): any; addAttribute(name: string, attribute: BufferAttribute|InterleavedBufferAttribute): void; @@ -553,7 +554,7 @@ declare module THREE { addGroup(start: number, count: number, materialIndex?: number): void; clearGroups(): void; - setDrawRange(start:number, count:number): void; + setDrawRange(start: number, count: number): void; /** * Bakes matrix transform directly into vertex coordinates. @@ -563,9 +564,9 @@ declare module THREE { rotateX(angle: number): BufferGeometry; rotateY(angle: number): BufferGeometry; rotateZ(angle: number): BufferGeometry; - translate(x:number, y:number, z:number): BufferGeometry; - scale(x:number, y:number, z:number): BufferGeometry; - lookAt(v:Vector3): void; + translate(x: number, y: number, z: number): BufferGeometry; + scale(x: number, y: number, z: number): BufferGeometry; + lookAt(v: Vector3): void; center(): Vector3; @@ -594,19 +595,12 @@ declare module THREE { */ computeVertexNormals(): void; - /** - * Computes vertex tangents. - * Based on http://www.terathon.com/code/tangent.html - * Geometry must have vertex UVs (layer 0 will be used). - */ - computeTangents(): void; - computeOffsets(size: number): void; merge(geometry: BufferGeometry, offset: number): BufferGeometry; normalizeNormals(): void; - reorderBuffers(indexBuffer: number, indexMap: number[], vertexCount: number): void; toJSON(): any; clone(): BufferGeometry; + copy(source: BufferGeometry): BufferGeometry; /** * Disposes the object from memory. @@ -728,7 +722,7 @@ declare module THREE { /** * Deprecated. Use new THREE.BufferAttribute().setDynamic(true) instead. */ - export class DynamicBufferAttribute extends BufferAttribute{ + export class DynamicBufferAttribute extends BufferAttribute { constructor(array: any, itemSize: number); updateRange: { @@ -957,13 +951,6 @@ declare module THREE { */ morphTargets: MorphTarget[]; - /** - * Array of morph colors. Morph colors have similar structure as morph targets, each color set is a Javascript object: - * - * morphColor = { name: "colorName", colors: [ new THREE.Color(), ... ] } - */ - morphColors: MorphColor[]; - /** * Array of morph normals. Morph normals have similar structure as morph targets, each normal set is a Javascript object: * @@ -996,11 +983,6 @@ declare module THREE { */ boundingSphere: BoundingSphere; - /** - * True if geometry has tangents. Set in Geometry.computeTangents. - */ - hasTangents: boolean; - /** * Set to true if attribute buffers will need to change in runtime (using "dirty" flags). * Unless set to true internal typed arrays corresponding to buffers will be deleted once sent to GPU. @@ -1076,13 +1058,6 @@ declare module THREE { */ computeMorphNormals(): void; - /** - * Computes vertex tangents. - * Based on http://www.terathon.com/code/tangent.html - * Geometry must have vertex UVs (layer 0 will be used). - */ - computeTangents(): void; - computeLineDistances(): void; /** @@ -1106,6 +1081,8 @@ declare module THREE { */ mergeVertices(): number; + sortFacesByMaterialIndex(): void; + toJSON(): any; /** @@ -1246,7 +1223,7 @@ declare module THREE { * */ static DefaultUp: Vector3; - + static DefaultMatrixAutoUpdate: boolean; /** * Order of axis for Euler angles. @@ -1435,6 +1412,8 @@ declare module THREE { export interface RaycasterParameters { Sprite?: any; Mesh?: any; + Points?: any; + /** Deprecated, use Points */ PointCloud?: any; LOD?: any; Line?: any; @@ -1465,8 +1444,43 @@ declare module THREE { color: Color; + shadow: LightShadow; + + /** Deprecated, use shadow */ + shadowCameraFov: number; + shadowCameraNear: number; + shadowCameraFar: number; + shadowCameraLeft: number; + shadowCameraRight: number; + shadowCameraTop: number; + shadowCameraBottom: number; + shadowBias: number; + shadowDarkness: number; + shadowMapWidth: number; + shadowMapHeight: number; + shadowMap: RenderTarget; + shadowMapSize: number; + shadowCamera: Camera; + shadowMatrix: Matrix4; + clone(light?: Light): Light; } + + export class LightShadow { + constructor(camera: Camera); + + camera: THREE.Camera; + + bias: number; + darkness: number; + + mapSize: THREE.Vector2; + + map: any; + matrix: THREE.Matrix4; + + clone(): LightShadow; + } /** * This light's color gets applied to all the objects in the scene globally. @@ -1487,20 +1501,6 @@ declare module THREE { clone(): AmbientLight; } - export class AreaLight extends Light{ - constructor(hex: number, intensity?: number); - - normal: Vector3; - right: Vector3; - intensity: number; - width: number; - height: number; - constantAttenuation: number; - linearAttenuation: number; - quadraticAttenuation: number; - - } - /** * Affects objects using MeshLambertMaterial or MeshPhongMaterial. * @@ -1527,149 +1527,6 @@ declare module THREE { */ intensity: number; - /** - * If set to true light will cast dynamic shadows. Warning: This is expensive and requires tweaking to get shadows looking right. - * Default — false. - */ - castShadow: boolean; - - /** - * If set to true light will only cast shadow but not contribute any lighting (as if intensity was 0 but cheaper to compute). - * Default — false. - */ - onlyShadow: boolean; - - /** - * Orthographic shadow camera frustum parameter. - * Default — 50. - */ - shadowCameraNear: number; - - /** - * Orthographic shadow camera frustum parameter. - * Default — 5000. - */ - shadowCameraFar: number; - - /** - * Orthographic shadow camera frustum parameter. - * Default — -500. - */ - shadowCameraLeft: number; - - /** - * Orthographic shadow camera frustum parameter. - * Default — 500. - */ - shadowCameraRight: number; - - /** - * Orthographic shadow camera frustum parameter. - * Default — 500. - */ - shadowCameraTop: number; - - /** - * Orthographic shadow camera frustum parameter. - * Default — -500. - */ - shadowCameraBottom: number; - - /** - * Show debug shadow camera frustum. - * Default — false. - */ - shadowCameraVisible: boolean; - - /** - * Shadow map bias. - * Default — 0. - */ - shadowBias: number; - - /** - * Darkness of shadow casted by this light (from 0 to 1). - * Default — 0.5. - */ - shadowDarkness: number; - - /** - * Shadow map texture width in pixels. - * Default — 512. - */ - shadowMapWidth: number; - - /** - * Shadow map texture height in pixels. - * Default — 512. - */ - shadowMapHeight: number; - - /** - * Default — false. - */ - shadowCascade: boolean; - - /** - * Three.Vector3( 0, 0, -1000 ). - */ - shadowCascadeOffset: Vector3; - - /** - * Default — 2. - */ - shadowCascadeCount: number; - - /** - * Default — [ 0, 0, 0 ]. - */ - shadowCascadeBias: number[]; - - /** - * Default — [ 512, 512, 512 ]. - */ - shadowCascadeWidth: number[]; - - /** - * Default — [ 512, 512, 512 ]. - */ - shadowCascadeHeight: number[]; - - /** - * Default — [ -1.000, 0.990, 0.998 ]. - */ - shadowCascadeNearZ: number[]; - - /** - * Default — [ 0.990, 0.998, 1.000 ]. - */ - shadowCascadeFarZ: number[]; - - /** - * Default — [ ]. - */ - shadowCascadeArray: DirectionalLight[]; - - /** - * Default — null. - */ - shadowMap: RenderTarget; - - /** - * Default — null. - */ - shadowMapSize: number; - - /** - * Default — null. - */ - shadowCamera: Camera; - - /** - * Default — null. - */ - shadowMatrix: Matrix4; - clone(): DirectionalLight; } @@ -1712,18 +1569,6 @@ declare module THREE { /** * A point light that can cast shadow in one direction. - * - * @example - * // white spotlight shining from the side, casting shadow - * var spotLight = new THREE.SpotLight( 0xffffff ); - * spotLight.position.set( 100, 1000, 100 ); - * spotLight.castShadow = true; - * spotLight.shadowMapWidth = 1024; - * spotLight.shadowMapHeight = 1024; - * spotLight.shadowCameraNear = 500; - * spotLight.shadowCameraFar = 4000; - * spotLight.shadowCameraFov = 30; - * scene.add( spotLight ); */ export class SpotLight extends Light { constructor(hex?: number, intensity?: number, distance?: number, angle?: number, exponent?: number, decay?: number); @@ -1760,71 +1605,6 @@ declare module THREE { decay: number; - /** - * If set to true light will cast dynamic shadows. Warning: This is expensive and requires tweaking to get shadows looking right. - * Default — false. - */ - castShadow: boolean; - - /** - * If set to true light will only cast shadow but not contribute any lighting (as if intensity was 0 but cheaper to compute). - * Default — false. - */ - onlyShadow: boolean; - - /** - * Perspective shadow camera frustum near parameter. - * Default — 50. - */ - shadowCameraNear: number; - - /** - * Perspective shadow camera frustum far parameter. - * Default — 5000. - */ - shadowCameraFar: number; - - /** - * Perspective shadow camera frustum field of view parameter. - * Default — 50. - */ - shadowCameraFov: number; - - /** - * Show debug shadow camera frustum. - * Default — false. - */ - shadowCameraVisible: boolean; - - /** - * Shadow map bias. - * Default — 0. - */ - shadowBias: number; - - /** - * Darkness of shadow casted by this light (from 0 to 1). - * Default — 0.5. - */ - shadowDarkness: number; - - /** - * Shadow map texture width in pixels. - * Default — 512. - */ - shadowMapWidth: number; - - /** - * Shadow map texture height in pixels. - * Default — 512. - */ - shadowMapHeight: number; - - shadowMap: RenderTarget; - shadowMapSize: Vector2; - shadowCamera: Camera; - shadowMatrix: Matrix4; - clone(): SpotLight; } @@ -1849,17 +1629,7 @@ declare module THREE { * message — error message */ export class Loader { - constructor(showStatus?: boolean); - - /** - * If true, show loading status in the statusDomElement. - */ - showStatus: boolean; - - /** - * This is the recipient of status messages. - */ - statusDomElement: HTMLElement; + constructor(); imageLoader: ImageLoader; @@ -1887,20 +1657,18 @@ declare module THREE { */ crossOrigin: string; - addStatusElement(): HTMLElement; - updateProgress(progress: Progress): void; extractUrlBase(url: string): string; initMaterials(materials: Material[], texturePath: string): Material[]; needsTangents(materials: Material[]): boolean; createMaterial(m: Material, texturePath: string): boolean; - static Handlers:LoaderHandler; + static Handlers: LoaderHandler; } - export interface LoaderHandler{ - handlers:any[]; - add(regex:string, loader:Loader):void; - get(file: string):Loader; + export interface LoaderHandler { + handlers: any[]; + add(regex: string, loader: Loader): void; + get(file: string): Loader; } export class BinaryTextureLoader { @@ -1918,7 +1686,8 @@ declare module THREE { parse(json: any): BufferGeometry; } - export interface Cache{ + export interface Cache { + enabled: boolean; files: any[]; add(key: string, file: any): void; @@ -1926,9 +1695,9 @@ declare module THREE { remove(key: string): void; clear(): void; } - export var Cache:Cache; + export var Cache: Cache; - export class CompressedTextureLoader{ + export class CompressedTextureLoader { constructor(); load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void, onError?: (event: any) => void): void; @@ -1970,7 +1739,7 @@ declare module THREE { * A loader for loading objects in JSON format. */ export class JSONLoader extends Loader { - constructor(showStatus?: boolean); + constructor(); withCredentials: boolean; @@ -1992,6 +1761,8 @@ declare module THREE { export class LoadingManager { constructor(onLoad?: () => void, onProgress?: (url: string, loaded: number, total: number) => void, onError?: () => void); + onStart: () => void; + /** * Will be called when load starts. * The default is a function with empty body. @@ -2002,7 +1773,7 @@ declare module THREE { * Will be called while load progresses. * The default is a function with empty body. */ - onProgress: (item:any, loaded:number, total:number) => void; + onProgress: (item: any, loaded: number, total: number) => void; /** * Will be called when each element in the scene completes loading. @@ -2157,6 +1928,8 @@ declare module THREE { blendDstAlpha: number; blendEquationAlpha: number; + depthFunc: Function; + /** * Whether to have depth test enabled when rendering this material. Default is true. */ @@ -2271,7 +2044,8 @@ declare module THREE { export interface MeshBasicMaterialParameters extends MaterialParameters{ color?: number; map?: Texture; - lightMap?: Texture; + aoMap?: Texture; + aoMapIntensity?: number; specularMap?: Texture; alphaMap?: Texture; envMap?: Texture; @@ -2294,7 +2068,8 @@ declare module THREE { color: Color; map: Texture; - lightMap: Texture; + aoMap: Texture; + aoMapIntensity: number; specularMap: Texture; alphaMap: Texture; envMap: Texture; @@ -2341,10 +2116,7 @@ declare module THREE { export interface MeshLambertMaterialParameters extends MaterialParameters{ color?: number; emissive?: number; - wrapAround?: boolean; - wrapRGB?: Vector3; map?: Texture; - lightMap?: Texture; specularMap?: Texture; alphaMap?: Texture; envMap?: Texture; @@ -2352,7 +2124,6 @@ declare module THREE { reflectivity?: number; refractionRatio?: number; fog?: boolean; - shading?: Shading; wireframe?: boolean; wireframeLinewidth?: number; wireframeLinecap?: string; @@ -2367,10 +2138,7 @@ declare module THREE { constructor(parameters?: MeshLambertMaterialParameters); color: Color; emissive: Color; - wrapAround: boolean; - wrapRGB: Vector3; map: Texture; - lightMap: Texture; specularMap: Texture; alphaMap: Texture; envMap: Texture; @@ -2378,7 +2146,6 @@ declare module THREE { reflectivity: number; refractionRatio: number; fog: boolean; - shading: Shading; wireframe: boolean; wireframeLinewidth: number; wireframeLinecap: string; @@ -2441,6 +2208,12 @@ declare module THREE { map?: Texture; /** Set light map. Default is null */ lightMap?: Texture; + lightMapIntensity?: number; + + aoMap?: Texture; + aoMapIntensity?: number; + emissiveMap?: Texture; + /** Set specular map. Default is null */ specularMap?: Texture; /** Set alpha map. Default is null */ @@ -2471,12 +2244,13 @@ declare module THREE { specular?: number; shininess?: number; metal?: boolean; - wrapAround?: boolean; - wrapRGB?: Vector3; bumpMap?: Texture; bumpScale?: number; normalMap?: Texture; normalScale?: Vector2; + displacementMap?: Texture; + displacementScale?: number; + displacementBias?: number; combine?: Combine; reflectivity?: number; refractionRatio?: number; @@ -2491,14 +2265,19 @@ declare module THREE { specular: Color; shininess: number; metal: boolean; - wrapAround: boolean; - wrapRGB: Vector3; map: Texture; lightMap: Texture; + lightMapIntensity: number; + aoMap: Texture; + aoMapIntensity: number; + emissiveMap: Texture; bumpMap: Texture; bumpScale: number; normalMap: Texture; normalScale: Vector2; + displacementMap: Texture; + displacementScale: number; + displacementBias: number; specularMap: Texture; alphaMap: Texture; envMap: Texture; @@ -2556,10 +2335,9 @@ declare module THREE { } - export interface ShaderMaterialParameters extends MaterialParameters{ + export interface ShaderMaterialParameters extends MaterialParameters { defines?: any; uniforms?: any; - attributes?: any; vertexShader?: string; fragmentShader?: string; shading?: Shading; @@ -2579,7 +2357,6 @@ declare module THREE { defines: any; uniforms: any; - attributes: any; vertexShader: string; fragmentShader: string; shading: Shading; @@ -2596,7 +2373,7 @@ declare module THREE { clone(): ShaderMaterial; } - export interface SpriteMaterialParameters extends MaterialParameters{ + export interface SpriteMaterialParameters extends MaterialParameters { color?: number; map?: Texture; rotation?: number; @@ -3033,13 +2810,6 @@ declare module THREE { */ clamp(x: number, a: number, b: number): number; - /** - * Clamps the x to be larger than a. - * - * @param x — Value to be clamped. - * @param a — Minimum value - */ - clampBottom(x: number, a: number): number; /** * Linear mapping of x from range [a1, a2] to range [b1, b2]. @@ -3508,6 +3278,7 @@ declare module THREE { recast(t: number): Ray; closestPointToPoint(point: Vector3, optionalTarget?: Vector3): Vector3; distanceToPoint(point: Vector3): number; + distanceSqToPoint(point: Vector3): number; distanceSqToSegment(v0: Vector3, v1: Vector3, optionalPointOnRay?: Vector3, optionalPointOnSegment?: Vector3): number; isIntersectionSphere(sphere: Sphere): boolean; intersectSphere(sphere: Sphere, optionalTarget?: Vector3): Vector3; @@ -3625,7 +3396,7 @@ declare module THREE { /** * ( interface Vector<T> ) * - * Abstruct interface of Vector2, Vector3 and Vector4. + * Abstract interface of Vector2, Vector3 and Vector4. * Currently the members of Vector is NOT type safe because it accepts different typed vectors. * Those definitions will be changed when TypeScript innovates Generics to be type safe. * @@ -3784,6 +3555,7 @@ declare module THREE { */ addScalar(s: number): Vector2; addVectors(a: Vector2, b: Vector2): Vector2; + addScaledVector(v: Vector2, s: number): Vector2; /** * Subtracts v from this vector. @@ -3813,6 +3585,7 @@ declare module THREE { max(v: Vector2): Vector2; clamp(min: Vector2, max: Vector2): Vector2; clampScalar(min: number, max: number): Vector2; + clampLength(min: number, max: number): Vector2; floor(): Vector2; ceil(): Vector2; round(): Vector2; @@ -3838,6 +3611,11 @@ declare module THREE { */ length(): number; + /** + * Computes Manhattan length of this vector. + */ + lengthManhattan(): number; + /** * Normalizes this vector. */ @@ -3873,6 +3651,8 @@ declare module THREE { fromAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector2; + rotateAround(center: Vector2, angle: number): Vector2; + /** * Clones this vector. */ @@ -3933,6 +3713,7 @@ declare module THREE { */ add(a: Vector3): Vector3; addScalar(s: number): Vector3; + addScaledVector(v: Vector3, s: number): Vector3; /** * Sets this vector to a + b. @@ -3977,6 +3758,7 @@ declare module THREE { max(v: Vector3): Vector3; clamp(min: Vector3, max: Vector3): Vector3; clampScalar(min: number, max: number): Vector3; + clampLength(min: number, max: number): Vector3; floor(): Vector3; ceil(): Vector3; round(): Vector3; @@ -4121,6 +3903,7 @@ declare module THREE { * Sets this vector to a + b. */ addVectors(a: Vector4, b: Vector4): Vector4; + addScaledVector(v: Vector4, s: number): Vector4; /** * Subtracts v from this vector. @@ -4269,9 +4052,8 @@ declare module THREE { constructor(geometry?: BufferGeometry, material?: LineBasicMaterial, mode?: number); constructor(geometry?: BufferGeometry, material?: ShaderMaterial, mode?: number); - geometry: any; // Geometry or BufferGeometry; + geometry: Geometry|BufferGeometry; material: Material; // LineDashedMaterial or LineBasicMaterial or ShaderMaterial - mode: LineMode; raycast(raycaster: Raycaster, intersects: any): void; clone(object?: Line): Line; @@ -4285,7 +4067,7 @@ declare module THREE { constructor(geometry?: BufferGeometry, material?: LineBasicMaterial); constructor(geometry?: BufferGeometry, material?: ShaderMaterial); - geometry: any; // Geometry or BufferGeometry; + geometry: Geometry|BufferGeometry; material: Material; // LineDashedMaterial or LineBasicMaterial or ShaderMaterial raycast(raycaster: Raycaster, intersects: any): void; @@ -4299,6 +4081,8 @@ declare module THREE { export class LOD extends Object3D { constructor(); + levels: any[]; + /** Deprecated, use levels instead */ objects: any[]; addLevel(object: Object3D, distance?: number): void; @@ -4312,7 +4096,7 @@ declare module THREE { constructor(geometry?: Geometry, material?: Material); constructor(geometry?: BufferGeometry, material?: Material); - geometry: Geometry; + geometry: Geometry|BufferGeometry; material: Material; updateMorphTargets(): void; @@ -4398,6 +4182,7 @@ declare module THREE { calculateInverses(bone: Bone): void; pose(): void; update(): void; + clone(): Skeleton; } export class SkinnedMesh extends Mesh { @@ -4512,9 +4297,7 @@ declare module THREE { /** * The HTML5 Canvas's 'webgl' context obtained from the canvas where the renderer will draw. */ - // If you are using three.d.ts with other complete definitions of webgl, context:WebGLRenderingContext is suitable. - //context:WebGLRenderingContext; - context: any; + context: WebGLRenderingContext; /** * Defines whether the renderer should automatically clear its output before rendering. @@ -4541,6 +4324,8 @@ declare module THREE { */ sortObjects: boolean; + extensions: WebGLExtensions; + gammaFactor: number; /** @@ -4574,11 +4359,6 @@ declare module THREE { */ shadowMapDebug: boolean; - /** - * Default is false. - */ - shadowMapCascade: boolean; - /** * Default is 8. */ @@ -4611,7 +4391,7 @@ declare module THREE { }; }; - shadowMapPlugin: ShadowMapPlugin; + shadowMap: WebGLShadowMap; /** * Return the WebGL context. @@ -4620,19 +4400,22 @@ declare module THREE { forceContextLoss(): void; - /** - * Return a Boolean true if the context supports vertex textures. - */ + capabilities: WebGLCapabilities; + + /** Deprecated, use capabilities instead */ supportsVertexTextures(): boolean; supportsFloatTextures(): boolean; supportsStandardDerivatives(): boolean; supportsCompressedTextureS3TC(): boolean; supportsCompressedTexturePVRTC(): boolean; supportsBlendMinMax(): boolean; - getMaxAnisotropy(): number; getPrecision(): string; + + getMaxAnisotropy(): number; getPixelRatio(): number; setPixelRatio(value: number): void; + + getSize(): { width: number; height: number; }; /** * Resizes the output canvas to (width, height), and also sets the viewport to fit that size, starting in (0, 0). @@ -4695,6 +4478,7 @@ declare module THREE { clearStencil(): void; clearTarget(renderTarget:WebGLRenderTarget, color: boolean, depth: boolean, stencil: boolean): void; resetGLState(): void; + dispose(): void; /** * Tells the shadow map plugin to update using the passed scene and camera parameters. @@ -4734,7 +4518,24 @@ declare module THREE { setRenderTarget(renderTarget: RenderTarget): void; readRenderTargetPixels( renderTarget: RenderTarget, x: number, y: number, width: number, height: number, buffer: any ): void; } - + + export interface WebGLCapabilities { + getMaxPrecision(precision: string): string; + precision: string; + logarithmicDepthBuffer: boolean; + maxTextures: number; + maxVertexTextures: number; + maxTextureSize: number; + maxCubemapSize: number; + maxAttributes: number; + maxVertexUniforms: number; + maxVaryings: number; + maxFragmentUniforms: number; + vertexTextures: boolean; + floatFragmentTextures: boolean; + floatVertexTextures: boolean; + } + export interface RenderTarget { } @@ -4886,17 +4687,23 @@ declare module THREE { }; // Renderers / WebGL ///////////////////////////////////////////////////////////////////// - export class WebGLExtensions{ - constructor(gl: any); // WebGLRenderingContext + export class WebGLExtensions { + constructor(gl: WebGLRenderingContext); get(name: string): any; } - export class WebGLProgram{ + export class WebGLProgram { constructor(renderer: WebGLRenderer, code: string, material: ShaderMaterial, parameters: WebGLRendererParameters); + + getUniforms(): any; + getAttributes(): any; + /** Deprecated, use getUniforms */ + uniforms: any; + /** Deprecated, use getAttributes */ attributes: any; - attributesKeys: string[]; + id: number; code: string; usedTimes: number; @@ -4905,27 +4712,27 @@ declare module THREE { fragmentShader: WebGLShader; } - export class WebGLShader{ - constructor(gl: any, type: string, string: string); + export class WebGLShader { + constructor(gl: WebGLRenderingContext, type: string, string: string); } - interface WebGLStateInstance{ - new ( gl: any, paramThreeToGL: Function ): void; + interface WebGLStateInstance { + new(gl: WebGLRenderingContext, paramThreeToGL: Function): void; initAttributes(): void; enableAttribute(attribute: string): void; disableUnusedAttributes(): void; - setBlending( blending: number, blendEquation: number, blendSrc: number, blendDst: number, blendEquationAlpha: number, blendSrcAlpha: number, blendDstAlpha: number ): void; - setDepthTest( depthTest: number ): void; - setDepthWrite( depthWrite: number ): void; - setColorWrite( colorWrite: number ): void; - setDoubleSided( doubleSided: number ): void; - setFlipSided( flipSided: number ): void; - setLineWidth( width: number ): void; + setBlending(blending: number, blendEquation: number, blendSrc: number, blendDst: number, blendEquationAlpha: number, blendSrcAlpha: number, blendDstAlpha: number): void; + setDepthTest(depthTest: number): void; + setDepthWrite(depthWrite: number): void; + setColorWrite(colorWrite: number): void; + setDoubleSided(doubleSided: number): void; + setFlipSided(flipSided: number): void; + setLineWidth(width: number): void; setPolygonOffset(polygonoffset: number, factor: number, units: number): void; reset(): void; } - interface WebGLStateStatic{ - ( gl: any, paramThreeToGL: Function ): WebGLStateInstance; + interface WebGLStateStatic { + (gl: WebGLRenderingContext, paramThreeToGL: Function): WebGLStateInstance; } export var WebGLState: WebGLStateStatic; @@ -4956,9 +4763,13 @@ declare module THREE { render(scene: Scene, camera: Camera, viewportWidth: number, viewportHeight: number): void; } - export class ShadowMapPlugin implements RendererPlugin { + export class WebGLShadowMap implements RendererPlugin { constructor(); + enabled: boolean; + type: ShadowMapType; + cullFace: CullFace; + init(renderer: Renderer): void; render(scene: Scene, camera: Camera): void; update(scene: Scene, camera: Camera): void; @@ -5046,6 +4857,20 @@ declare module THREE { } // Textures ///////////////////////////////////////////////////////////////////// + export class CanvasTexture extends Texture { + constructor( + canvas?: HTMLCanvasElement, + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + } + export class CompressedTexture extends Texture { constructor( mipmaps: ImageData[], @@ -5147,6 +4972,7 @@ declare module THREE { clone(): Texture; update(): void; + toJSON(): any; dispose(): void; // EventDispatcher mixins @@ -5416,16 +5242,16 @@ declare module THREE { */ getTangentAt(u: number): T; - static Utils: { - tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; - tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; - tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; - interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; - }; - static create(constructorFunc: Function, getPointFunc: Function): Function; } + export var CurveUtils: { + tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; + tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; + tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; + interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; + }; + export interface BoundingBox { minX: number; minY: number; @@ -5494,8 +5320,8 @@ declare module THREE { splineThru(pts: Vector2[]): void; arc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; absarc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; - ellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; - absellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; + ellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number): void; + absellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number): void; getSpacedPoints(divisions?: number, closedPath?: boolean): Vector2[]; getPoints(divisions?: number, closedPath?: boolean): Vector2[]; toShapes(): Shape[]; @@ -5527,17 +5353,23 @@ declare module THREE { // Extras / Curves ///////////////////////////////////////////////////////////////////// export class ArcCurve extends EllipseCurve { - constructor(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); + constructor(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number); + } + + export class CatmullRomCurve3 extends Curve { + constructor(points?: Vector3[]); + + points: Vector3[]; } export class ClosedSplineCurve3 extends Curve { - constructor( points?:Vector3[] ); + constructor(points?: Vector3[]); - points:Vector3[]; + points: Vector3[]; } export class CubicBezierCurve extends Curve { - constructor( v0: Vector2, v1: Vector2, v2: Vector2, v3: Vector2 ); + constructor(v0: Vector2, v1: Vector2, v2: Vector2, v3: Vector2); v0: Vector2; v1: Vector2; @@ -5545,7 +5377,7 @@ declare module THREE { v3: Vector2; } export class CubicBezierCurve3 extends Curve { - constructor( v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3 ); + constructor(v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3); v0: Vector3; v1: Vector3; @@ -5553,7 +5385,7 @@ declare module THREE { v3: Vector3; } export class EllipseCurve extends Curve { - constructor( aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); + constructor(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number); aX: number; aY: number; @@ -5562,6 +5394,7 @@ declare module THREE { aStartAngle: number; aEndAngle: number; aClockwise: boolean; + aRotation: number; } export class LineCurve extends Curve { constructor( v1: Vector2, v2: Vector2 ); @@ -5626,6 +5459,17 @@ declare module THREE { }; } + export class CircleBufferGeometry extends BufferGeometry { + constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); + + parameters: { + radius: number; + segments: number; + thetaStart: number; + thetaLength: number; + }; + } + export class CircleGeometry extends Geometry { constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); @@ -5673,6 +5517,10 @@ declare module THREE { }; } + export class EdgesGeometry extends BufferGeometry { + constructor(geometry: Geometry|BufferGeometry, thresholdAngle?: number); + } + export class ExtrudeGeometry extends Geometry { constructor(shape?: Shape, options?: any); constructor(shapes?: Shape[], options?: any); @@ -5862,8 +5710,10 @@ declare module THREE { static NoTaper(u?: number): number; static SinusoidalTaper(u: number): number; - static FrenetFrames(path: Path, segments: number, closed: boolean): void; + } + export class WireframeGeometry extends BufferGeometry { + constructor(geometry: Geometry|BufferGeometry); } // Extras / Helpers ///////////////////////////////////////////////////////////////////// @@ -6008,9 +5858,11 @@ declare module THREE { // Extras / Objects ///////////////////////////////////////////////////////////////////// export class ImmediateRenderObject extends Object3D { - constructor(); + constructor(material: Material); - render(renderCallback:Function): void; + material: Material; + + render(renderCallback: Function): void; } export interface MorphBlendMeshAnimation { @@ -6052,5 +5904,5 @@ declare module THREE { } declare module 'three' { - export=THREE; + export = THREE; } From c7703702ebbc611cdf5632b288a26e418626c37b Mon Sep 17 00:00:00 2001 From: Lou Millott Date: Wed, 4 Nov 2015 13:19:55 -0800 Subject: [PATCH 15/86] update application insights to 0.15.7 --- applicationinsights/applicationinsights-tests.ts | 1 + applicationinsights/applicationinsights.d.ts | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/applicationinsights/applicationinsights-tests.ts b/applicationinsights/applicationinsights-tests.ts index 871a029e8..8d4d83e9d 100644 --- a/applicationinsights/applicationinsights-tests.ts +++ b/applicationinsights/applicationinsights-tests.ts @@ -18,6 +18,7 @@ appInsights.client.trackEvent("custom event", {customProperty: "custom property appInsights.client.trackException(new Error("handled exceptions can be logged with this method")); appInsights.client.trackMetric("custom metric", 3); appInsights.client.trackTrace("trace message"); +appInsights.client.trackDependency("dependency name", "commandName", 500, true); // assign common properties to all telemetry appInsights.client.commonProperties = { diff --git a/applicationinsights/applicationinsights.d.ts b/applicationinsights/applicationinsights.d.ts index 12dffdd81..9fc6f494d 100644 --- a/applicationinsights/applicationinsights.d.ts +++ b/applicationinsights/applicationinsights.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Application Insights v0.15.1 +// Type definitions for Application Insights v0.15.7 // Project: https://github.com/Microsoft/ApplicationInsights-node.js // Definitions by: Scott Southwood // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -342,6 +342,19 @@ interface Client { trackRequest(request: any /* http.ServerRequest */, response: any /* http.ServerResponse */, properties?: { [key: string]: string; }): void; + /** + * Log information about a dependency of your app. Typically used to track the time database calls or outgoing http requests take from your server. + * @param name The name of the dependency (i.e. "myDatabse") + * @param commandname The name of the command executed on the dependency + * @param elapsedTimeMs The amount of time in ms that the dependency took to return the result + * @param success True if the dependency succeeded, false otherwise + * @param dependencyTypeName The type of the dependency (i.e. "SQL" "HTTP"). Defaults to empty. + * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. + * @param dependencyKind ContractsModule.DependencyKind of this dependency. Defaults to Other. + * @param async True if the dependency was executed asynchronously, false otherwise. Defaults to false + * @param dependencySource ContractsModule.DependencySourceType of this dependency. Defaults to Undefined. + */ + trackDependency(name: string, commandName: string, elapsedTimeMs: number, success: boolean, dependencyTypeName?: string, properties?: {}, dependencyKind?: any, async?: boolean, dependencySource?: number): void; /** * Immediately send all queued telemetry. */ From ba72a292ddfda7b615bec42861657a30b89ca235 Mon Sep 17 00:00:00 2001 From: kwiateusz Date: Thu, 5 Nov 2015 15:27:42 +0100 Subject: [PATCH 16/86] Update mCustomScrollbar.d.ts --- mCustomScrollbar/mCustomScrollbar.d.ts | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/mCustomScrollbar/mCustomScrollbar.d.ts b/mCustomScrollbar/mCustomScrollbar.d.ts index 6ce44b23c..5763bcbe0 100644 --- a/mCustomScrollbar/mCustomScrollbar.d.ts +++ b/mCustomScrollbar/mCustomScrollbar.d.ts @@ -10,15 +10,16 @@ declare module MCustomScrollbar { /** * Set the width of your content (overwrites CSS width), value in pixels (integer) or percentage (string) */ - set_width?: any; + setWidth?: any; /** * Set the height of your content (overwirtes CSS height), value in pixels (integer) or percentage (string) */ - set_height?: any; + setHeight?: any; /** - * Add horizontal scrollbar (default is vertical), value: true, false - */ - horizontalScroll?: boolean; + * Define content’s scrolling axis (the type of scrollbars added to the element: vertical and/of horizontal). + * Available values: "y", "x", "yx". y -vertical, x - horizontal + */ + axis: string; /** * Scrolling inertia (easing), value in milliseconds (0 for no scrolling inertia) */ @@ -132,17 +133,17 @@ declare module MCustomScrollbar { */ scrollInertia?: number; /** -+ * Scroll-to animation easing, values: "linear", "easeOut", "easeInOut". -+ */ -+ scrollEasing?: string; -+ /** + * Scroll-to animation easing, values: "linear", "easeOut", "easeInOut". + */ + scrollEasing?: string; + /** * Scroll scrollbar dragger (instead of content) to a number of pixels, values: true, false */ moveDragger?: boolean; /** -+ * Set a timeout for the method (the default timeout is 60 ms in order to work with automatic scrollbar update), value in milliseconds. -+ */ -+ timeout?: number; + * Set a timeout for the method (the default timeout is 60 ms in order to work with automatic scrollbar update), value in milliseconds. + */ + timeout?: number; /** * Trigger user defined callback after scroll-to completes, value: true, false */ From b6e9e608493f13c88d02f025bf6c19d9739eb0c3 Mon Sep 17 00:00:00 2001 From: Martin D Date: Thu, 5 Nov 2015 09:30:42 -0500 Subject: [PATCH 17/86] Update leaflet.d.ts Clearer syntax --- leaflet/leaflet.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 04f2da409..cc4aa51b6 100755 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1088,7 +1088,7 @@ declare namespace L { /** * Size of the icon image in pixels. */ - iconSize?: Point|number[]; + iconSize?: Point|[number, number]; /** * The coordinates of the "tip" of the icon (relative to its top left corner). @@ -1096,7 +1096,7 @@ declare namespace L { * location. Centered by default if size is specified, also can be set in CSS * with negative margins. */ - iconAnchor?: Point|number[]; + iconAnchor?: Point|[number, number]; /** * The URL to the icon shadow image. If not specified, no shadow image will be @@ -1113,19 +1113,19 @@ declare namespace L { /** * Size of the shadow image in pixels. */ - shadowSize?: Point|number[]; + shadowSize?: Point|[number, number]; /** * The coordinates of the "tip" of the shadow (relative to its top left corner) * (the same as iconAnchor if not specified). */ - shadowAnchor?: Point|number[]; + shadowAnchor?: Point|[number, number]; /** * The coordinates of the point from which popups will "open", relative to the * icon anchor. */ - popupAnchor?: Point|number[]; + popupAnchor?: Point|[number, number]; /** * A custom class name to assign to both icon and shadow images. Empty by default. From 037b4c0597a37be9af7e91c54724be7a28dd6588 Mon Sep 17 00:00:00 2001 From: James O'Cull Date: Thu, 5 Nov 2015 10:18:02 -0500 Subject: [PATCH 18/86] Fixing incorrect function declaration syntax --- sequelize/sequelize.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index 3a80498c0..0a151c60f 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -5446,7 +5446,7 @@ declare module "sequelize" { * @param defineFunction An optional function that provides model definitions. Useful if you do not * want to use the module root as the define function */ - import( path : string, defineFunction? : (Sequelize, DataTypes) => Model ) : Model; + import( path : string, defineFunction? : (sequelize: Sequelize, dataTypes: DataTypes) => Model ) : Model; /** * Execute a query on the DB, with the posibility to bypass all the sequelize goodness. From fccf41376b522683139cadd8885dea0d044420df Mon Sep 17 00:00:00 2001 From: kwiateusz Date: Thu, 5 Nov 2015 19:14:02 +0100 Subject: [PATCH 19/86] Update mCustomScrollbar-tests.ts --- mCustomScrollbar/mCustomScrollbar-tests.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/mCustomScrollbar/mCustomScrollbar-tests.ts b/mCustomScrollbar/mCustomScrollbar-tests.ts index 983dc3a83..e2c43a119 100644 --- a/mCustomScrollbar/mCustomScrollbar-tests.ts +++ b/mCustomScrollbar/mCustomScrollbar-tests.ts @@ -22,9 +22,9 @@ class SimpleTestAllParams { this.element = $(".content"); this.element.mCustomScrollbar({ - set_width: false, - set_height: false, - horizontalScroll: false, + setWidth: false, + setHeight: false, + axis: "y", scrollInertia: 950, mouseWheel: true, mouseWheelPixels: "auto", @@ -39,7 +39,7 @@ class SimpleTestAllParams { advanced: { updateOnBrowserResize: true, updateOnContentResize: false, - autoExpandHorizontalScroll: false, + autoExpandscrollInertia: false, autoScrollOnFocus: true, normalizeMouseWheelDelta: false }, @@ -147,4 +147,4 @@ class DisableDestroyTest { }); }); } -} \ No newline at end of file +} From 47a19e1ca50137e830cc0d55579f15886f7b9449 Mon Sep 17 00:00:00 2001 From: kwiateusz Date: Thu, 5 Nov 2015 19:16:20 +0100 Subject: [PATCH 20/86] Update mCustomScrollbar.d.ts --- mCustomScrollbar/mCustomScrollbar.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mCustomScrollbar/mCustomScrollbar.d.ts b/mCustomScrollbar/mCustomScrollbar.d.ts index 5763bcbe0..3d354ee45 100644 --- a/mCustomScrollbar/mCustomScrollbar.d.ts +++ b/mCustomScrollbar/mCustomScrollbar.d.ts @@ -19,7 +19,7 @@ declare module MCustomScrollbar { * Define content’s scrolling axis (the type of scrollbars added to the element: vertical and/of horizontal). * Available values: "y", "x", "yx". y -vertical, x - horizontal */ - axis: string; + axis?: string; /** * Scrolling inertia (easing), value in milliseconds (0 for no scrolling inertia) */ From be07b0617c6114f45fdadbfcf134099314ac241e Mon Sep 17 00:00:00 2001 From: kwiateusz Date: Thu, 5 Nov 2015 19:21:11 +0100 Subject: [PATCH 21/86] Update mCustomScrollbar-tests.ts --- mCustomScrollbar/mCustomScrollbar-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mCustomScrollbar/mCustomScrollbar-tests.ts b/mCustomScrollbar/mCustomScrollbar-tests.ts index e2c43a119..7dcf79356 100644 --- a/mCustomScrollbar/mCustomScrollbar-tests.ts +++ b/mCustomScrollbar/mCustomScrollbar-tests.ts @@ -39,7 +39,7 @@ class SimpleTestAllParams { advanced: { updateOnBrowserResize: true, updateOnContentResize: false, - autoExpandscrollInertia: false, + autoExpandHorizontalScroll: false, autoScrollOnFocus: true, normalizeMouseWheelDelta: false }, From 352ad8af4020f9105734dd828773acd26b92cfac Mon Sep 17 00:00:00 2001 From: Julien Evano Date: Fri, 6 Nov 2015 06:29:28 +1100 Subject: [PATCH 22/86] refactor(Ionic framework): update ionic.Platform.ready callback to accept any return To be more generic, the ionic.Platform.ready callback has been updated to accept any return. --- ionic/ionic-tests.ts | 6 ++++-- ionic/ionic.d.ts | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/ionic/ionic-tests.ts b/ionic/ionic-tests.ts index e6e8ab0d5..ee8647b08 100644 --- a/ionic/ionic-tests.ts +++ b/ionic/ionic-tests.ts @@ -371,8 +371,10 @@ class IonicTestController { * ionic.Platform */ private testStaticPlaform(): void { - var ready: void = ionic.Platform.ready(function() { - }); + var callbackWithoutReturn: ()=>void; + var callbackWithReturn: ()=>boolean; + var ready: void = ionic.Platform.ready(callbackWithoutReturn); + ready = ionic.Platform.ready(callbackWithReturn); var setGrade: void = ionic.Platform.setGrade('iOS'); var deviceInformation: string = ionic.Platform.device(); var isWebView: boolean = ionic.Platform.isWebView(); diff --git a/ionic/ionic.d.ts b/ionic/ionic.d.ts index 774102c95..688a253ed 100644 --- a/ionic/ionic.d.ts +++ b/ionic/ionic.d.ts @@ -21,7 +21,7 @@ interface IonicStatic { * Please remember that Cordova features (Camera, FileSystem, etc) still * will not work in a web browser. */ - ready(callback: ()=>void): void; + ready(callback: ()=>any): void; /** * Set the grade of the device: ‘a’, ‘b’, or ‘c’. ‘a’ is the best * (most css features enabled), ‘c’ is the worst. By default, sets the grade From 33ee27f8f8ebb87275cefd6730c2860c15680c81 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Fri, 6 Nov 2015 02:42:18 +0500 Subject: [PATCH 23/86] lodash: signatures of the method _.shuffle have been changed --- lodash/lodash-tests.ts | 51 +++++++++++++++++++++++++++++++++++++--- lodash/lodash.d.ts | 53 ++++++++++++++++++++++++++++++------------ 2 files changed, 86 insertions(+), 18 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..3c78e6c2a 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -3056,9 +3056,54 @@ result = <_.LoDashImplicitArrayWrapper>_([1, 2, 3, 4]).sample(2); result = _([1, 2, 3, 4]).sample().value(); result = _([1, 2, 3, 4]).sample(2).value(); -result = _.shuffle([1, 2, 3, 4, 5, 6]); -result = <_.LoDashImplicitArrayWrapper>_([1, 2, 3]).shuffle(); -result = <_.LoDashImplicitArrayWrapper<_.Dictionary>>_(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' }).shuffle(); +// _.shuffle +module TestShuffle { + let array: TResult[]; + let list: _.List; + let dictionary: _.Dictionary; + + { + let result: string[]; + + result = _.shuffle('abc'); + } + + { + let result: TResult[]; + + result = _.shuffle(array); + result = _.shuffle(list); + result = _.shuffle(dictionary); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _('abc').shuffle(); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _(array).shuffle(); + result = _(list).shuffle(); + result = _(dictionary).shuffle(); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + result = _('abc').chain().shuffle(); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + result = _(array).chain().shuffle(); + result = _(list).chain().shuffle(); + result = _(dictionary).chain().shuffle(); + } +} result = _.size([1, 2]); result = _([1, 2]).size(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..c061e0639 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6176,36 +6176,59 @@ declare module _ { //_.shuffle interface LoDashStatic { /** - * Creates an array of shuffled values, using a version of the Fisher-Yates shuffle. - * See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. - * @param collection The collection to shuffle. - * @return Returns a new shuffled collection. - **/ - shuffle(collection: Array): T[]; + * Creates an array of shuffled values, using a version of the Fisher-Yates shuffle. + * + * @param collection The collection to shuffle. + * @return Returns the new shuffled array. + */ + shuffle(collection: List|Dictionary): T[]; /** - * @see _.shuffle - **/ - shuffle(collection: List): T[]; + * @see _.shuffle + */ + shuffle(collection: string): string[]; + } + interface LoDashImplicitWrapper { /** - * @see _.shuffle - **/ - shuffle(collection: Dictionary): T[]; + * @see _.shuffle + */ + shuffle(): LoDashImplicitArrayWrapper; } interface LoDashImplicitArrayWrapper { /** * @see _.shuffle - **/ + */ shuffle(): LoDashImplicitArrayWrapper; } interface LoDashImplicitObjectWrapper { /** * @see _.shuffle - **/ - shuffle(): LoDashImplicitArrayWrapper; + */ + shuffle(): LoDashImplicitArrayWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.shuffle + */ + shuffle(): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitArrayWrapper { + /** + * @see _.shuffle + */ + shuffle(): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.shuffle + */ + shuffle(): LoDashExplicitArrayWrapper; } //_.size From f266ea8a346ee8814f83a4a7fd32c13058ccba61 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Fri, 6 Nov 2015 03:15:49 +0500 Subject: [PATCH 24/86] lodash: signatures of the method _.methodOf have been changed --- lodash/lodash-tests.ts | 46 +++++++++++++++++++++++++++++++++--------- lodash/lodash.d.ts | 27 +++++++++++++++++++++++-- 2 files changed, 62 insertions(+), 11 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..146270d4f 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -5673,16 +5673,44 @@ module TestMethod { } // _.methodOf -class TestMethodOf { - a = [ - (a1: number, a2: number) => a1 + a2 - ]; +module TestMethodOf { + type SampleObject = {a: {b: () => TResult}[]}; + type ResultFn = (path: _.StringRepresentable|_.StringRepresentable[]) => TResult; + + let object: SampleObject; + + { + let result: ResultFn; + + result = _.methodOf(object); + result = _.methodOf(object, any); + result = _.methodOf(object, any, any); + result = _.methodOf(object, any, any, any); + + result = _.methodOf(object); + result = _.methodOf(object, any); + result = _.methodOf(object, any, any); + result = _.methodOf(object, any, any, any); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _(object).methodOf(); + result = _(object).methodOf(any); + result = _(object).methodOf(any, any); + result = _(object).methodOf(any, any, any); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(object).chain().methodOf(); + result = _(object).chain().methodOf(any); + result = _(object).chain().methodOf(any, any); + result = _(object).chain().methodOf(any, any, any); + } } -var TestMethodOfObject = new TestMethodOf(); -result = (_.methodOf(TestMethodOfObject, 1, 2))('a[0]'); -result = (_.methodOf(TestMethodOfObject, 1, 2))(['a', '0']); -result = (_(TestMethodOfObject).methodOf(1, 2).value())('a[0]'); -result = (_(TestMethodOfObject).methodOf(1, 2).value())(['a', '0']); // _.mixin module TestMixin { diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..c3e99d4d2 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -11276,18 +11276,41 @@ declare module _ { /** * The opposite of _.method; this method creates a function that invokes the method at a given path on object. * Any additional arguments are provided to the invoked method. + * * @param object The object to query. * @param args The arguments to invoke the method with. * @return Returns the new function. */ - methodOf(object: Object, ...args: any[]): (path: string | any[]) => TResult; + methodOf( + object: TObject, + ...args: any[] + ): (path: StringRepresentable|StringRepresentable[]) => TResult; + + /** + * @see _.methodOf + */ + methodOf( + object: {}, + ...args: any[] + ): (path: StringRepresentable|StringRepresentable[]) => TResult; } interface LoDashImplicitObjectWrapper { /** * @see _.methodOf */ - methodOf(...args: any[]): LoDashImplicitObjectWrapper<(path: string | any[]) => TResult>; + methodOf( + ...args: any[] + ): LoDashImplicitObjectWrapper<(path: StringRepresentable|StringRepresentable[]) => TResult>; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.methodOf + */ + methodOf( + ...args: any[] + ): LoDashExplicitObjectWrapper<(path: StringRepresentable|StringRepresentable[]) => TResult>; } //_.mixin From 78fba6d9572215eaf68d1a4a0a24057fd9d0fa32 Mon Sep 17 00:00:00 2001 From: Jacques Kang Date: Thu, 5 Nov 2015 23:25:45 +0100 Subject: [PATCH 25/86] Add QueryAutocompletionRequest.offset Reference: https://developers.google.com/maps/documentation/javascript/reference#QueryAutocompletionRequest --- googlemaps/google.maps.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 2093f2fd9..b951a966a 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1956,6 +1956,7 @@ declare module google.maps { bounds?: LatLngBounds; input?: string; location?: LatLng; + offset?: number; radius?: number; } From f140e0fc12de6cea22485ace1d0ad45893bede0a Mon Sep 17 00:00:00 2001 From: Joe Herman Date: Thu, 5 Nov 2015 10:58:55 -0500 Subject: [PATCH 26/86] node: Split to 0.12.x and 4.x. Added http.RequestOptions. --- node/node-0.12-tests.ts | 411 ++++++++ node/node-0.12.d.ts | 2080 +++++++++++++++++++++++++++++++++++++++ node/node.d.ts | 32 +- 3 files changed, 2511 insertions(+), 12 deletions(-) create mode 100644 node/node-0.12-tests.ts create mode 100644 node/node-0.12.d.ts diff --git a/node/node-0.12-tests.ts b/node/node-0.12-tests.ts new file mode 100644 index 000000000..f955421d9 --- /dev/null +++ b/node/node-0.12-tests.ts @@ -0,0 +1,411 @@ +/// +import * as assert from "assert"; +import * as fs from "fs"; +import * as events from "events"; +import * as zlib from "zlib"; +import * as url from "url"; +import * as util from "util"; +import * as crypto from "crypto"; +import * as tls from "tls"; +import * as http from "http"; +import * as net from "net"; +import * as dgram from "dgram"; +import * as querystring from "querystring"; +import * as path from "path"; +import * as readline from "readline"; +import * as childProcess from "child_process"; + +assert(1 + 1 - 2 === 0, "The universe isn't how it should."); + +assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); + +assert.equal(3, "3", "uses == comparator"); + +assert.notStrictEqual(2, "2", "uses === comparator"); + +assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); + +assert.doesNotThrow(() => { + if (false) { throw "a hammer at your face"; } +}, undefined, "What the...*crunch*"); + +//////////////////////////////////////////////////// +/// File system tests : http://nodejs.org/api/fs.html +//////////////////////////////////////////////////// +fs.writeFile("thebible.txt", + "Do unto others as you would have them do unto you.", + assert.ifError); + +fs.write(1234, "test"); + +fs.writeFile("Harry Potter", + "\"You be wizzing, Harry,\" jived Dumbledore.", + { + encoding: "ascii" + }, + assert.ifError); + +var content: string, + buffer: Buffer; + +content = fs.readFileSync('testfile', 'utf8'); +content = fs.readFileSync('testfile', {encoding : 'utf8'}); +buffer = fs.readFileSync('testfile'); +buffer = fs.readFileSync('testfile', {flag : 'r'}); +fs.readFile('testfile', 'utf8', (err, data) => content = data); +fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); +fs.readFile('testfile', (err, data) => buffer = data); +fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); + +class Networker extends events.EventEmitter { + constructor() { + super(); + + this.emit("mingling"); + } +} + +var errno: number; +fs.readFile('testfile', (err, data) => { + if (err && err.errno) { + errno = err.errno; + } +}); + + +/////////////////////////////////////////////////////// +/// Buffer tests : https://nodejs.org/api/buffer.html +/////////////////////////////////////////////////////// + +function bufferTests() { + var utf8Buffer = new Buffer('test'); + var base64Buffer = new Buffer('','base64'); + var octets: Uint8Array = null; + var octetBuffer = new Buffer(octets); + console.log(Buffer.isBuffer(octetBuffer)); + console.log(Buffer.isEncoding('utf8')); + console.log(Buffer.byteLength('xyz123')); + console.log(Buffer.byteLength('xyz123', 'ascii')); + var result1 = Buffer.concat([utf8Buffer, base64Buffer]); + var result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999); + + // Test that TS 1.6 works with the 'as Buffer' annotation + // on isBuffer. + var a: Buffer | number; + a = new Buffer(10); + if (Buffer.isBuffer(a)) { + a.writeUInt8(3, 4); + } + + // write* methods return offsets. + var b = new Buffer(16); + var result: number = b.writeUInt32LE(0, 0); + result = b.writeUInt16LE(0, 4); + result = b.writeUInt8(0, 6); + result = b.writeInt8(0, 7); + result = b.writeDoubleLE(0, 8); + + // fill returns the input buffer. + b.fill('a').fill('b'); +} + + +//////////////////////////////////////////////////// +/// Url tests : http://nodejs.org/api/url.html +//////////////////////////////////////////////////// + +url.format(url.parse('http://www.example.com/xyz')); + +// https://google.com/search?q=you're%20a%20lizard%2C%20gary +url.format({ + protocol: 'https', + host: "google.com", + pathname: 'search', + query: { q: "you're a lizard, gary" } +}); + +var helloUrl = url.parse('http://example.com/?hello=world', true) +assert.equal(helloUrl.query.hello, 'world'); + + +// Old and new util.inspect APIs +util.inspect(["This is nice"], false, 5); +util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); + +//////////////////////////////////////////////////// +/// Stream tests : http://nodejs.org/api/stream.html +//////////////////////////////////////////////////// + +// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options +function stream_readable_pipe_test() { + var r = fs.createReadStream('file.txt'); + var z = zlib.createGzip(); + var w = fs.createWriteStream('file.txt.gz'); + r.pipe(z).pipe(w); + r.close(); +} + +//////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html +//////////////////////////////////////////////////// + +var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + +function crypto_cipher_decipher_string_test() { + var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + var clearText:string = "This is the clear text."; + var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + var cipherText:string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); + + var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + var clearText2:string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); + + assert.equal(clearText2, clearText); +} + +function crypto_cipher_decipher_buffer_test() { + var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + var cipherBuffers:Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); + + var cipherText:Buffer = Buffer.concat(cipherBuffers); + + var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + var decipherBuffers:Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); + + var clearText2:Buffer = Buffer.concat(decipherBuffers); + + assert.deepEqual(clearText2, clearText); +} + +//////////////////////////////////////////////////// +/// TLS tests : http://nodejs.org/api/tls.html +//////////////////////////////////////////////////// + +var ctx: tls.SecureContext = tls.createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", +}); +var blah = ctx.context; + +//////////////////////////////////////////////////// + +// Make sure .listen() and .close() retuern a Server instance +http.createServer().listen(0).close().address(); +net.createServer().listen(0).close().address(); + +var request = http.request('http://0.0.0.0'); +request.once('error', function () {}); +request.setNoDelay(true); +request.abort(); + +//////////////////////////////////////////////////// +/// Http tests : http://nodejs.org/api/http.html +//////////////////////////////////////////////////// +module http_tests { + // Status codes + var code = 100; + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; + + var agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256 + }); + + var agent: http.Agent = http.globalAgent; +} + +//////////////////////////////////////////////////// +/// Dgram tests : http://nodejs.org/api/dgram.html +//////////////////////////////////////////////////// + +var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { +}); +var ai: dgram.AddressInfo = ds.address(); +ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { +}); + +//////////////////////////////////////////////////// +///Querystring tests : https://gist.github.com/musubu/2202583 +//////////////////////////////////////////////////// + +var original: string = 'http://example.com/product/abcde.html'; +var escaped: string = querystring.escape(original); +console.log(escaped); +// http%3A%2F%2Fexample.com%2Fproduct%2Fabcde.html +var unescaped: string = querystring.unescape(escaped); +console.log(unescaped); +// http://example.com/product/abcde.html + +//////////////////////////////////////////////////// +/// path tests : http://nodejs.org/api/path.html +//////////////////////////////////////////////////// + +module path_tests { + + path.normalize('/foo/bar//baz/asdf/quux/..'); + + path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); + // returns + //'/foo/bar/baz/asdf' + + try { + path.join('foo', {}, 'bar'); + } + catch(error) { + + } + + path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile'); + //Is similar to: + // + //cd foo/bar + //cd /tmp/file/ + //cd .. + // cd a/../subfile + //pwd + + path.resolve('/foo/bar', './baz') + // returns + // '/foo/bar/baz' + + path.resolve('/foo/bar', '/tmp/file/') + // returns + // '/tmp/file' + + path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif') + // if currently in /home/myself/node, it returns + // '/home/myself/node/wwwroot/static_files/gif/image.gif' + + path.isAbsolute('/foo/bar') // true + path.isAbsolute('/baz/..') // true + path.isAbsolute('qux/') // false + path.isAbsolute('.') // false + + path.isAbsolute('//server') // true + path.isAbsolute('C:/foo/..') // true + path.isAbsolute('bar\\baz') // false + path.isAbsolute('.') // false + + path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb') +// returns +// '..\\..\\impl\\bbb' + + path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') +// returns +// '../../impl/bbb' + + path.dirname('/foo/bar/baz/asdf/quux') +// returns +// '/foo/bar/baz/asdf' + + path.basename('/foo/bar/baz/asdf/quux.html') +// returns +// 'quux.html' + + path.basename('/foo/bar/baz/asdf/quux.html', '.html') +// returns +// 'quux' + + path.extname('index.html') +// returns +// '.html' + + path.extname('index.coffee.md') +// returns +// '.md' + + path.extname('index.') +// returns +// '.' + + path.extname('index') +// returns +// '' + + 'foo/bar/baz'.split(path.sep) +// returns +// ['foo', 'bar', 'baz'] + + 'foo\\bar\\baz'.split(path.sep) +// returns +// ['foo', 'bar', 'baz'] + + console.log(process.env.PATH) +// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' + + process.env.PATH.split(path.delimiter) +// returns +// ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] + + console.log(process.env.PATH) +// 'C:\Windows\system32;C:\Windows;C:\Program Files\nodejs\' + + process.env.PATH.split(path.delimiter) +// returns +// ['C:\Windows\system32', 'C:\Windows', 'C:\Program Files\nodejs\'] + + path.parse('/home/user/dir/file.txt') +// returns +// { +// root : "/", +// dir : "/home/user/dir", +// base : "file.txt", +// ext : ".txt", +// name : "file" +// } + + path.parse('C:\\path\\dir\\index.html') +// returns +// { +// root : "C:\", +// dir : "C:\path\dir", +// base : "index.html", +// ext : ".html", +// name : "index" +// } + + path.format({ + root : "/", + dir : "/home/user/dir", + base : "file.txt", + ext : ".txt", + name : "file" + }); +// returns +// '/home/user/dir/file.txt' +} + +//////////////////////////////////////////////////// +///ReadLine tests : https://nodejs.org/api/readline.html +//////////////////////////////////////////////////// + +var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +rl.setPrompt("$>"); +rl.prompt(); +rl.prompt(true); + +rl.question("do you like typescript?", function(answer: string) { + rl.close(); +}); + +////////////////////////////////////////////////////////////////////// +/// Child Process tests: https://nodejs.org/api/child_process.html /// +////////////////////////////////////////////////////////////////////// + +childProcess.exec("echo test"); +childProcess.spawnSync("echo test"); diff --git a/node/node-0.12.d.ts b/node/node-0.12.d.ts new file mode 100644 index 000000000..11fd92d24 --- /dev/null +++ b/node/node-0.12.d.ts @@ -0,0 +1,2080 @@ +// Type definitions for Node.js v0.12.0 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript , DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/************************************************ +* * +* Node.js v0.12.0 API * +* * +************************************************/ + +interface Error { + stack?: string; +} + + +// compat for TypeScript 1.5.3 +// if you use with --target es3 or --target es5 and use below definitions, +// use the lib.es6.d.ts that is bundled with TypeScript 1.5.3. +interface MapConstructor {} +interface WeakMapConstructor {} +interface SetConstructor {} +interface WeakSetConstructor {} + +/************************************************ +* * +* GLOBAL * +* * +************************************************/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearTimeout(timeoutId: NodeJS.Timer): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearInterval(intervalId: NodeJS.Timer): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; +declare function clearImmediate(immediateId: any): void; + +interface NodeRequireFunction { + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve(id:string): string; + cache: any; + extensions: any; + main: any; +} + +declare var require: NodeRequire; + +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: any; + children: any[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; +declare var SlowBuffer: { + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; +}; + + +// Buffer class +interface Buffer extends NodeBuffer {} + +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare var Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + new (str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: Uint8Array): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: any[]): Buffer; + prototype: Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Buffer, buf2: Buffer): number; +}; + +/************************************************ +* * +* GLOBAL INTERFACES * +* * +************************************************/ +declare module NodeJS { + export interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + export interface EventEmitter { + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } + + export interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string|Buffer; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + } + + export interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer|string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface ReadWriteStream extends ReadableStream, WritableStream {} + + export interface Process extends EventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: any; + exit(code?: number): void; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + openssl: string; + }; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string): void; + pid: number; + title: string; + arch: string; + platform: string; + memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; + nextTick(callback: Function): void; + umask(mask?: number): number; + uptime(): number; + hrtime(time?:number[]): number[]; + + // Worker + send?(message: any, sendHandle?: any): void; + } + + export interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: any) => void; + clearInterval: (intervalId: NodeJS.Timer) => void; + clearTimeout: (timeoutId: NodeJS.Timer) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + export interface Timer { + ref() : void; + unref() : void; + } +} + +/** + * @deprecated + */ +interface NodeBuffer { + [index: number]: number; + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): any; + length: number; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAsset?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): Buffer; +} + +/************************************************ +* * +* MODULES * +* * +************************************************/ +declare module "buffer" { + export var INSPECT_MAX_BYTES: number; +} + +declare module "querystring" { + export function stringify(obj: any, sep?: string, eq?: string): string; + export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; + export function escape(str: string): string; + export function unescape(str: string): string; +} + +declare module "events" { + export class EventEmitter implements NodeJS.EventEmitter { + static listenerCount(emitter: EventEmitter, event: string): number; + + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } +} + +declare module "http" { + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; + + export interface Server extends events.EventEmitter { + listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server; + listen(port: number, hostname?: string, callback?: Function): Server; + listen(path: string, callback?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + close(cb?: any): Server; + address(): { port: number; family: string; address: string; }; + maxHeadersCount: number; + } + /** + * @deprecated Use IncomingMessage + */ + export interface ServerRequest extends IncomingMessage { + connection: net.Socket; + } + export interface ServerResponse extends events.EventEmitter, stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + writeContinue(): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; + writeHead(statusCode: number, headers?: any): void; + statusCode: number; + statusMessage: string; + setHeader(name: string, value: string): void; + sendDate: boolean; + getHeader(name: string): string; + removeHeader(name: string): void; + write(chunk: any, encoding?: string): any; + addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface ClientRequest extends events.EventEmitter, stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + write(chunk: any, encoding?: string): void; + abort(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface IncomingMessage extends events.EventEmitter, stream.Readable { + httpVersion: string; + headers: any; + rawHeaders: string[]; + trailers: any; + rawTrailers: any; + setTimeout(msecs: number, callback: Function): NodeJS.Timer; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + } + /** + * @deprecated Use IncomingMessage + */ + export interface ClientResponse extends IncomingMessage { } + + export interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + } + + export class Agent { + maxSockets: number; + sockets: any; + requests: any; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } + + export var METHODS: string[]; + + export var STATUS_CODES: { + [errorCode: number]: string; + [errorCode: string]: string; + }; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; + export function createClient(port?: number, host?: string): any; + export function request(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export var globalAgent: Agent; +} + +declare module "cluster" { + import * as child from "child_process"; + import * as events from "events"; + + export interface ClusterSettings { + exec?: string; + args?: string[]; + silent?: boolean; + } + + export class Worker extends events.EventEmitter { + id: string; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): void; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + } + + export var settings: ClusterSettings; + export var isMaster: boolean; + export var isWorker: boolean; + export function setupMaster(settings?: ClusterSettings): void; + export function fork(env?: any): Worker; + export function disconnect(callback?: Function): void; + export var worker: Worker; + export var workers: Worker[]; + + // Event emitter + export function addListener(event: string, listener: Function): void; + export function on(event: string, listener: Function): any; + export function once(event: string, listener: Function): void; + export function removeListener(event: string, listener: Function): void; + export function removeAllListeners(event?: string): void; + export function setMaxListeners(n: number): void; + export function listeners(event: string): Function[]; + export function emit(event: string, ...args: any[]): boolean; +} + +declare module "zlib" { + import * as stream from "stream"; + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } + + export interface Gzip extends stream.Transform { } + export interface Gunzip extends stream.Transform { } + export interface Deflate extends stream.Transform { } + export interface Inflate extends stream.Transform { } + export interface DeflateRaw extends stream.Transform { } + export interface InflateRaw extends stream.Transform { } + export interface Unzip extends stream.Transform { } + + export function createGzip(options?: ZlibOptions): Gzip; + export function createGunzip(options?: ZlibOptions): Gunzip; + export function createDeflate(options?: ZlibOptions): Deflate; + export function createInflate(options?: ZlibOptions): Inflate; + export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + export function createInflateRaw(options?: ZlibOptions): InflateRaw; + export function createUnzip(options?: ZlibOptions): Unzip; + + export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateSync(buf: Buffer, options?: ZlibOptions): any; + export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; + export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gzipSync(buf: Buffer, options?: ZlibOptions): any; + export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; + export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateSync(buf: Buffer, options?: ZlibOptions): any; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; + export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function unzipSync(buf: Buffer, options?: ZlibOptions): any; + + // Constants + export var Z_NO_FLUSH: number; + export var Z_PARTIAL_FLUSH: number; + export var Z_SYNC_FLUSH: number; + export var Z_FULL_FLUSH: number; + export var Z_FINISH: number; + export var Z_BLOCK: number; + export var Z_TREES: number; + export var Z_OK: number; + export var Z_STREAM_END: number; + export var Z_NEED_DICT: number; + export var Z_ERRNO: number; + export var Z_STREAM_ERROR: number; + export var Z_DATA_ERROR: number; + export var Z_MEM_ERROR: number; + export var Z_BUF_ERROR: number; + export var Z_VERSION_ERROR: number; + export var Z_NO_COMPRESSION: number; + export var Z_BEST_SPEED: number; + export var Z_BEST_COMPRESSION: number; + export var Z_DEFAULT_COMPRESSION: number; + export var Z_FILTERED: number; + export var Z_HUFFMAN_ONLY: number; + export var Z_RLE: number; + export var Z_FIXED: number; + export var Z_DEFAULT_STRATEGY: number; + export var Z_BINARY: number; + export var Z_TEXT: number; + export var Z_ASCII: number; + export var Z_UNKNOWN: number; + export var Z_DEFLATED: number; + export var Z_NULL: number; +} + +declare module "os" { + export function tmpdir(): string; + export function hostname(): string; + export function type(): string; + export function platform(): string; + export function arch(): string; + export function release(): string; + export function uptime(): number; + export function loadavg(): number[]; + export function totalmem(): number; + export function freemem(): number; + export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; + export function networkInterfaces(): any; + export var EOL: string; +} + +declare module "https" { + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; + + export interface ServerOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + crl?: any; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; + SNICallback?: (servername: string) => any; + } + + export interface RequestOptions { + host?: string; + hostname?: string; + port?: number; + path?: string; + method?: string; + headers?: any; + auth?: string; + agent?: any; + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + } + + export interface Agent { + maxSockets: number; + sockets: any; + requests: any; + } + export var Agent: { + new (options?: RequestOptions): Agent; + }; + export interface Server extends tls.Server { } + export function createServer(options: ServerOptions, requestListener?: Function): Server; + export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; + export var globalAgent: Agent; +} + +declare module "punycode" { + export function decode(string: string): string; + export function encode(string: string): string; + export function toUnicode(domain: string): string; + export function toASCII(domain: string): string; + export var ucs2: ucs2; + interface ucs2 { + decode(string: string): string; + encode(codePoints: number[]): string; + } + export var version: any; +} + +declare module "repl" { + import * as stream from "stream"; + import * as events from "events"; + + export interface ReplOptions { + prompt?: string; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + } + export function start(options: ReplOptions): events.EventEmitter; +} + +declare module "readline" { + import * as events from "events"; + import * as stream from "stream"; + + export interface ReadLine extends events.EventEmitter { + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: Function): void; + pause(): void; + resume(): void; + close(): void; + write(data: any, key?: any): void; + } + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output: NodeJS.WritableStream; + completer?: Function; + terminal?: boolean; + } + export function createInterface(options: ReadLineOptions): ReadLine; +} + +declare module "vm" { + export interface Context { } + export interface Script { + runInThisContext(): void; + runInNewContext(sandbox?: Context): void; + } + export function runInThisContext(code: string, filename?: string): void; + export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; + export function runInContext(code: string, context: Context, filename?: string): void; + export function createContext(initSandbox?: Context): Context; + export function createScript(code: string, filename?: string): Script; +} + +declare module "child_process" { + import * as events from "events"; + import * as stream from "stream"; + + export interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + pid: number; + kill(signal?: string): void; + send(message: any, sendHandle?: any): void; + disconnect(): void; + unref(): void; + } + + export function spawn(command: string, args?: string[], options?: { + cwd?: string; + stdio?: any; + custom?: any; + env?: any; + detached?: boolean; + }): ChildProcess; + export function exec(command: string, options: { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function exec(command: string, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, + callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], + callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], options?: { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function fork(modulePath: string, args?: string[], options?: { + cwd?: string; + env?: any; + encoding?: string; + }): ChildProcess; + export function spawnSync(command: string, args?: string[], options?: { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + encoding?: string; + }): { + pid: number; + output: string[]; + stdout: string | Buffer; + stderr: string | Buffer; + status: number; + signal: string; + error: Error; + }; + export function execSync(command: string, options?: { + cwd?: string; + input?: string|Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + encoding?: string; + }): string | Buffer; + export function execFileSync(command: string, args?: string[], options?: { + cwd?: string; + input?: string|Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + encoding?: string; + }): string | Buffer; +} + +declare module "url" { + export interface Url { + href?: string; + protocol?: string; + auth?: string; + hostname?: string; + port?: string; + host?: string; + pathname?: string; + search?: string; + query?: any; // string | Object + slashes?: boolean; + hash?: string; + path?: string; + } + + export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; + export function format(url: Url): string; + export function resolve(from: string, to: string): string; +} + +declare module "dns" { + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; +} + +declare module "net" { + import * as stream from "stream"; + + export interface Socket extends stream.Duplex { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + connect(port: number, host?: string, connectionListener?: Function): void; + connect(path: string, connectionListener?: Function): void; + bufferSize: number; + setEncoding(encoding?: string): void; + write(data: any, encoding?: string, callback?: Function): void; + destroy(): void; + pause(): void; + resume(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setKeepAlive(enable?: boolean, initialDelay?: number): void; + address(): { port: number; family: string; address: string; }; + unref(): void; + ref(): void; + + remoteAddress: string; + remoteFamily: string; + remotePort: number; + localAddress: string; + localPort: number; + bytesRead: number; + bytesWritten: number; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + + export var Socket: { + new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + }; + + export interface Server extends Socket { + listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; + listen(path: string, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + close(callback?: Function): Server; + address(): { port: number; family: string; address: string; }; + maxConnections: number; + connections: number; + } + export function createServer(connectionListener?: (socket: Socket) =>void ): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; + export function connect(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function connect(port: number, host?: string, connectionListener?: Function): Socket; + export function connect(path: string, connectionListener?: Function): Socket; + export function createConnection(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + export function createConnection(path: string, connectionListener?: Function): Socket; + export function isIP(input: string): number; + export function isIPv4(input: string): boolean; + export function isIPv6(input: string): boolean; +} + +declare module "dgram" { + import * as events from "events"; + + interface RemoteInfo { + address: string; + port: number; + size: number; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + interface Socket extends events.EventEmitter { + send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port: number, address?: string, callback?: () => void): void; + close(): void; + address(): AddressInfo; + setBroadcast(flag: boolean): void; + setMulticastTTL(ttl: number): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + } +} + +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + + interface Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + } + + export interface ReadStream extends stream.Readable { + close(): void; + } + export interface WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + } + + /** + * Asynchronous rename. + * @param oldPath + * @param newPath + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /** + * Synchronous rename + * @param oldPath + * @param newPath + */ + export function renameSync(oldPath: string, newPath: string): void; + export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncateSync(path: string, len?: number): void; + export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncateSync(fd: number, len?: number): void; + export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chownSync(path: string, uid: number, gid: number): void; + export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchownSync(fd: number, uid: number, gid: number): void; + export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchownSync(path: string, uid: number, gid: number): void; + export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmodSync(path: string, mode: number): void; + export function chmodSync(path: string, mode: string): void; + export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmodSync(fd: number, mode: number): void; + export function fchmodSync(fd: number, mode: string): void; + export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmodSync(path: string, mode: number): void; + export function lchmodSync(path: string, mode: string): void; + export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function statSync(path: string): Stats; + export function lstatSync(path: string): Stats; + export function fstatSync(fd: number): Stats; + export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function linkSync(srcpath: string, dstpath: string): void; + export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; + export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string): string; + export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; + export function realpathSync(path: string, cache?: { [path: string]: string }): string; + /* + * Asynchronous unlink - deletes the file specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous unlink - deletes the file specified in {path} + * + * @param path + */ + export function unlinkSync(path: string): void; + /* + * Asynchronous rmdir - removes the directory specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous rmdir - removes the directory specified in {path} + * + * @param path + */ + export function rmdirSync(path: string): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string, mode?: number): void; + /* + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string, mode?: string): void; + export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string): string[]; + export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function closeSync(fd: number): void; + export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function openSync(path: string, flags: string, mode?: number): number; + export function openSync(path: string, flags: string, mode?: string): number; + export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimesSync(path: string, atime: number, mtime: number): void; + export function utimesSync(path: string, atime: Date, mtime: Date): void; + export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimesSync(fd: number, atime: number, mtime: number): void; + export function futimesSync(fd: number, atime: Date, mtime: Date): void; + export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fsyncSync(fd: number): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + */ + export function readFileSync(filename: string, encoding: string): string; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ + export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ + export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; + export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; + export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; + export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; + export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; + export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; + export function exists(path: string, callback?: (exists: boolean) => void): void; + export function existsSync(path: string): boolean; + /** Constant for fs.access(). File is visible to the calling process. */ + export var F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + export var R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + export var W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + export var X_OK: number; + /** Tests a user's permissions for the file specified by path. */ + export function access(path: string, callback: (err: NodeJS.ErrnoException) => void): void; + export function access(path: string, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; + /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ + export function accessSync(path: string, mode ?: number): void; + export function createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + }): ReadStream; + export function createWriteStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + }): WriteStream; +} + +declare module "path" { + + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + export interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + export function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths string paths to join. + */ + export function join(...paths: any[]): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths string paths to join. + */ + export function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + export function resolve(...pathSegments: any[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + export function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @param from + * @param to + */ + export function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + export function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + export function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + export function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + export var sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + export var delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + export function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + export function format(pathObject: ParsedPath): string; + + export module posix { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } + + export module win32 { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } +} + +declare module "string_decoder" { + export interface NodeStringDecoder { + write(buffer: Buffer): string; + detectIncompleteChar(buffer: Buffer): number; + } + export var StringDecoder: { + new (encoding: string): NodeStringDecoder; + }; +} + +declare module "tls" { + import * as crypto from "crypto"; + import * as net from "net"; + import * as stream from "stream"; + + var CLIENT_RENEG_LIMIT: number; + var CLIENT_RENEG_WINDOW: number; + + export interface TlsOptions { + pfx?: any; //string or buffer + key?: any; //string or buffer + passphrase?: string; + cert?: any; + ca?: any; //string or buffer + crl?: any; //string or string array + ciphers?: string; + honorCipherOrder?: any; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; //array or Buffer; + SNICallback?: (servername: string) => any; + } + + export interface ConnectionOptions { + host?: string; + port?: number; + socket?: net.Socket; + pfx?: any; //string | Buffer + key?: any; //string | Buffer + passphrase?: string; + cert?: any; //string | Buffer + ca?: any; //Array of string | Buffer + rejectUnauthorized?: boolean; + NPNProtocols?: any; //Array of string | Buffer + servername?: string; + } + + export interface Server extends net.Server { + // Extended base methods + listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; + listen(path: string, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + + listen(port: number, host?: string, callback?: Function): Server; + close(): Server; + address(): { port: number; family: string; address: string; }; + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + maxConnections: number; + connections: number; + } + + export interface ClearTextStream extends stream.Duplex { + authorized: boolean; + authorizationError: Error; + getPeerCertificate(): any; + getCipher: { + name: string; + version: string; + }; + address: { + port: number; + family: string; + address: string; + }; + remoteAddress: string; + remotePort: number; + } + + export interface SecurePair { + encrypted: any; + cleartext: any; + } + + export interface SecureContextOptions { + pfx?: any; //string | buffer + key?: any; //string | buffer + passphrase?: string; + cert?: any; // string | buffer + ca?: any; // string | buffer + crl?: any; // string | string[] + ciphers?: string; + honorCipherOrder?: boolean; + } + + export interface SecureContext { + context: any; + } + + export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; + export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + export function createSecureContext(details: SecureContextOptions): SecureContext; +} + +declare module "crypto" { + export interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: any; //string | string array + crl: any; //string | string array + ciphers: string; + } + export interface Credentials { context?: any; } + export function createCredentials(details: CredentialDetails): Credentials; + export function createHash(algorithm: string): Hash; + export function createHmac(algorithm: string, key: string): Hmac; + export function createHmac(algorithm: string, key: Buffer): Hmac; + interface Hash { + update(data: any, input_encoding?: string): Hash; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; + } + interface Hmac { + update(data: any, input_encoding?: string): Hmac; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; + } + export function createCipher(algorithm: string, password: any): Cipher; + export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; + interface Cipher { + update(data: Buffer): Buffer; + update(data: string, input_encoding?: string, output_encoding?: string): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding: boolean): void; + } + export function createDecipher(algorithm: string, password: any): Decipher; + export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; + interface Decipher { + update(data: Buffer): Buffer; + update(data: string, input_encoding?: string, output_encoding?: string): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding: boolean): void; + } + export function createSign(algorithm: string): Signer; + interface Signer extends NodeJS.WritableStream { + update(data: any): void; + sign(private_key: string, output_format: string): string; + } + export function createVerify(algorith: string): Verify; + interface Verify extends NodeJS.WritableStream { + update(data: any): void; + verify(object: string, signature: string, signature_format?: string): boolean; + } + export function createDiffieHellman(prime_length: number): DiffieHellman; + export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; + interface DiffieHellman { + generateKeys(encoding?: string): string; + computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; + getPrime(encoding?: string): string; + getGenerator(encoding: string): string; + getPublicKey(encoding?: string): string; + getPrivateKey(encoding?: string): string; + setPublicKey(public_key: string, encoding?: string): void; + setPrivateKey(public_key: string, encoding?: string): void; + } + export function getDiffieHellman(group_name: string): DiffieHellman; + export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; + export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number, digest: string) : Buffer; + export function randomBytes(size: number): Buffer; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export function pseudoRandomBytes(size: number): Buffer; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; +} + +declare module "stream" { + import * as events from "events"; + + export interface Stream extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + } + + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + } + + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + writable: boolean; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends ReadableOptions, WritableOptions {} + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: Function): void; + _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform {} +} + +declare module "util" { + export interface InspectOptions { + showHidden?: boolean; + depth?: number; + colors?: boolean; + customInspect?: boolean; + } + + export function format(format: any, ...param: any[]): string; + export function debug(string: string): void; + export function error(...param: any[]): void; + export function puts(...param: any[]): void; + export function print(...param: any[]): void; + export function log(string: string): void; + export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export function isArray(object: any): boolean; + export function isRegExp(object: any): boolean; + export function isDate(object: any): boolean; + export function isError(object: any): boolean; + export function inherits(constructor: any, superConstructor: any): void; + export function debuglog(key:string): (msg:string,...param: any[])=>void; +} + +declare module "assert" { + function internal (value: any, message?: string): void; + module internal { + export class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + + constructor(options?: {message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function}); + } + + export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function ok(value: any, message?: string): void; + export function equal(actual: any, expected: any, message?: string): void; + export function notEqual(actual: any, expected: any, message?: string): void; + export function deepEqual(actual: any, expected: any, message?: string): void; + export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function strictEqual(actual: any, expected: any, message?: string): void; + export function notStrictEqual(actual: any, expected: any, message?: string): void; + export var throws: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export var doesNotThrow: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export function ifError(value: any): void; + } + + export = internal; +} + +declare module "tty" { + import * as net from "net"; + + export function isatty(fd: number): boolean; + export interface ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + } + export interface WriteStream extends net.Socket { + columns: number; + rows: number; + } +} + +declare module "domain" { + import * as events from "events"; + + export class Domain extends events.EventEmitter { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + + addListener(event: string, listener: Function): Domain; + on(event: string, listener: Function): Domain; + once(event: string, listener: Function): Domain; + removeListener(event: string, listener: Function): Domain; + removeAllListeners(event?: string): Domain; + } + + export function create(): Domain; +} + +declare module "constants" { + export var E2BIG: number; + export var EACCES: number; + export var EADDRINUSE: number; + export var EADDRNOTAVAIL: number; + export var EAFNOSUPPORT: number; + export var EAGAIN: number; + export var EALREADY: number; + export var EBADF: number; + export var EBADMSG: number; + export var EBUSY: number; + export var ECANCELED: number; + export var ECHILD: number; + export var ECONNABORTED: number; + export var ECONNREFUSED: number; + export var ECONNRESET: number; + export var EDEADLK: number; + export var EDESTADDRREQ: number; + export var EDOM: number; + export var EEXIST: number; + export var EFAULT: number; + export var EFBIG: number; + export var EHOSTUNREACH: number; + export var EIDRM: number; + export var EILSEQ: number; + export var EINPROGRESS: number; + export var EINTR: number; + export var EINVAL: number; + export var EIO: number; + export var EISCONN: number; + export var EISDIR: number; + export var ELOOP: number; + export var EMFILE: number; + export var EMLINK: number; + export var EMSGSIZE: number; + export var ENAMETOOLONG: number; + export var ENETDOWN: number; + export var ENETRESET: number; + export var ENETUNREACH: number; + export var ENFILE: number; + export var ENOBUFS: number; + export var ENODATA: number; + export var ENODEV: number; + export var ENOENT: number; + export var ENOEXEC: number; + export var ENOLCK: number; + export var ENOLINK: number; + export var ENOMEM: number; + export var ENOMSG: number; + export var ENOPROTOOPT: number; + export var ENOSPC: number; + export var ENOSR: number; + export var ENOSTR: number; + export var ENOSYS: number; + export var ENOTCONN: number; + export var ENOTDIR: number; + export var ENOTEMPTY: number; + export var ENOTSOCK: number; + export var ENOTSUP: number; + export var ENOTTY: number; + export var ENXIO: number; + export var EOPNOTSUPP: number; + export var EOVERFLOW: number; + export var EPERM: number; + export var EPIPE: number; + export var EPROTO: number; + export var EPROTONOSUPPORT: number; + export var EPROTOTYPE: number; + export var ERANGE: number; + export var EROFS: number; + export var ESPIPE: number; + export var ESRCH: number; + export var ETIME: number; + export var ETIMEDOUT: number; + export var ETXTBSY: number; + export var EWOULDBLOCK: number; + export var EXDEV: number; + export var WSAEINTR: number; + export var WSAEBADF: number; + export var WSAEACCES: number; + export var WSAEFAULT: number; + export var WSAEINVAL: number; + export var WSAEMFILE: number; + export var WSAEWOULDBLOCK: number; + export var WSAEINPROGRESS: number; + export var WSAEALREADY: number; + export var WSAENOTSOCK: number; + export var WSAEDESTADDRREQ: number; + export var WSAEMSGSIZE: number; + export var WSAEPROTOTYPE: number; + export var WSAENOPROTOOPT: number; + export var WSAEPROTONOSUPPORT: number; + export var WSAESOCKTNOSUPPORT: number; + export var WSAEOPNOTSUPP: number; + export var WSAEPFNOSUPPORT: number; + export var WSAEAFNOSUPPORT: number; + export var WSAEADDRINUSE: number; + export var WSAEADDRNOTAVAIL: number; + export var WSAENETDOWN: number; + export var WSAENETUNREACH: number; + export var WSAENETRESET: number; + export var WSAECONNABORTED: number; + export var WSAECONNRESET: number; + export var WSAENOBUFS: number; + export var WSAEISCONN: number; + export var WSAENOTCONN: number; + export var WSAESHUTDOWN: number; + export var WSAETOOMANYREFS: number; + export var WSAETIMEDOUT: number; + export var WSAECONNREFUSED: number; + export var WSAELOOP: number; + export var WSAENAMETOOLONG: number; + export var WSAEHOSTDOWN: number; + export var WSAEHOSTUNREACH: number; + export var WSAENOTEMPTY: number; + export var WSAEPROCLIM: number; + export var WSAEUSERS: number; + export var WSAEDQUOT: number; + export var WSAESTALE: number; + export var WSAEREMOTE: number; + export var WSASYSNOTREADY: number; + export var WSAVERNOTSUPPORTED: number; + export var WSANOTINITIALISED: number; + export var WSAEDISCON: number; + export var WSAENOMORE: number; + export var WSAECANCELLED: number; + export var WSAEINVALIDPROCTABLE: number; + export var WSAEINVALIDPROVIDER: number; + export var WSAEPROVIDERFAILEDINIT: number; + export var WSASYSCALLFAILURE: number; + export var WSASERVICE_NOT_FOUND: number; + export var WSATYPE_NOT_FOUND: number; + export var WSA_E_NO_MORE: number; + export var WSA_E_CANCELLED: number; + export var WSAEREFUSED: number; + export var SIGHUP: number; + export var SIGINT: number; + export var SIGILL: number; + export var SIGABRT: number; + export var SIGFPE: number; + export var SIGKILL: number; + export var SIGSEGV: number; + export var SIGTERM: number; + export var SIGBREAK: number; + export var SIGWINCH: number; + export var SSL_OP_ALL: number; + export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; + export var SSL_OP_CISCO_ANYCONNECT: number; + export var SSL_OP_COOKIE_EXCHANGE: number; + export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + export var SSL_OP_EPHEMERAL_RSA: number; + export var SSL_OP_LEGACY_SERVER_CONNECT: number; + export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; + export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + export var SSL_OP_NETSCAPE_CA_DN_BUG: number; + export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NO_COMPRESSION: number; + export var SSL_OP_NO_QUERY_MTU: number; + export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + export var SSL_OP_NO_SSLv2: number; + export var SSL_OP_NO_SSLv3: number; + export var SSL_OP_NO_TICKET: number; + export var SSL_OP_NO_TLSv1: number; + export var SSL_OP_NO_TLSv1_1: number; + export var SSL_OP_NO_TLSv1_2: number; + export var SSL_OP_PKCS1_CHECK_1: number; + export var SSL_OP_PKCS1_CHECK_2: number; + export var SSL_OP_SINGLE_DH_USE: number; + export var SSL_OP_SINGLE_ECDH_USE: number; + export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; + export var SSL_OP_TLS_D5_BUG: number; + export var SSL_OP_TLS_ROLLBACK_BUG: number; + export var ENGINE_METHOD_DSA: number; + export var ENGINE_METHOD_DH: number; + export var ENGINE_METHOD_RAND: number; + export var ENGINE_METHOD_ECDH: number; + export var ENGINE_METHOD_ECDSA: number; + export var ENGINE_METHOD_CIPHERS: number; + export var ENGINE_METHOD_DIGESTS: number; + export var ENGINE_METHOD_STORE: number; + export var ENGINE_METHOD_PKEY_METHS: number; + export var ENGINE_METHOD_PKEY_ASN1_METHS: number; + export var ENGINE_METHOD_ALL: number; + export var ENGINE_METHOD_NONE: number; + export var DH_CHECK_P_NOT_SAFE_PRIME: number; + export var DH_CHECK_P_NOT_PRIME: number; + export var DH_UNABLE_TO_CHECK_GENERATOR: number; + export var DH_NOT_SUITABLE_GENERATOR: number; + export var NPN_ENABLED: number; + export var RSA_PKCS1_PADDING: number; + export var RSA_SSLV23_PADDING: number; + export var RSA_NO_PADDING: number; + export var RSA_PKCS1_OAEP_PADDING: number; + export var RSA_X931_PADDING: number; + export var RSA_PKCS1_PSS_PADDING: number; + export var POINT_CONVERSION_COMPRESSED: number; + export var POINT_CONVERSION_UNCOMPRESSED: number; + export var POINT_CONVERSION_HYBRID: number; + export var O_RDONLY: number; + export var O_WRONLY: number; + export var O_RDWR: number; + export var S_IFMT: number; + export var S_IFREG: number; + export var S_IFDIR: number; + export var S_IFCHR: number; + export var S_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: number; + export var O_TRUNC: number; + export var O_APPEND: number; + export var F_OK: number; + export var R_OK: number; + export var W_OK: number; + export var X_OK: number; + export var UV_UDP_REUSEADDR: number; +} diff --git a/node/node.d.ts b/node/node.d.ts index 4e6ffdcaf..5a163f0df 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1,11 +1,11 @@ -// Type definitions for Node.js v0.12.0 +// Type definitions for Node.js v4.x // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript , DefinitelyTyped // Definitions: https://github.com/borisyankov/DefinitelyTyped /************************************************ * * -* Node.js v0.12.0 API * +* Node.js v4.x API * * * ************************************************/ @@ -430,6 +430,21 @@ declare module "http" { import * as events from "events"; import * as net from "net"; import * as stream from "stream"; + + export interface RequestOptions { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: { [key: string]: any }; + auth?: string; + agent?: Agent; + } export interface Server extends events.EventEmitter { listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server; @@ -568,7 +583,7 @@ declare module "http" { }; export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; export function createClient(port?: number, host?: string): any; - export function request(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; export var globalAgent: Agent; } @@ -718,15 +733,7 @@ declare module "https" { SNICallback?: (servername: string) => any; } - export interface RequestOptions { - host?: string; - hostname?: string; - port?: number; - path?: string; - method?: string; - headers?: any; - auth?: string; - agent?: any; + export interface RequestOptions extends http.RequestOptions{ pfx?: any; key?: any; passphrase?: string; @@ -734,6 +741,7 @@ declare module "https" { ca?: any; ciphers?: string; rejectUnauthorized?: boolean; + secureProtocol?: string; } export interface Agent { From f7ae294142f1677f910a571da283868080c95b54 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Fri, 6 Nov 2015 03:54:04 +0500 Subject: [PATCH 27/86] lodash: signatures of the method _.range have been changed --- lodash/lodash-tests.ts | 111 ++++++++++++++++++++++------------------- lodash/lodash.d.ts | 20 ++++++-- 2 files changed, 77 insertions(+), 54 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..d40e2dd86 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -4778,57 +4778,9 @@ result = _.property(['a', 'b'])(testProperty result = (_('a.b').property().value())(testPropertyObject); result = (_(['a', 'b']).property().value())(testPropertyObject); -// _.propertyOf -module TestPropertyOf { - interface SampleObject { - a: { - b: number[]; - } - } - - let object: SampleObject; - - { - let result: (path: string|string[]) => any; - - result = _.propertyOf({}); - result = _.propertyOf(object); - } - - { - let result: _.LoDashImplicitObjectWrapper<(path: string|string[]) => any>; - - result = _({}).propertyOf(); - } - - { - let result: _.LoDashExplicitObjectWrapper<(path: string|string[]) => any>; - - result = _({}).chain().propertyOf(); - } -} - -// _.range -result = _.range(10); -result = _.range(1, 11); -result = _.range(0, 30, 5); -result = _(10).range().value(); -result = _(1).range(11).value(); -result = _(0).range(30, 5).value(); - -class Mage { - public castSpell(n: number) { - return n; - } - - public cast(n: number) { - return n; - } -} - -/********* -* String -*********/ +/********** + * String * + **********/ // _.camelCase module TestCamelCase { @@ -5754,6 +5706,63 @@ module TestNoop { } } +// _.propertyOf +module TestPropertyOf { + interface SampleObject { + a: { + b: number[]; + } + } + + let object: SampleObject; + + { + let result: (path: string|string[]) => any; + + result = _.propertyOf({}); + result = _.propertyOf(object); + } + + { + let result: _.LoDashImplicitObjectWrapper<(path: string|string[]) => any>; + + result = _({}).propertyOf(); + } + + { + let result: _.LoDashExplicitObjectWrapper<(path: string|string[]) => any>; + + result = _({}).chain().propertyOf(); + } +} + +// _.range +module TestRange { + { + let result: number[]; + + result = _.range(10); + result = _.range(1, 11); + result = _.range(0, 30, 5); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _(10).range(); + result = _(1).range(11); + result = _(0).range(30, 5); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + result = _(10).chain().range(); + result = _(1).chain().range(11); + result = _(0).chain().range(30, 5); + } +} + // _.runInContext { let result: typeof _; diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..56cdf8af3 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -11455,6 +11455,7 @@ declare module _ { * Creates an array of numbers (positive and/or negative) progressing from start up to, but not including, end. * If end is not specified it’s set to start with start then set to 0. If end is less than start a zero-length * range is created unless a negative step is specified. + * * @param start The start of the range. * @param end The end of the range. * @param step The value to increment or decrement by. @@ -11463,14 +11464,16 @@ declare module _ { range( start: number, end: number, - step?: number): number[]; + step?: number + ): number[]; /** * @see _.range */ range( end: number, - step?: number): number[]; + step?: number + ): number[]; } interface LoDashImplicitWrapper { @@ -11479,7 +11482,18 @@ declare module _ { */ range( end?: number, - step?: number): LoDashImplicitArrayWrapper; + step?: number + ): LoDashImplicitArrayWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.range + */ + range( + end?: number, + step?: number + ): LoDashExplicitArrayWrapper; } //_.runInContext From 7f61bfa1d2cbb67c97a330243018c479fbd0c87d Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Fri, 6 Nov 2015 04:04:11 +0500 Subject: [PATCH 28/86] lodash: signatures of the method _.uniqueId have been changed --- lodash/lodash-tests.ts | 19 ++++++++++++++++--- lodash/lodash.d.ts | 8 ++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..f4ed9f1cc 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -5807,9 +5807,22 @@ module TestTimes { } // _.uniqueId -result = _.uniqueId(); -result = _.uniqueId(''); -result = _('').uniqueId(); +module TestUniqueId { + { + let result: string; + + result = _.uniqueId(); + result = _.uniqueId(''); + + result = _('').uniqueId(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _('').chain().uniqueId(); + } +} result = _.VERSION; result = <_.Support>_.support; diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..022793f19 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -11557,6 +11557,7 @@ declare module _ { interface LoDashStatic { /** * Generates a unique ID. If prefix is provided the ID is appended to it. + * * @param prefix The value to prefix the ID with. * @return Returns the unique ID. */ @@ -11570,6 +11571,13 @@ declare module _ { uniqueId(): string; } + interface LoDashExplicitWrapper { + /** + * @see _.uniqueId + */ + uniqueId(): LoDashExplicitWrapper; + } + interface ListIterator { (value: T, index: number, collection: List): TResult; } From 70d024cba1497f2a66ac88da852e93a25db1416d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Ba=C5=A1e?= Date: Fri, 6 Nov 2015 08:57:46 +0100 Subject: [PATCH 29/86] Added possibility to add number or number[] to .val() --- jquery/jquery-tests.ts | 2 ++ jquery/jquery.d.ts | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 62cd273f4..13c568cb3 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -3128,6 +3128,8 @@ function test_val() { $("#single").val("Single2"); $("#multiple").val(["Multiple2", "Multiple3"]); $("input").val(["check1", "check2", "radio1"]); + $("input").val(1); + $("input").val([1, 2, 3]); } function test_selector() { diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 8401753e3..9f7a13d89 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -1365,7 +1365,7 @@ interface JQuery { * * @param value A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked. */ - val(value: string|string[]): JQuery; + val(value: string|string[]|number|number[]): JQuery; /** * Set the value of each element in the set of matched elements. * From 7d29bad1f3915793e3bfdcbfc0720c9cd7f96fe2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Ba=C5=A1e?= Date: Fri, 6 Nov 2015 09:03:08 +0100 Subject: [PATCH 30/86] Added possibility to add number or number[] to .val() --- jquery/jquery-tests.ts | 2 ++ jquery/jquery.d.ts | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 62cd273f4..13c568cb3 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -3128,6 +3128,8 @@ function test_val() { $("#single").val("Single2"); $("#multiple").val(["Multiple2", "Multiple3"]); $("input").val(["check1", "check2", "radio1"]); + $("input").val(1); + $("input").val([1, 2, 3]); } function test_selector() { diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 8401753e3..9cf3a5864 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -1363,9 +1363,9 @@ interface JQuery { /** * Set the value of each element in the set of matched elements. * - * @param value A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked. + * @param value A string of text, an array of strings, number or an array of numbers corresponding to the value of each matched element to set as selected/checked. */ - val(value: string|string[]): JQuery; + val(value: string|string[]|number|number[]): JQuery; /** * Set the value of each element in the set of matched elements. * From 899595db5d143145ec7965829260b1edbc80cc4b Mon Sep 17 00:00:00 2001 From: Patrick Westerhoff Date: Fri, 6 Nov 2015 14:09:44 +0100 Subject: [PATCH 31/86] Add definitions for svg-injector --- svg-injector/svg-injector-tests.ts | 22 +++++++++++++++ svg-injector/svg-injector.d.ts | 43 ++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 svg-injector/svg-injector-tests.ts create mode 100644 svg-injector/svg-injector.d.ts diff --git a/svg-injector/svg-injector-tests.ts b/svg-injector/svg-injector-tests.ts new file mode 100644 index 000000000..e90bf8e2a --- /dev/null +++ b/svg-injector/svg-injector-tests.ts @@ -0,0 +1,22 @@ +/// + +var SVGInjector: SVGInjector; + +// Simple example +var mySVGsToInject = document.querySelectorAll('img.inject-me'); +SVGInjector(mySVGsToInject); + +// Single DOM element +SVGInjector(document.querySelector('.inject-me')); + +// Configuration +SVGInjector(mySVGsToInject, { + evalScripts: 'always', + pngFallback: './path/to/images/', + each: eachCallback +}); +function eachCallback(element: SVGElement) { } + +// Callback +SVGInjector(mySVGsToInject, null, callback); +function callback(count: number) { } diff --git a/svg-injector/svg-injector.d.ts b/svg-injector/svg-injector.d.ts new file mode 100644 index 000000000..2fd41caa8 --- /dev/null +++ b/svg-injector/svg-injector.d.ts @@ -0,0 +1,43 @@ +// Type definitions for SVG Injector +// Project: https://github.com/iconic/SVGInjector +// Definitions by: Patrick Westerhoff +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare interface SVGInjector { + /** + * Replace the given elements with their full inline SVG DOM elements. + * + * @param elements Array of or single DOM element. + * @param options Injector options. + * @param done Callback that receives the injected element count as parameter. + */ + (elements: Node | NodeList | Array, options?: SVGInjectorOptions, done?: (elementCount: number) => void): void; +} + +declare interface SVGInjectorOptions { + /** + * Whether to run scripts blocks found in the SVG. + * + * Possible values: + * 'always' — Run scripts every time. + * 'once' — Only run scripts once for each SVG. + * 'never' — Ignore scripts (default) + */ + evalScripts?: string; + + /** + * Location of fallback pngs, if desired. + */ + pngFallback?: string; + + /** + * Callback to run during each SVG injection. The SVG element is passed if + * the injection was successful. + */ + each?: (svg: SVGElement | string) => void; +} + +declare module "svg-injector" { + var SVGInjector: SVGInjector; + export = SVGInjector; +} From bad4f0c7a1967bc51751138ff351f69287743442 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Fri, 6 Nov 2015 16:21:16 +0000 Subject: [PATCH 32/86] Create ngbootbox.d.ts --- ngbootbox.d.ts | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 ngbootbox.d.ts diff --git a/ngbootbox.d.ts b/ngbootbox.d.ts new file mode 100644 index 000000000..99d4941d1 --- /dev/null +++ b/ngbootbox.d.ts @@ -0,0 +1,38 @@ +// Type definitions for ngbootbox +// Project: https://github.com/eriktufvesson/ngBootbox +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +interface IBootboxDialog { + title?: string; + message?: string; + templateUrl?: string; + locale?: string; + callback?: () => any; + onEscape?: () => any | boolean; + show?: boolean; + backdrop?: boolean; + closeButton?: boolean; + animate?: boolean; + className?: string; + size?: string; + buttons?: BootboxButtonMap; +} + +interface IBootboxService { + alert(msg: string): Promise; + confirm(msg: string): Promise; + prompt(msg: string): Promise; + customDialog(options: IBootboxDialog): void; + setDefaults(options: BootboxDefaultOptions): void; + hideAll(): void; + + addLocale(name: string, values: BootboxLocaleValues): void; + removeLocale(name: string): void; + setLocale(name: string): void; +} + +declare var $ngBootbox: IBootboxService; From 2825966f76c31c366d50f225d6c0acfd0dfb4584 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Fri, 6 Nov 2015 16:21:48 +0000 Subject: [PATCH 33/86] Rename ngbootbox.d.ts to ngbootbox/ngbootbox.d.ts --- ngbootbox.d.ts => ngbootbox/ngbootbox.d.ts | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename ngbootbox.d.ts => ngbootbox/ngbootbox.d.ts (100%) diff --git a/ngbootbox.d.ts b/ngbootbox/ngbootbox.d.ts similarity index 100% rename from ngbootbox.d.ts rename to ngbootbox/ngbootbox.d.ts From de5f7178c6f14cbbf16525dd0dc1f9e3d1c6e34a Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Fri, 6 Nov 2015 16:22:02 +0000 Subject: [PATCH 34/86] Update ngbootbox.d.ts From e7f3e75436523a2c283b9d13fe8c52d117c3db7f Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Fri, 6 Nov 2015 16:23:53 +0000 Subject: [PATCH 35/86] Create ngbootbox-tests.ts --- ngbootbox/ngbootbox-tests.ts | 50 ++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 ngbootbox/ngbootbox-tests.ts diff --git a/ngbootbox/ngbootbox-tests.ts b/ngbootbox/ngbootbox-tests.ts new file mode 100644 index 000000000..0b64d6376 --- /dev/null +++ b/ngbootbox/ngbootbox-tests.ts @@ -0,0 +1,50 @@ +/// +/// + +class TestBootboxController { + + constructor(private $scope: angular.IScope, $ngBootbox: IBootboxService) { + + $ngBootbox.alert('An important message!').then(function() { + console.log('Alert closed'); + }); + + $ngBootbox.confirm('A question?').then(function() { + console.log('Confirmed!'); + }, function() { + console.log('Confirm dismissed!'); + }); + + $ngBootbox.prompt('Enter something').then(function(result) { + console.log('Prompt returned: ' + result); + }, function() { + console.log('Prompt dismissed!'); + }); + + var options: IBootboxDialog = { + message: 'This is a message!', + title: 'The title!', + className: 'test-class', + buttons: { + warning: { + label: "Cancel", + className: "btn-warning", + callback: function() { + console.log('warning callback'); + } + }, + success: { + label: "Ok", + className: "btn-success", + callback: function() { + console.log('sucess callback'); + } + } + } + }; + $ngBootbox.customDialog(options); + } +} + +var app = angular.module('testBootbox', ['ngBootbox']); +app.controller('TestBootboxCtrl', ['$scope', '$ngBootbox', TestBootboxController]); From debd1616001fc422abc2c0e802ca396ff8612272 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Fri, 6 Nov 2015 16:24:24 +0000 Subject: [PATCH 36/86] Update ngbootbox.d.ts --- ngbootbox/ngbootbox.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ngbootbox/ngbootbox.d.ts b/ngbootbox/ngbootbox.d.ts index 99d4941d1..b81a07501 100644 --- a/ngbootbox/ngbootbox.d.ts +++ b/ngbootbox/ngbootbox.d.ts @@ -3,8 +3,8 @@ // Definitions by: Sam Saint-Pettersen // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// -/// +/// +/// interface IBootboxDialog { title?: string; From 17c4962083dad92ac297c5b6a1eb030e7e4ccd91 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Fri, 6 Nov 2015 16:29:57 +0000 Subject: [PATCH 37/86] Update ngbootbox-tests.ts --- ngbootbox/ngbootbox-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ngbootbox/ngbootbox-tests.ts b/ngbootbox/ngbootbox-tests.ts index 0b64d6376..7e8196fec 100644 --- a/ngbootbox/ngbootbox-tests.ts +++ b/ngbootbox/ngbootbox-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// class TestBootboxController { From efce0c25ec532a4651859f10eda49e97a5716a42 Mon Sep 17 00:00:00 2001 From: bgrieder Date: Fri, 6 Nov 2015 22:01:15 +0100 Subject: [PATCH 38/86] Initial definitions for react-native 0.14 --- react-native/react-native-tests.tsx | 68 + react-native/react-native-tests.tsx.tscparams | 1 + react-native/react-native.d.ts | 1260 +++++++++++++++++ 3 files changed, 1329 insertions(+) create mode 100644 react-native/react-native-tests.tsx create mode 100644 react-native/react-native-tests.tsx.tscparams create mode 100644 react-native/react-native.d.ts diff --git a/react-native/react-native-tests.tsx b/react-native/react-native-tests.tsx new file mode 100644 index 000000000..4f2ef64d6 --- /dev/null +++ b/react-native/react-native-tests.tsx @@ -0,0 +1,68 @@ + +/* + +The content of index.io.js could be something like + + +'use strict'; + +import { AppRegistry } from 'react-native' +import Welcome from './gen/Welcome' + +AppRegistry.registerComponent('MopNative', () => Welcome); + + +*/ + +/// + + +import React from 'react-native' +const { StyleSheet, Text, View } = React + +var styles = StyleSheet.create( + { + container: { + flex: 1, + justifyContent: 'center', + alignItems: 'center', + backgroundColor: '#F5FCFF', + }, + welcome: { + fontSize: 20, + textAlign: 'center', + margin: 10, + }, + instructions: { + textAlign: 'center', + color: '#333333', + marginBottom: 5, + }, + } +) + + +class Welcome extends React.Component { + + + render() { + + return ( + + + Welcome to React Native + + + To get started, edit index.ios.js + + + Press Cmd+R to reload,{'\n'} + Cmd+D or shake for dev menu + + + ) + } +} + +export default Welcome + diff --git a/react-native/react-native-tests.tsx.tscparams b/react-native/react-native-tests.tsx.tscparams new file mode 100644 index 000000000..bc8c2d622 --- /dev/null +++ b/react-native/react-native-tests.tsx.tscparams @@ -0,0 +1 @@ +--target es6 --noImplicitAny --jsx react diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts new file mode 100644 index 000000000..fe18baa09 --- /dev/null +++ b/react-native/react-native.d.ts @@ -0,0 +1,1260 @@ +// Type definitions for react-native 0.14 +// Project: https://github.com/facebook/react-native +// Definitions by: Bruno Grieder +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// This work is mostly based on the work made by Bernd Paradies: https://github.com/bparadie +// +// +// WARNING: this work is very much beta: +// -it may be missing react-native definitions +// -it re-exports the whole of react 0.14 which may not be what react-native actually does +// +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/// + +import React = __React; + +declare namespace ReactNative { + + + /** + * Represents the completion of an asynchronous operation + * @see lib.es6.d.ts + */ + export interface Promise { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | Promise, onrejected?: (reason: any) => TResult | Promise): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: (reason: any) => T | Promise): Promise; + + + // not in lib.es6.d.ts but called by react-native + done(): void; + } + + export interface PromiseConstructor { + /** + * A reference to the prototype. + */ + prototype: Promise; + + /** + * Creates a new Promise. + * @param init A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (init: (resolve: (value?: T | Promise) => void, reject: (reason?: any) => void) => void): Promise; + + (init: (resolve: (value?: T | Promise) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: (T | Promise)[]): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of values. + * @returns A new Promise. + */ + all(values: Promise[]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: (T | Promise)[]): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | Promise): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; + } + + // @see lib.es6.d.ts + export var Promise: PromiseConstructor; + + // node_modules/react-tools/src/classic/class/ReactClass.js + export interface ReactClass + { + // TODO: + } + + // see react-jsx.d.ts + export function createElement

( + type: React.ReactType, + props?: P, + ...children: React.ReactNode[]): React.ReactElement

; + + + export type Runnable = (appParameters:any) => void; + + export type AppConfig = { + appKey: string; + component: ReactClass; + run?: Runnable; + } + + // https://github.com/facebook/react-native/blob/master/Libraries/AppRegistry/AppRegistry.js + export class AppRegistry + { + static registerConfig(config: AppConfig[]): void; + static registerComponent(appKey: string, getComponentFunc: () => React.ComponentClass): string; + static registerRunnable(appKey: string, func: Runnable): string; + static runApplication(appKey: string, appParameters: any): void; + } + + /* + export interface ReactPropTypes extends React.ReactPropTypes + { + + } + + export interface PropTypes + { + [key:string]: React.Requireable; + } + */ + + + export interface StyleSheetProperties + { + // TODO: + } + + export interface LayoutRectangle + { + x: number; + y: number; + width: number; + height: number; + } + + // @see TextProperties.onLayout + export interface LayoutChangeEvent + { + nativeEvent: { + layout: LayoutRectangle + } + } + + // @see https://facebook.github.io/react-native/docs/text.html#style + export interface TextStyle + { + color?: string; + containerBackgroundColor?: string; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; // 'normal' | 'italic'; + fontWeight?: string; // enum("normal", 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900') + letterSpacing?: number; + lineHeight?: number; + textAlign?: string; // enum("auto", 'left', 'right', 'center') + writingDirection?: string; //enum("auto", 'ltr', 'rtl') + } + + // https://facebook.github.io/react-native/docs/text.html#props + export interface TextProperties + { + /** + * numberOfLines number + * + * Used to truncate the text with an elipsis after computing the text layout, including line wrapping, such that the total number of lines does not exceed this number. + */ + numberOfLines?: number; + + /** + * onLayout function + * + * Invoked on mount and layout changes with + * + * {nativeEvent: { layout: {x, y, width, height}}}. + */ + onLayout?: (event: LayoutChangeEvent) => void; + + /** + * onPress function + * + * This function is called on press. Text intrinsically supports press handling with a default highlight state (which can be disabled with suppressHighlighting). + */ + onPress?: () => void; + + /** + * @see https://facebook.github.io/react-native/docs/text.html#style + */ + style?: TextStyle; + } + + export interface AccessibilityTraits + { + // TODO + } + + // @see https://facebook.github.io/react-native/docs/view.html#style + export interface ViewStyle + { + backgroundColor?: string; + borderBottomColor?: string; + borderBottomLeftRadius?: number; + borderBottomRightRadius?: number; + borderColor?: string; + borderLeftColor?: string; + borderRadius?: number; + borderRightColor?: string; + borderTopColor?: string; + borderTopLeftRadius?: number; + borderTopRightRadius?: number; + opacity?: number; + overflow?: string; // enum('visible', 'hidden') + shadowColor?: string; + shadowOffset?: {width: number, height: number}; + shadowOpacity?: number; + shadowRadius?: number; + } + + /** + * @see https://facebook.github.io/react-native/docs/view.html#props + */ + export interface ViewProperties + { + /** + * accessibilityLabel string + * + * Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the children and accumulating all the Text nodes separated by space. + * + */ + + accessibilityLabel?: string; + + + /** + * accessibilityTraits AccessibilityTraits, [AccessibilityTraits] + * Provides additional traits to screen reader. By default no traits are provided unless specified otherwise in element + */ + + accessibilityTraits?: AccessibilityTraits; + + /** + * accessible bool + * + * When true, indicates that the view is an accessibility element. By default, all the touchable elements are accessible. + */ + + accessible?: boolean; + + /** + * onAcccessibilityTap function + * When accessible is true, the system will try to invoke this function when the user performs accessibility tap gesture. + * + */ + + onAcccessibilityTap?: () => void; + + /** + * onLayout function + * + * Invoked on mount and layout changes with + * + * {nativeEvent: { layout: {x, y, width, height}}}. + */ + onLayout?: (event: LayoutChangeEvent) => void; + + /** + * onMagicTap function + * + * When accessible is true, the system will invoke this function when the user performs the magic tap gesture. + */ + + onMagicTap?: () => void; + + /** + * onMoveShouldSetResponder function + * + * For most touch interactions, you'll simply want to wrap your component in TouchableHighlight or TouchableOpacity. Check out Touchable.js, ScrollResponder.js and ResponderEventPlugin.js for more discussion. + */ + onMoveShouldSetResponder?: () => void; + + onResponderGrant?: () => void; + + onResponderMove?: () => void; + + onResponderReject?: () => void; + + onResponderRelease?: () => void; + + onResponderTerminate?: () => void; + + onResponderTerminationRequest?: () => void; + + onStartShouldSetResponder?: () => void; + + onStartShouldSetResponderCapture?: () => void; + + /** + * pointerEvents enum('box-none', 'none', 'box-only', 'auto') + * + * In the absence of auto property, none is much like CSS's none value. box-none is as if you had applied the CSS class: + * + * .box-none { + * pointer-events: none; + * } + * .box-none * { + * pointer-events: all; + * } + * + * box-only is the equivalent of + * + * .box-only { + * pointer-events: all; + * } + * .box-only * { + * pointer-events: none; + * } + * + * But since pointerEvents does not affect layout/appearance, and we are already deviating from the spec by adding additional modes, + * we opt to not include pointerEvents on style. On some platforms, we would need to implement it as a className anyways. Using style or not is an implementation detail of the platform. + */ + + pointerEvents?: string; + + /** + * removeClippedSubviews bool + * + * This is a special performance property exposed by RCTView and is useful for scrolling content when there are many subviews, + * most of which are offscreen. For this property to be effective, it must be applied to a view that contains many subviews that extend outside its bound. + * The subviews must also have overflow: hidden, as should the containing view (or one of its superviews). + */ + + removeClippedSubviews?: boolean + + /** + * renderToHardwareTextureAndroid bool + * + * Whether this view should render itself (and all of its children) into a single hardware texture on the GPU. + * + * On Android, this is useful for animations and interactions that only modify opacity, rotation, translation, and/or scale: + * in those cases, the view doesn't have to be redrawn and display lists don't need to be re-executed. The texture can just be + * re-used and re-composited with different parameters. The downside is that this can use up limited video memory, so this prop should be set back to false at the end of the interaction/animation. + */ + + renderToHardwareTextureAndroid?: boolean; + + style?: ViewStyle; + + /** + * testID string + * + * Used to locate this view in end-to-end tests. + */ + + testID?: string; + } + + /** + * @see https://facebook.github.io/react-native/docs/activityindicatorios.html#props + */ + export interface AlertIOSProperties + { + /** + * animating bool + * + * Whether to show the indicator (true, the default) or hide it (false). + */ + animating?: boolean; + + /** + * color string + * + * The foreground color of the spinner (default is gray). + */ + + color?: string; + + /** + * hidesWhenStopped bool + * + * Whether the indicator should hide when not animating (true by default). + */ + + hidesWhenStopped?: boolean; + + /** + * onLayout function + * + * Invoked on mount and layout changes with + * + * {nativeEvent: { layout: {x, y, width, height}}}. + */ + onLayout?: (event: LayoutChangeEvent) => void; + + /** + * size enum('small', 'large') + * + * Size of the indicator. Small has a height of 20, large has a height of 36. + */ + size: string; // enum('small', 'large') + } + + /** + * @see + */ + export interface SegmentedControlIOSProperties + { + /// TODO + } + + /** + * @see + */ + export interface SwitchIOSProperties + { + /// TODO + } + + /** + * @see + */ + export interface NavigatorProperties + { + /// TODO + } + + /** + * @see + */ + export interface ActivityIndicatorIOSProperties + { + /// TODO + } + + /** + * @see https://facebook.github.io/react-native/docs/sliderios.html + */ + export interface SliderIOSProperties + { + /** + maximumTrackTintColor string + The color used for the track to the right of the button. Overrides the default blue gradient image. + */ + maximumTrackTintColor?: string; + + /** + maximumValue number + + Initial maximum value of the slider. Default value is 1. + */ + maximumValue?: number; + + /** + minimumTrackTintColor string + The color used for the track to the left of the button. Overrides the default blue gradient image. + */ + minimumTrackTintColor?: string; + + /** + minimumValue number + Initial minimum value of the slider. Default value is 0. + */ + minimumValue?: number; + + /** + onSlidingComplete function + Callback called when the user finishes changing the value (e.g. when the slider is released). + */ + onSlidingComplete?: () => void; + + /** + onValueChange function + Callback continuously called while the user is dragging the slider. + */ + onValueChange?: (value: number) => void; + + /** + value number + Initial value of the slider. The value should be between minimumValue and maximumValue, which default to 0 and 1 respectively. Default value is 0. + + This is not a controlled component, e.g. if you don't update the value, the component won't be reset to its inital value. + */ + value?: number; + } + + /** + * @see + */ + export interface CameraRollProperties + { + /// TODO + } + + /** + * @see + */ + export interface ImageProperties + { + /// TODO + } + + /** + * @see + */ + export interface ListViewProperties + { + /// TODO + } + + /** + * @see https://facebook.github.io/react-native/docs/touchablehighlight.html#props + */ + export interface TouchableHighlightProperties + { + /** + * activeOpacity number + * + * Determines what the opacity of the wrapped view should be when touch is active. + */ + activeOpacity?: number; + + /** + * onHideUnderlay function + * + * Called immediately after the underlay is hidden + */ + + onHideUnderlay?: () => void; + + + /** + * onShowUnderlay function + * + * Called immediately after the underlay is shown + */ + + /** + * @see https://facebook.github.io/react-native/docs/view.html#style + */ + style?: ViewStyle; + + + /** + * underlayColor string + * + * The color of the underlay that will show through when the touch is active. + */ + underlayColor?: string; + + } + + /** + * @see https://facebook.github.io/react-native/docs/touchablewithoutfeedback.html + */ + export interface TouchableWithoutFeedbackProperties + { + /* + accessible bool + + Called when the touch is released, but not if cancelled (e.g. by a scroll that steals the responder lock). + */ + accessible?: boolean; + /* + delayLongPress number + + Delay in ms, from onPressIn, before onLongPress is called. + */ + delayLongPress?: number; + + /* + delayPressIn number + + Delay in ms, from the start of the touch, before onPressIn is called. + */ + delayPressIn?: number; + + /* + delayPressOut number + + Delay in ms, from the release of the touch, before onPressOut is called. + */ + delayPressOut?: number; + + /* + onLongPress function + */ + onLongPress?: () => void; + + /* + onPress function + */ + onPress?: () => void; + + /* + onPressIn function + */ + onPressIn?: () => void; + + /* + onPressOut function + */ + onPressOut?: () => void; + } + + + /** + * @see https://facebook.github.io/react-native/docs/touchableopacity.html#props + */ + export interface TouchableOpacityProperties + { + /** + * activeOpacity number + * + * Determines what the opacity of the wrapped view should be when touch is active. + */ + activeOpacity?: number; + } + + + export interface LeftToRightGesture + { + + } + + export interface AnimationInterpolator + { + + } + + // see /NavigatorSceneConfigs.js + export interface SceneConfig + { + // A list of all gestures that are enabled on this scene + gestures: { + pop: LeftToRightGesture, + }, + + // Rebound spring parameters when transitioning FROM this scene + springFriction: number; + springTension: number; + + // Velocity to start at when transitioning without gesture + defaultTransitionVelocity: number; + + // Animation interpolators for horizontal transitioning: + animationInterpolators: { + into: AnimationInterpolator, + out: AnimationInterpolator + }; + + } + + // see /NavigatorSceneConfigs.js + export interface SceneConfigs + { + FloatFromBottom: SceneConfig; + FloatFromRight: SceneConfig; + PushFromRight: SceneConfig; + FloatFromLeft: SceneConfig; + HorizontalSwipeJump: SceneConfig; + } + + export interface Route { + id: string; + title?: string; + } + + /** + * @see + */ + export interface NavigatorBarProperties + { + + } + + export interface NavigationBar extends React.ComponentClass + { + + } + + export interface NavigatorStatic extends React.ComponentClass + { + SceneConfigs: SceneConfigs; + getContext(self:any): NavigatorStatic; + + push(route: Route): void; + pop(): void; + popToTop(): void; + popToRoute( route: Route ): void; + immediatelyResetRouteStack( routes: Route[] ): void; + getCurrentRoutes(): Route[]; + + NavigationBar: NavigationBar; + } + + export interface StyleSheetStatic extends React.ComponentClass + { + create(styles:T): T; + } + + export interface DataSourceAssetCallback + { + rowHasChanged: (r1: any[], r2: any[]) => boolean; + } + + export interface ListViewDataSource + { + new(onAsset: DataSourceAssetCallback): ListViewDataSource; + cloneWithRows(rowList:T[][]): void; + } + + export interface ListViewStatic extends React.ComponentClass + { + DataSource: ListViewDataSource; + } + + export interface ImageStatic extends React.ComponentClass + { + uri: string; + } + + /** + * @see + */ + export interface TabBarItemProperties + { + + } + + export interface TabBarItem extends React.ComponentClass + { + } + + /** + * @see + */ + export interface TabBarIOSProperties + { + } + + export interface TabBarIOSStatic extends React.ComponentClass + { + Item: TabBarItem; + } + + export interface CameraRollFetchParams + { + first: number; + groupTypes: string; + after?: string; + } + + export interface CameraRollNodeInfo + { + image: Image; + group_name: string; + timestamp: number; + location: any; + } + + export interface CameraRollEdgeInfo + { + node: CameraRollNodeInfo; + } + + export interface CameraRollAssetInfo + { + edges: CameraRollEdgeInfo[]; + page_info: { + has_next_page: boolean; + end_cursor: string; + }; + } + + export interface CameraRollStatic extends React.ComponentClass + { + getPhotos(fetch: CameraRollFetchParams, + onAsset: (assetInfo: CameraRollAssetInfo) => void, + logError: ()=> void): void; + } + + export interface PanHandlers + { + + } + + export interface PanResponderEvent + { + + } + + export interface PanResponderGestureState + { + stateID: number; + moveX: number; + moveY: number; + x0: number; + y0: number; + dx: number; + dy: number; + vx: number; + vy: number; + numberActiveTouches: number; + // All `gestureState` accounts for timeStamps up until: + _accountsForMovesUpTo: number; + } + + /** + * @param {object} config Enhanced versions of all of the responder callbacks + * that provide not only the typical `ResponderSyntheticEvent`, but also the + * `PanResponder` gesture state. Simply replace the word `Responder` with + * `PanResponder` in each of the typical `onResponder*` callbacks. For + * example, the `config` object would look like: + * + * - `onMoveShouldSetPanResponder: (e, gestureState) => {...}` + * - `onMoveShouldSetPanResponderCapture: (e, gestureState) => {...}` + * - `onStartShouldSetPanResponder: (e, gestureState) => {...}` + * - `onStartShouldSetPanResponderCapture: (e, gestureState) => {...}` + * - `onPanResponderReject: (e, gestureState) => {...}` + * - `onPanResponderGrant: (e, gestureState) => {...}` + * - `onPanResponderStart: (e, gestureState) => {...}` + * - `onPanResponderEnd: (e, gestureState) => {...}` + * - `onPanResponderRelease: (e, gestureState) => {...}` + * - `onPanResponderMove: (e, gestureState) => {...}` + * - `onPanResponderTerminate: (e, gestureState) => {...}` + * - `onPanResponderTerminationRequest: (e, gestureState) => {...}` + * + * In general, for events that have capture equivalents, we update the + * gestureState once in the capture phase and can use it in the bubble phase + * as well. + * + * Be careful with onStartShould* callbacks. They only reflect updated + * `gestureState` for start/end events that bubble/capture to the Node. + * Once the node is the responder, you can rely on every start/end event + * being processed by the gesture and `gestureState` being updated + * accordingly. (numberActiveTouches) may not be totally accurate unless you + * are the responder. + */ + export interface PanResponderCallbacks + { + onMoveShouldSetPanResponder?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => boolean; + onStartShouldSetPanResponder?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; + onPanResponderGrant?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; + onPanResponderMove?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; + onPanResponderRelease?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; + onPanResponderTerminate?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; + + onMoveShouldSetPanResponderCapture?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => boolean; + onStartShouldSetPanResponderCapture?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => boolean; + onPanResponderReject?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; + onPanResponderStart?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; + onPanResponderEnd?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; + onPanResponderTerminationRequest?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; + } + + export interface PanResponderInstance + { + panHandlers: PanHandlers; + } + + export interface PanResponderStatic + { + create(callbacks: PanResponderCallbacks): PanResponderInstance; + } + + export interface PixelRatioStatic + { + get(): number; + } + + export interface DeviceEventSubscriptionStatic + { + remove(): void; + } + + export interface DeviceEventEmitterStatic + { + addListener(type:string, onReceived: (data:T) => void): DeviceEventSubscription; + } + + // Used by Dimensions below + export interface ScaledSize + { + width: number; + height: number; + scale: number; + } + + // @see https://facebook.github.io/react-native/docs/asyncstorage.html#content + export interface AsyncStorageStatic + { + getItem(key: string, callback?: (error?: Error, result?: string) => void): Promise; + setItem(key: string, value: string, callback?: (error?: Error) => void): Promise; + removeItem(key: string, callback?: (error?: Error) => void): Promise; + mergeItem(key: string, value: string, callback?: (error?: Error) => void): Promise; + clear(callback?: (error?: Error) => void): Promise; + getAllKeys(callback?: (error?: Error, keys?: string[]) => void): Promise; + multiGet(keys: string[], callback?: (errors?: Error[], result?: string[][]) => void): Promise; + multiSet(keyValuePairs: string[][], callback?: (errors?: Error[]) => void): Promise; + multiRemove(keys: string[], callback?: (errors?: Error[]) => void): Promise; + multiMerge(keyValuePairs: string[][], callback?: (errors?: Error[]) => void): Promise; + } + + export interface InteractionManagerStatic + { + runAfterInteractions( fn: () => void ): void; + } + + export interface ScrollViewProperties + { + + } + + + export interface NativeScrollRectangle + { + left: number; + top: number; + bottom: number; + right: number; + } + + export interface NativeScrollPoint + { + x: number; + y: number; + } + + export interface NativeScrollSize + { + height: number; + width: number; + } + + export interface NativeScrollEvent + { + contentInset: NativeScrollRectangle; + contentOffset: NativeScrollPoint; + contentSize: NativeScrollSize; + layoutMeasurement: NativeScrollSize; + zoomScale: number; + } + + export interface AppStateIOSStatic + { + currentState: string; + addEventListener( type: string, listener: (state: string) => void ): void; + removeEventListener( type: string, listener: (state: string) => void ): void; + } + + // exported singletons: + // export var AppRegistry: AppRegistryStatic; + export var StyleSheet: StyleSheetStatic; + export var Navigator: NavigatorStatic; + export type Navigator = NavigatorStatic; + export var ListView: ListViewStatic; + export var CameraRoll: CameraRollStatic; + export var Image: ImageStatic; + export type Image = ImageStatic; + export var TabBarIOS: TabBarIOSStatic; + export type TabBarIOS = TabBarIOSStatic; + export var AsyncStorage: AsyncStorageStatic; + + export var Text: React.ComponentClass; + export var View: React.ComponentClass; + export var AlertIOS: React.ComponentClass; + export var SegmentedControlIOS: React.ComponentClass; + export var SwitchIOS: React.ComponentClass; + export var TouchableHighlight: React.ComponentClass; + export var TouchableOpacity: React.ComponentClass; + export var TouchableWithoutFeedback: React.ComponentClass; + + + export var ActivityIndicatorIOS: React.ComponentClass; + export var PixelRatio: PixelRatioStatic; + export var DeviceEventEmitter: DeviceEventEmitterStatic; + export var DeviceEventSubscription: DeviceEventSubscriptionStatic; + export type DeviceEventSubscription = DeviceEventSubscriptionStatic; + export var InteractionManager: InteractionManagerStatic; + export var ScrollView: React.ComponentClass; + export var PanResponder: PanResponderStatic; + export var SliderIOS: React.ComponentClass; + export var AppStateIOS: AppStateIOSStatic; + + + //react re-exported + export type ReactType = React.ReactType; + + export interface ReactElement

extends React.ReactElement

{} + + export interface ClassicElement

extends React.ClassicElement

{} + + export interface DOMElement

extends React.DOMElement

{} + + export type HTMLElement =React.HTMLElement; + export type SVGElement = React.SVGElement; + + // + // Factories + // ---------------------------------------------------------------------- + + export interface Factory

extends React.Factory

{} + + export interface ClassicFactory

extends React.ClassicFactory

{} + + export interface DOMFactory

extends React.DOMFactory

{} + + export type HTMLFactory = React.HTMLFactory; + export type SVGFactory = React.SVGFactory; + export type SVGElementFactory = React.SVGElementFactory; + + // + // React Nodes + // http://facebook.github.io/react/docs/glossary.html + // ---------------------------------------------------------------------- + + export type ReactText = React.ReactText; + export type ReactChild = React.ReactChild; + + // Should be Array but type aliases cannot be recursive + export type ReactFragment = React.ReactFragment; + export type ReactNode = React.ReactNode; + + // + // Top Level API + // ---------------------------------------------------------------------- + + export function createClass(spec: React.ComponentSpec): React.ClassicComponentClass

; + + export function createFactory

(type: string): React.DOMFactory

; + export function createFactory

(type: React.ClassicComponentClass

| string): React.ClassicFactory

; + export function createFactory

(type: React.ComponentClass

): React.Factory

; + + export function createElement

( + type: string, + props?: P, + ...children: React.ReactNode[]): React.DOMElement

; + export function createElement

( + type: React.ClassicComponentClass

| string, + props?: P, + ...children: React.ReactNode[]): React.ClassicElement

; + export function createElement

( + type: React.ComponentClass

, + props?: P, + ...children: React.ReactNode[]): React.ReactElement

; + + export function cloneElement

( + element: React.DOMElement

, + props?: P, + ...children: React.ReactNode[]): React.DOMElement

; + export function cloneElement

( + element: React.ClassicElement

, + props?: P, + ...children: React.ReactNode[]): React.ClassicElement

; + export function cloneElement

( + element: React.ReactElement

, + props?: P, + ...children: React.ReactNode[]): React.ReactElement

; + + export function isValidElement(object: {}): boolean; + + export var DOM: React.ReactDOM; + export var PropTypes: React.ReactPropTypes; + export var Children: React.ReactChildren; + + // + // Component API + // ---------------------------------------------------------------------- + + // Base component for plain JS classes + export class Component extends React.Component{} + + export interface ClassicComponent extends React.ClassicComponent {} + + export interface DOMComponent

extends ClassicComponent { + tagName: string; + } + + export type HTMLComponent = React.HTMLComponent; + export type SVGComponent = React.SVGComponent + + export interface ChildContextProvider extends React.ChildContextProvider{} + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + export interface ComponentClass

extends React.ComponentClass

{} + + export interface ClassicComponentClass

extends React.ClassicComponentClass

{} + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + export interface ComponentLifecycle extends React.ComponentLifecycle{} + + export interface Mixin extends React.Mixin{} + + export interface ComponentSpec extends React.ComponentSpec{} + + // + // Event System + // ---------------------------------------------------------------------- + + interface SyntheticEvent extends React.SyntheticEvent{} + + interface DragEvent extends React.DragEvent{} + + interface ClipboardEvent extends React.ClipboardEvent{} + + interface KeyboardEvent extends React.KeyboardEvent{} + + + interface FocusEvent extends React.FocusEvent{} + + interface FormEvent extends React.FormEvent {} + + interface MouseEvent extends React.MouseEvent {} + + interface TouchEvent extends React.TouchEvent {} + + interface UIEvent extends React.UIEvent {} + + interface WheelEvent extends React.WheelEvent {} + + // + // Event Handler Types + // ---------------------------------------------------------------------- + + interface EventHandler extends React.EventHandler{} + + interface DragEventHandler extends React.DragEventHandler {} + interface ClipboardEventHandler extends React.ClipboardEventHandler {} + interface KeyboardEventHandler extends React.KeyboardEventHandler {} + interface FocusEventHandler extends React.FocusEventHandler {} + interface FormEventHandler extends React.FormEventHandler {} + interface MouseEventHandler extends React.MouseEventHandler {} + interface TouchEventHandler extends React.TouchEventHandler {} + interface UIEventHandler extends React.UIEventHandler {} + interface WheelEventHandler extends React.WheelEventHandler{} + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + interface Props extends React.Props{} + + interface DOMAttributesBase extends React.DOMAttributesBase{} + + interface DOMAttributes extends React.DOMAttributes{} + + // This interface is not complete. Only properties accepting + // unitless numbers are listed here (see CSSProperty.js in React) + interface CSSProperties extends React.CSSProperties{} + + interface HTMLAttributesBase extends React.HTMLAttributesBase{} + + interface HTMLAttributes extends React.HTMLAttributes{} + + interface SVGElementAttributes extends React.SVGElementAttributes{} + + interface SVGAttributes extends React.SVGAttributes{} + + // + // React.DOM + // ---------------------------------------------------------------------- + + interface ReactDOM extends React.ReactDOM{} + + // + // React.PropTypes + // ---------------------------------------------------------------------- + + interface Validator extends React.Validator{} + + interface Requireable extends React.Requireable {} + + interface ValidationMap extends React.ValidationMap{} + + interface ReactPropTypes extends React.ReactPropTypes{} + + // + // React.Children + // ---------------------------------------------------------------------- + + interface ReactChildren extends React.ReactChildren{} + + // + // Browser Interfaces + // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts + // ---------------------------------------------------------------------- + + interface AbstractView extends React.AbstractView{} + + interface Touch extends React.Touch{} + + interface TouchList extends React.TouchList{} + + + export function __spread(target:any, ...sources:any[]): any; +} + +declare module "react-native" { + + export default ReactNative +} + + + +declare module "Dimensions" +{ + import React from 'react-native'; + + interface Dimensions + { + get(what:string): React.ScaledSize; + } + + var ExportDimensions: Dimensions; + export = ExportDimensions; +} From c4d24f7f7e98fdfa69a0c8a44351375c9f0ab44b Mon Sep 17 00:00:00 2001 From: bgrieder Date: Fri, 6 Nov 2015 22:20:52 +0100 Subject: [PATCH 39/86] Note on using ES6 as the target --- react-native/react-native-tests.tsx | 3 +++ react-native/react-native-tests.tsx.tscparams | 2 +- react-native/react-native.d.ts | 1 + 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/react-native/react-native-tests.tsx b/react-native/react-native-tests.tsx index 4f2ef64d6..7c02ce9ca 100644 --- a/react-native/react-native-tests.tsx +++ b/react-native/react-native-tests.tsx @@ -1,6 +1,9 @@ /* +Note: This must be compiled with the target set to ES6 + + The content of index.io.js could be something like diff --git a/react-native/react-native-tests.tsx.tscparams b/react-native/react-native-tests.tsx.tscparams index bc8c2d622..b928cbf7c 100644 --- a/react-native/react-native-tests.tsx.tscparams +++ b/react-native/react-native-tests.tsx.tscparams @@ -1 +1 @@ ---target es6 --noImplicitAny --jsx react +--target ES6 --noImplicitAny --experimentalDecorators --jsx react diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index fe18baa09..bc1926a30 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -7,6 +7,7 @@ // // This work is mostly based on the work made by Bernd Paradies: https://github.com/bparadie // +// These definitions are meant to be used with the compiler target set to ES6 // // WARNING: this work is very much beta: // -it may be missing react-native definitions From 281006bf74486985e994ddb0e53f7d0b9edb1b03 Mon Sep 17 00:00:00 2001 From: bgrieder Date: Fri, 6 Nov 2015 22:40:15 +0100 Subject: [PATCH 40/86] Test building using es5/commonjs --- react-native/react-native-tests.tsx.tscparams | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react-native/react-native-tests.tsx.tscparams b/react-native/react-native-tests.tsx.tscparams index b928cbf7c..7cf88bb1b 100644 --- a/react-native/react-native-tests.tsx.tscparams +++ b/react-native/react-native-tests.tsx.tscparams @@ -1 +1 @@ ---target ES6 --noImplicitAny --experimentalDecorators --jsx react +--target es5 --noImplicitAny --experimentalDecorators --jsx react --module commonjs From 855dfaafb10cbe5f9338e8d3fe7d8c56720e7b1a Mon Sep 17 00:00:00 2001 From: Bruno Leonardo Michels Date: Fri, 6 Nov 2015 19:42:50 -0200 Subject: [PATCH 41/86] Add new package definition linqsharp --- linqsharp/linqsharp-tests.ts | 90 +++++++ linqsharp/linqsharp.d.ts | 500 +++++++++++++++++++++++++++++++++++ 2 files changed, 590 insertions(+) create mode 100644 linqsharp/linqsharp-tests.ts create mode 100644 linqsharp/linqsharp.d.ts diff --git a/linqsharp/linqsharp-tests.ts b/linqsharp/linqsharp-tests.ts new file mode 100644 index 000000000..5bf05a355 --- /dev/null +++ b/linqsharp/linqsharp-tests.ts @@ -0,0 +1,90 @@ +/// + +import Linq, { LinqSharp } from "linqsharp"; + +var linq: Linq = new Linq([0, 1, 2, 3]); + +var linqResult: Linq; +var linqAny: Linq; +var arrayResult: number[]; + +var numberResult: number; +var boolResult: boolean; + +var comparer: LinqSharp.IEqualityComparer = { + Equals: (x: number, y: number): boolean => + { + return x === y; + }, + GetHashCode: (obj: number): number => + { + return obj.valueOf(); + } +}; + +numberResult = linq.Aggregate((prev: number, next: number) => { return prev + next; }); +boolResult = linq.All((value: number) => value == 0); +boolResult = linq.Any(); +boolResult = linq.Any((value: number) => value == 0); +numberResult = linq.Average(); +numberResult = linq.Average((value: number) => value); +linqResult = linq.Concat([4, 5, 6]); +boolResult = linq.Contains(0); +boolResult = linq.Contains(0, comparer); +numberResult = linq.Count(); +numberResult = linq.Count((value: number) => value == 0); +linqResult = linq.Distinct(); +linqResult = linq.Distinct(comparer); +linqResult = linq.DistinctBy((value: number) => value); +numberResult = linq.ElementAt(0); +numberResult = linq.ElementAtOrDefault(0, 1); +linqResult = linq.Except([2]); +linqResult = linq.Except([2], comparer); +numberResult = linq.First(); +numberResult = linq.First((value: number) => value == 0); +numberResult = linq.FirstOrDefault(); +numberResult = linq.FirstOrDefault((value: number) => value == 0); +linq.ForEach((value: number, index: number) => { }); +linqAny = linq.GroupBy((value: number) => value % 2); +linqAny = linq.GroupBy((value: number) => value % 2, (value: number) => value * 2); +linqAny = linq.GroupBy((value: number) => value % 2, (value: number) => value * 2, comparer); +numberResult = linq.IndexOf(0); +numberResult = linq.IndexOf(0, comparer); +linqResult = linq.Intersect([0]); +linqResult = linq.Intersect([0], comparer); +linqResult = linq.Join([0], (outer: number) => outer, (inner: number) => inner, (outer: number, inner: number) => outer + inner); +linqResult = linq.Join([0], (outer: number) => outer, (inner: number) => inner, (outer: number, inner: number) => outer + inner, comparer); +numberResult = linq.Last(); +numberResult = linq.Last((value: number) => value == 0); +numberResult = linq.LastOrDefault(); +numberResult = linq.LastOrDefault((value: number) => value == 0); +numberResult = linq.Max(); +numberResult = linq.Max((value: number) => value); +numberResult = linq.Min(); +numberResult = linq.Min((value: number) => value); +linqResult = linq.OrderBy((value: number) => value); +linqResult = linq.OrderBy((value: number) => value, comparer); +linqResult = linq.OrderByDescending((value: number) => value); +linqResult = linq.OrderByDescending((value: number) => value, comparer); +linqResult = linq.Reverse(); +linqResult = linq.Select((value: number) => value); +linqResult = linq.Select((value: number, index: number) => value + index); +linqResult = linq.SelectMany((value: number) => [ value ]); +linqResult = linq.SelectMany((value: number) => [ value ], (value: number) => value); +boolResult = linq.SequenceEqual([0]); +boolResult = linq.SequenceEqual([0], comparer); +numberResult = linq.Single(); +numberResult = linq.Single((value: number) => value == 0); +numberResult = linq.SingleOrDefault(); +numberResult = linq.SingleOrDefault((value: number) => value == 0); +linqResult = linq.Skip(0); +linqResult = linq.SkipWhile((value: number) => value < 2); +numberResult = linq.Sum(); +numberResult = linq.Sum((value: number) => value * 2); +linqResult = linq.Take(2); +linqResult = linq.TakeWhile((value: number) => value < 2); +arrayResult = linq.ToArray(); +linqResult = linq.Union([0]); +linqResult = linq.Union([0], comparer); +linqResult = linq.Where((value: number) => value > 0); +linqResult = linq.Zip([0], (outer: number, inner: number) => outer + inner); \ No newline at end of file diff --git a/linqsharp/linqsharp.d.ts b/linqsharp/linqsharp.d.ts new file mode 100644 index 000000000..0ead62cd7 --- /dev/null +++ b/linqsharp/linqsharp.d.ts @@ -0,0 +1,500 @@ +// Type definitions for linqsharp +// Project: https://www.npmjs.com/package/linqsharp +// Definitions by: Bruno Leonardo Michels +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// JSDoc: Extracted and adapted from .NET source code. + +/** + * LinqSharp module defines a helper class with + * .NET's Linq methods. + * + * @module linqsharp + */ +declare module "linqsharp" +{ + export namespace LinqSharp { + /** + * Defines methods to support the comparison of objects for equality. + * + * {T} The type of objects to compare. + */ + export interface IEqualityComparer { + Equals(x: T, y: T): boolean; + GetHashCode(obj: T): number; + } + + /** + * Represents a collection of objects that have a common key. + * + * {TKey} The type of the key. + * {T} The type of the values. + */ + export interface IGrouping { + Key: TKey; + Elements: T[]; + } + + /** + * Gets the HashCode of the object. + * + * @param e Object to compute hash. + * @returns A computed HashCode for the object. + */ + export function GetHashCode(e: any): any; + + /** + * Transforms a object into a string replacing circular + * references by reference tokens. + * + * @param obj Object to convert to string. + * @returns String representation of the object. + */ + export function StringifyNonCircular(obj: any): string; + } + + /** + * Wrapper class for an array that provides Linq functionallity. + * + * @class Linq + */ + class Linq { + /** {T[]} Internal array reference. */ + private a: T[]; + + /** + * Creates a new instance holding an array of . + * @constructor + * + * @param {Array} a Array. + */ + constructor(a?: T[]); + + /** + * Applies an accumulator function over a sequence. + * + * @param func An accumulator function to be + * invoked on each element. + * @param {T} [initialValue] The initial accumulator value. + * + * @throws Error if array is empty. + * + * @returns {T} The final accumulator value. + */ + Aggregate(func: (previous: T, next: T) => TResult, initialValue?: T): T; + + /** + * Determines whether all elements of a sequence satisfy a condition. + * + * @param predicate A function to test each element for a condition. + * + * @returns true if every element of the source sequence passes the test in the specified + * predicate, or if the sequence is empty; otherwise, false. + */ + All(predicate: (value: T) => boolean): boolean; + + /** + * Determines whether a sequence contains any elements. + * + * @param [predicate] A function to test each element for a condition. + * + * @returns true if any elements in the source sequence pass the test in the specified predicate; + * otherwise, false. If no predicate is specified return true if the source sequence contains any elements; + * otherwise, false. + */ + Any(predicate?: (value: T) => boolean): boolean; + + /** + * Computes the average of a sequence of {number} values. + * + * @param [selector] A transform function to apply to each element. + * + * @returns The average of the sequence of values. + */ + Average(selector?: (value: T) => number): number; + + /** + * Concatenates two sequences. + * + * @param array The sequence to concatenate to the first sequence. + * + * @returns An array that contains the concatenated elements of the two input sequences. + */ + Concat(array: T[]): Linq; + + /** + * Determines whether a sequence contains a specified element by using a specified comparer. + * + * @param value The value to locate in the sequence. + * @param [comparer] An IEqualityComparer to compare values. + * + * @returns true if the source sequence contains an element that has the specified value; + * otherwise, false. + */ + Contains(value: T, comparer?: LinqSharp.IEqualityComparer): boolean; + + /** + * Returns a number that represents how many elements in the specified sequence satisfy a condition. + * + * @param [selector] A function to test each element for a condition. + * + * @returns A number that represents how many elements in the sequence satisfy the condition + * in the predicate function. + */ + Count(selector?: (value: T) => boolean): number; + + /** + * Returns distinct elements from a sequence by using a specified IEqualityComparer + * to compare values. + * + * @param [comparer] An IEqualityComparer to compare values. + * + * @returns An array that contains distinct elements from the source sequence. + */ + Distinct(comparer?: LinqSharp.IEqualityComparer): Linq; + + /** + * Returns distinct elements from a sequence by using a specified IEqualityComparer + * to compare values. + * + * @param selector A function to test each element for a condition. + * @param [comparer] An IEqualityComparer to compare values. + * + * @returns An array that contains distinct elements from the source sequence. + */ + DistinctBy(selector: (e: T) => U, comparer?: LinqSharp.IEqualityComparer): Linq; + + /** + * Returns the element at a specified index in a sequence. + * + * @param index The zero-based index of the element to retrieve. + * + * @throws index is less than 0 or greater than or equal to the number of elements in source. + * + * @returns The element at the specified position in the source sequence. + */ + ElementAt(index: number): T; + + /** + * Returns the element at a specified index in a sequence or a default value if + * the index is out of range. + * + * @param index The zero-based index of the element to retrieve. + * @param defaultValue A default value if no element is found. + * + * @returns defaultValue if the index is outside the bounds of the source sequence; + * otherwise, the element at the specified position in the source sequence. + */ + ElementAtOrDefault(index: number, defaultValue: T): T; + + /** + * Produces the set difference of two sequences by using the specified IEqualityComparer + * to compare values. + * + * @param except An array whose elements that also occur in the first sequence will cause + * those elements to be removed from the returned sequence. + * @param [comparer] An IEqualityComparer to compare values. + * + * @returns A sequence that contains the set difference of the elements of two sequences. + */ + Except(except: T[], comparer?: LinqSharp.IEqualityComparer): Linq; + + /** + * Returns the first element in a sequence that satisfies a specified condition. + * + * @param [selector] A function to test each element for a condition. + * + * @throws No element satisfies the condition in predicate.-or-The source sequence is empty. + * + * @returns The first element in the sequence that passes the test in the specified predicate function. + */ + First(selector?: (e: T) => boolean): T; + + /** + * Returns the first element of the sequence that satisfies a condition or a default + * value if no such element is found. + * + * @param [selector] A function to test each element for a condition. + * @param [defaultValue] A default value to return if no element is found. + * + * @returns defaultValue if source is empty or if no element passes the test specified by predicate; + * otherwise, the first element in source that passes the test specified by predicate. + */ + FirstOrDefault(selector?: (e: T) => boolean, defaultValue?: T): T; + + /** + * Performs the specified action on each element of the array. + * + * @param callback The function delegate to perform on each element of the array. + */ + ForEach(callback: (e: T, index: number) => any): void; + + /** + * Groups the elements of a sequence according to a specified key selector function. + * + * @param keySelector A function to extract the key for each element. + * @param [elementSelector] A function to create a result value from each group. + * @param [comparer] An IEqualityComparer to compare keys with. + * + * @returns A collection of elements of type TResult where each element represents a projection + * over a group and its key. + */ + GroupBy(keySelector: (e: T) => TKey, elementSelector?: (e: T) => TElement, comparer?: LinqSharp.IEqualityComparer): Linq; + + /** + * Searches for the specified object and returns the zero-based index of the first + * occurrence within the entire array. + * + * @param e The object to locate in the array. + * @param [comparer] An IEqualityComparer to compare elements with. + * + * @returns The zero-based index of the first occurrence of item within the entire array, if found; + * otherwise, –1. + */ + IndexOf(e: T, comparer?: LinqSharp.IEqualityComparer): number; + + /** + * Produces the set intersection of two sequences by using the specified IEqualityComparer + * to compare values. + * + * @param array An array whose distinct elements that also appear in the first sequence will be returned. + * @param [comparer] An IEqualityComparer to compare values. + * + * @returns A sequence that contains the elements that form the set intersection of two sequences. + */ + Intersect(array: T[], comparer?: LinqSharp.IEqualityComparer): Linq; + + /** + * Correlates the elements of two sequences based on matching keys. A specified IEqualityComparer is used to compare keys. + * + * @param array The sequence to join to the first sequence. + * @param outerKeySelector A function to extract the join key from each element of the first sequence. + * @param innerKeySelector A function to extract the join key from each element of the second sequence. + * @param resultSelector A function to create a result element from two matching elements. + * @param [comparer] An IEqualityComparer to hash and compare keys. + * + * @returns An array that has elements of type TResult that are obtained by performing an inner join on two sequences. + */ + Join(array: TInner[], outerKeySelector: (e: T) => TKey, innerKeySelector: (e: TInner) => TKey, resultSelector: (outer: T, inner: TInner) => TResult, comparer?: LinqSharp.IEqualityComparer): Linq; + + /** + * Returns the last element of a sequence that satisfies a specified condition. + * + * @param [predicate] A function to test each element for a condition. + * + * @throws No element satisfies the condition in predicate.-or-The source sequence is empty. + * + * @returns The last element in the sequence that passes the test in the specified predicate function. + */ + Last(predicate?: (e: T) => boolean): T; + + /** + * Returns the last element of a sequence that satisfies a condition or a default + * value if no such element is found. + * + * @param [predicate] A function to test each element for a condition. + * @param [defaultValue] A default value to return if no element is found. + * + * @returns defaultValue if the sequence is empty or if no elements pass the test in + * the predicate function; otherwise, the last element that passes the test in the + * predicate function. + */ + LastOrDefault(predicate?: (e: T) => boolean, defaultValue?: T): T; + + /** + * Returns the maximum value in a sequence of System.Double values. + * + * @param [selector] A transform function to apply to each element. + * + * @returns The maximum value in the sequence. + */ + Max(): T; + Max(selector?: (e: T) => TResult): TResult; + + /** + * Returns the minimum value in a sequence of System.Int64 values. + * + * @param [selector] A transform function to apply to each element. + * + * @returns The minimum value in the sequence. + */ + Min(): T; + Min(selector?: (e: T) => TResult): TResult; + + /** + * Sorts the elements of a sequence in ascending order according to a key. + * + * @param keySelector A function to extract a key from an element. + * @param [comparer] An IEqualityComparer to compare values. + * + * @returns An array whose elements are sorted according to a key. + */ + OrderBy(keySelector: (e: T) => TKey, comparer?: (a: TKey, b: TKey) => number): Linq; + + /** + * Sorts the elements of a sequence in descending order according to a key. + * + * @param keySelector A function to extract a key from an element. + * @param [comparer] An IEqualityComparer to compare values. + * + * @returns An array whose elements are sorted in descending order according to a key. + */ + OrderByDescending(keySelector: (e: T) => TKey, comparer?: (a: TKey, b: TKey) => number): Linq; + + /** + * Inverts the order of the elements in a sequence. + * + * @returns A sequence whose elements correspond to those of the input sequence in reverse order. + */ + Reverse(): Linq; + + /** + * Projects each element of a sequence into a new form. + * + * @param selector A transform function to apply to each element. + * + * @returns An array whose elements are the result of invoking the transform function on each element of source. + */ + Select(selector: (e: T, i?: number) => TResult): Linq; + + /** + * Projects each element of a sequence to an array flattens the resulting sequences into one sequence, + * and invokes a result selector function on each element therein. + * + * @param selector A transform function to apply to each element of the input sequence. + * @param [resultSelector] A transform function to apply to each element of the intermediate sequence. + * + * @returns An array whose elements are the result of invoking the one-to-many transform function + * selector on each element of source and then mapping each of those sequence elements and + * their corresponding source element to a result element. + */ + SelectMany(selector: (e: T) => T[], resultSelector?: (e: T) => TResult): Linq; + + /** + * Determines whether two sequences are equal by comparing their elements by using + * a specified IEqualityComparer. + * + * @param second An array to compare to the first sequence. + * @param [comparer] An equality comparer to compare values. + * + * @returns true if the two source sequences are of equal length and their corresponding + * elements compare equal according to comparer; otherwise, false. + */ + SequenceEqual(second: T[], comparer?: (a: T, b: T) => boolean): boolean; + + /** + * Returns the only element of a sequence that satisfies a specified condition, + * and throws an exception if more than one such element exists. + * + * @param [predicate] A function to test an element for a condition. + * + * @returns The single element of the input sequence that satisfies a condition. + */ + Single(predicate?: (e: T) => boolean): T; + + /** + * Returns the only element of a sequence that satisfies a specified condition or + * a default value if no such element exists; this method throws an exception if + * more than one element satisfies the condition. + * + * @param [predicate] A function to test an element for a condition. + * @param [defaultValue] A default value if no element is found. + * + * @returns The single element of the input sequence that satisfies the condition, + * or defaultValue if no such element is found. + */ + SingleOrDefault(predicate?: (e: T) => boolean, defaultValue?: T): T; + + /** + * Bypasses a specified number of elements in a sequence and then returns the remaining + * elements. + * + * @param count The number of elements to skip before returning the remaining elements. + * + * @returns An array that contains the elements that occur + * after the specified index in the input sequence. + */ + Skip(count: number): Linq; + + /** + * Bypasses elements in a sequence as long as a specified condition is true and + * then returns the remaining elements. + * + * @param predicate A function to test an element for a condition. + * + * @returns An array that contains the elements from the + * input sequence starting at the first element in the linear series that does not + * pass the test specified by predicate. + */ + SkipWhile(predicate: (e: T) => boolean): Linq; + + /** + * Computes the sum of a sequence values. + * + * @param [selector] A transform function to apply to each element. + * + * @returns The sum of the values in the sequence. + */ + Sum(selector?: (value: T) => number): number; + + /** + * Returns a specified number of contiguous elements from the start of a sequence. + * + * @param count The number of elements to skip before returning the remaining elements. + * + * @returns An array that contains the specified number of elements from the start + * of the input sequence. + */ + Take(count: number): Linq; + + /** + * Returns elements from a sequence as long as a specified condition is true. + * + * @param predicate A function to test an element for a condition. + * + * @returns An array that contains the elements from the + * input sequence that occur before the element at which the test no longer passes. + */ + TakeWhile(predicate: (e: T) => boolean): Linq; + + /** + * Produces the set union of two sequences by using a specified IEqualityComparer. + * + * @param second An array whose distinct elements form the second set for the union. + * @param [comparer] An equality comparer to compare values. + * + * @returns An array that contains the elements from both + * input sequences, excluding duplicates. + */ + Union(second: T[], comparer?: LinqSharp.IEqualityComparer): Linq; + + /** + * Filters a sequence of values based on a predicate. + * + * @param selector A transform function to apply to each element. + * + * @returns An array that contains elements from the input sequence + * that satisfy the condition. + */ + Where(selector: (value: T) => boolean): Linq; + + /** + * Applies a specified function to the corresponding elements of two sequences, + * producing a sequence of the results. + * + * @param array The second sequence to merge. + * @param resultSelector A function that specifies how to merge the elements from the two sequences. + * + * @returns An array that contains merged elements of two input sequences. + */ + Zip(array: TInner[], resultSelector: (o: T, i: TInner) => TResult): Linq; + + /** + * Retrieves the internal array. + * + * @returns Internal array. + */ + ToArray(): T[]; + } + export default Linq; +} From dabc04016862c60be6898eaf30125d1558fe126f Mon Sep 17 00:00:00 2001 From: Bruno Leonardo Michels Date: Fri, 6 Nov 2015 20:04:35 -0200 Subject: [PATCH 42/86] Fix unit tests --- linqsharp/linqsharp-tests.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/linqsharp/linqsharp-tests.ts b/linqsharp/linqsharp-tests.ts index 5bf05a355..ec6b1c725 100644 --- a/linqsharp/linqsharp-tests.ts +++ b/linqsharp/linqsharp-tests.ts @@ -21,6 +21,8 @@ var comparer: LinqSharp.IEqualityComparer = { return obj.valueOf(); } }; +var comparer2: (o: number, i: number) => number; +var comparer3: (o: number, i: number) => boolean; numberResult = linq.Aggregate((prev: number, next: number) => { return prev + next; }); boolResult = linq.All((value: number) => value == 0); @@ -63,16 +65,16 @@ numberResult = linq.Max((value: number) => value); numberResult = linq.Min(); numberResult = linq.Min((value: number) => value); linqResult = linq.OrderBy((value: number) => value); -linqResult = linq.OrderBy((value: number) => value, comparer); +linqResult = linq.OrderBy((value: number) => value, comparer2); linqResult = linq.OrderByDescending((value: number) => value); -linqResult = linq.OrderByDescending((value: number) => value, comparer); +linqResult = linq.OrderByDescending((value: number) => value, comparer2); linqResult = linq.Reverse(); linqResult = linq.Select((value: number) => value); linqResult = linq.Select((value: number, index: number) => value + index); linqResult = linq.SelectMany((value: number) => [ value ]); linqResult = linq.SelectMany((value: number) => [ value ], (value: number) => value); boolResult = linq.SequenceEqual([0]); -boolResult = linq.SequenceEqual([0], comparer); +boolResult = linq.SequenceEqual([0], comparer3); numberResult = linq.Single(); numberResult = linq.Single((value: number) => value == 0); numberResult = linq.SingleOrDefault(); From b2ce26a078c850923a3aa81b7112bfdf7a98af62 Mon Sep 17 00:00:00 2001 From: bgrieder Date: Sat, 7 Nov 2015 07:03:49 +0100 Subject: [PATCH 43/86] Fixed missing exports --- react-native/react-native.d.ts | 74 +++++++++++++++++----------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index bc1926a30..ad6b132ea 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -1142,99 +1142,99 @@ declare namespace ReactNative { // Event System // ---------------------------------------------------------------------- - interface SyntheticEvent extends React.SyntheticEvent{} + export interface SyntheticEvent extends React.SyntheticEvent{} - interface DragEvent extends React.DragEvent{} + export interface DragEvent extends React.DragEvent{} - interface ClipboardEvent extends React.ClipboardEvent{} + export interface ClipboardEvent extends React.ClipboardEvent{} - interface KeyboardEvent extends React.KeyboardEvent{} + export interface KeyboardEvent extends React.KeyboardEvent{} - interface FocusEvent extends React.FocusEvent{} + export interface FocusEvent extends React.FocusEvent{} - interface FormEvent extends React.FormEvent {} + export interface FormEvent extends React.FormEvent {} - interface MouseEvent extends React.MouseEvent {} + export interface MouseEvent extends React.MouseEvent {} - interface TouchEvent extends React.TouchEvent {} + export interface TouchEvent extends React.TouchEvent {} - interface UIEvent extends React.UIEvent {} + export interface UIEvent extends React.UIEvent {} - interface WheelEvent extends React.WheelEvent {} + export interface WheelEvent extends React.WheelEvent {} // // Event Handler Types // ---------------------------------------------------------------------- - interface EventHandler extends React.EventHandler{} + export interface EventHandler extends React.EventHandler{} - interface DragEventHandler extends React.DragEventHandler {} - interface ClipboardEventHandler extends React.ClipboardEventHandler {} - interface KeyboardEventHandler extends React.KeyboardEventHandler {} - interface FocusEventHandler extends React.FocusEventHandler {} - interface FormEventHandler extends React.FormEventHandler {} - interface MouseEventHandler extends React.MouseEventHandler {} - interface TouchEventHandler extends React.TouchEventHandler {} - interface UIEventHandler extends React.UIEventHandler {} - interface WheelEventHandler extends React.WheelEventHandler{} + export interface DragEventHandler extends React.DragEventHandler {} + export interface ClipboardEventHandler extends React.ClipboardEventHandler {} + export interface KeyboardEventHandler extends React.KeyboardEventHandler {} + export interface FocusEventHandler extends React.FocusEventHandler {} + export interface FormEventHandler extends React.FormEventHandler {} + export interface MouseEventHandler extends React.MouseEventHandler {} + export interface TouchEventHandler extends React.TouchEventHandler {} + export interface UIEventHandler extends React.UIEventHandler {} + export interface WheelEventHandler extends React.WheelEventHandler{} // // Props / DOM Attributes // ---------------------------------------------------------------------- - interface Props extends React.Props{} + export interface Props extends React.Props{} - interface DOMAttributesBase extends React.DOMAttributesBase{} + export interface DOMAttributesBase extends React.DOMAttributesBase{} - interface DOMAttributes extends React.DOMAttributes{} + export interface DOMAttributes extends React.DOMAttributes{} // This interface is not complete. Only properties accepting // unitless numbers are listed here (see CSSProperty.js in React) - interface CSSProperties extends React.CSSProperties{} + export interface CSSProperties extends React.CSSProperties{} - interface HTMLAttributesBase extends React.HTMLAttributesBase{} + export interface HTMLAttributesBase extends React.HTMLAttributesBase{} - interface HTMLAttributes extends React.HTMLAttributes{} + export interface HTMLAttributes extends React.HTMLAttributes{} - interface SVGElementAttributes extends React.SVGElementAttributes{} + export interface SVGElementAttributes extends React.SVGElementAttributes{} - interface SVGAttributes extends React.SVGAttributes{} + export interface SVGAttributes extends React.SVGAttributes{} // // React.DOM // ---------------------------------------------------------------------- - interface ReactDOM extends React.ReactDOM{} + export interface ReactDOM extends React.ReactDOM{} // // React.PropTypes // ---------------------------------------------------------------------- - interface Validator extends React.Validator{} + export interface Validator extends React.Validator{} - interface Requireable extends React.Requireable {} + export interface Requireable extends React.Requireable {} - interface ValidationMap extends React.ValidationMap{} + export interface ValidationMap extends React.ValidationMap{} - interface ReactPropTypes extends React.ReactPropTypes{} + export interface ReactPropTypes extends React.ReactPropTypes{} // // React.Children // ---------------------------------------------------------------------- - interface ReactChildren extends React.ReactChildren{} + export interface ReactChildren extends React.ReactChildren{} // // Browser Interfaces // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts // ---------------------------------------------------------------------- - interface AbstractView extends React.AbstractView{} + export interface AbstractView extends React.AbstractView{} - interface Touch extends React.Touch{} + export interface Touch extends React.Touch{} - interface TouchList extends React.TouchList{} + export interface TouchList extends React.TouchList{} export function __spread(target:any, ...sources:any[]): any; From 5d0f0c9085c05c5ac1a06bf52d8cd0b87e4139fd Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Fri, 6 Nov 2015 02:19:46 +0500 Subject: [PATCH 44/86] lodash: signatures of the method _.assign have been changed --- lodash/lodash-tests.ts | 341 +++++++++++++++++++++++++--- lodash/lodash.d.ts | 499 +++++++++++++++++++++++++++-------------- 2 files changed, 649 insertions(+), 191 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..d86326259 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -4285,32 +4285,166 @@ module TestRandom { } } -/********* -* Object * -**********/ -interface NameAge { - name: string; - age: number; +/********** + * Object * + **********/ + +// _.assign +module TestAssign { + interface Obj {a: string}; + interface S1 {a: number}; + interface S2 {b: number}; + interface S3 {c: number}; + interface S4 {d: number}; + interface S5 {e: number}; + + let obj: Obj; + let s1: S1; + let s2: S2; + let s3: S3; + let s4: S4; + let s5: S5; + + let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any; + + { + let result: Obj; + + result = _.assign(obj); + } + + { + let result: {a: number}; + + result = _.assign(obj, s1); + result = _.assign(obj, s1, customizer); + result = _.assign(obj, s1, customizer, any); + } + + { + let result: {a: number, b: number}; + + result = _.assign(obj, s1, s2); + result = _.assign(obj, s1, s2, customizer); + result = _.assign(obj, s1, s2, customizer, any); + } + + { + let result: {a: number, b: number, c: number}; + + result = _.assign(obj, s1, s2, s3); + result = _.assign(obj, s1, s2, s3, customizer); + result = _.assign(obj, s1, s2, s3, customizer, any); + } + + { + let result: {a: number, b: number, c: number, d: number}; + + result = _.assign(obj, s1, s2, s3, s4); + result = _.assign(obj, s1, s2, s3, s4, customizer); + result = _.assign(obj, s1, s2, s3, s4, customizer, any); + } + + { + let result: {a: number, b: number, c: number, d: number, e: number}; + + result = _.assign(obj, s1, s2, s3, s4, s5); + result = _.assign(obj, s1, s2, s3, s4, s5, customizer); + result = _.assign(obj, s1, s2, s3, s4, s5, customizer, any); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _(obj).assign(); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: number}>; + + result = _(obj).assign(s1); + result = _(obj).assign(s1, customizer); + result = _(obj).assign(s1, customizer, any); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: number, b: number}>; + + result = _(obj).assign(s1, s2); + result = _(obj).assign(s1, s2, customizer); + result = _(obj).assign(s1, s2, customizer, any); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number}>; + + result = _(obj).assign(s1, s2, s3); + result = _(obj).assign(s1, s2, s3, customizer); + result = _(obj).assign(s1, s2, s3, customizer, any); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + + result = _(obj).assign(s1, s2, s3, s4); + result = _(obj).assign(s1, s2, s3, s4, customizer); + result = _(obj).assign(s1, s2, s3, s4, customizer, any); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + + result = _(obj).assign<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); + result = _(obj).assign<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5, customizer); + result = _(obj).assign<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5, customizer, any); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(obj).chain().assign(); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: number}>; + + result = _(obj).chain().assign(s1); + result = _(obj).chain().assign(s1, customizer); + result = _(obj).chain().assign(s1, customizer, any); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: number, b: number}>; + + result = _(obj).chain().assign(s1, s2); + result = _(obj).chain().assign(s1, s2, customizer); + result = _(obj).chain().assign(s1, s2, customizer, any); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number}>; + + result = _(obj).chain().assign(s1, s2, s3); + result = _(obj).chain().assign(s1, s2, s3, customizer); + result = _(obj).chain().assign(s1, s2, s3, customizer, any); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + + result = _(obj).chain().assign(s1, s2, s3, s4); + result = _(obj).chain().assign(s1, s2, s3, s4, customizer); + result = _(obj).chain().assign(s1, s2, s3, s4, customizer, any); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + + result = _(obj).chain().assign<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); + result = _(obj).chain().assign<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5, customizer); + result = _(obj).chain().assign<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5, customizer, any); + } } -result = _.assign({ 'name': 'moe' }, { 'age': 40 }); -result = _.assign({ 'name': 'moe' }, { 'age': 40 }, function (a, b) { - return typeof a == 'undefined' ? b : a; -}); - -result = <_.LoDashImplicitObjectWrapper>_({ 'name': 'moe' }).assign({ 'age': 40 }); -result = <_.LoDashImplicitObjectWrapper>_({ 'name': 'moe' }).assign({ 'age': 40 }, function (a, b) { - return typeof a == 'undefined' ? b : a; -}); - -result = _.extend({ 'name': 'moe' }, { 'age': 40 }); -result = _.extend({ 'name': 'moe' }, { 'age': 40 }, function (a, b) { - return typeof a == 'undefined' ? b : a; -}); - -result = <_.LoDashImplicitObjectWrapper>_({ 'name': 'moe' }).extend({ 'age': 40 }); -result = <_.LoDashImplicitObjectWrapper>_({ 'name': 'moe' }).extend({ 'age': 40 }, function (a, b) { - return typeof a == 'undefined' ? b : a; -}); // _.create interface TestCreateProto { @@ -4351,6 +4485,163 @@ var TestDefaultsDeepSource = {'user': {'name': 'fred', 'age': 36}}; result = _.defaultsDeep(TestDefaultsDeepObject, TestDefaultsDeepSource); result = _(TestDefaultsDeepObject).defaultsDeep(TestDefaultsDeepSource).value(); +// _.extend +module TestExtend { + type Obj = {a: string}; + type S1 = {a: number}; + type S2 = {b: number}; + type S3 = {c: number}; + type S4 = {d: number}; + type S5 = {e: number}; + + let obj: Obj; + let s1: S1; + let s2: S2; + let s3: S3; + let s4: S4; + let s5: S5; + + let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any; + + { + let result: Obj; + + result = _.extend(obj); + } + + { + let result: {a: number}; + + result = _.extend(obj, s1); + result = _.extend(obj, s1, customizer); + result = _.extend(obj, s1, customizer, any); + } + + { + let result: {a: number, b: number}; + + result = _.extend(obj, s1, s2); + result = _.extend(obj, s1, s2, customizer); + result = _.extend(obj, s1, s2, customizer, any); + } + + { + let result: {a: number, b: number, c: number}; + + result = _.extend(obj, s1, s2, s3); + result = _.extend(obj, s1, s2, s3, customizer); + result = _.extend(obj, s1, s2, s3, customizer, any); + } + + { + let result: {a: number, b: number, c: number, d: number}; + + result = _.extend(obj, s1, s2, s3, s4); + result = _.extend(obj, s1, s2, s3, s4, customizer); + result = _.extend(obj, s1, s2, s3, s4, customizer, any); + } + + { + let result: {a: number, b: number, c: number, d: number, e: number}; + + result = _.extend(obj, s1, s2, s3, s4, s5); + result = _.extend(obj, s1, s2, s3, s4, s5, customizer); + result = _.extend(obj, s1, s2, s3, s4, s5, customizer, any); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _(obj).extend(); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: number}>; + + result = _(obj).extend(s1); + result = _(obj).extend(s1, customizer); + result = _(obj).extend(s1, customizer, any); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: number, b: number}>; + + result = _(obj).extend(s1, s2); + result = _(obj).extend(s1, s2, customizer); + result = _(obj).extend(s1, s2, customizer, any); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number}>; + + result = _(obj).extend(s1, s2, s3); + result = _(obj).extend(s1, s2, s3, customizer); + result = _(obj).extend(s1, s2, s3, customizer, any); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + + result = _(obj).extend(s1, s2, s3, s4); + result = _(obj).extend(s1, s2, s3, s4, customizer); + result = _(obj).extend(s1, s2, s3, s4, customizer, any); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + + result = _(obj).extend(s1, s2, s3, s4, s5); + result = _(obj).extend(s1, s2, s3, s4, s5, customizer); + result = _(obj).extend(s1, s2, s3, s4, s5, customizer, any); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(obj).chain().extend(); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: number}>; + + result = _(obj).chain().extend(s1); + result = _(obj).chain().extend(s1, customizer); + result = _(obj).chain().extend(s1, customizer, any); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: number, b: number}>; + + result = _(obj).chain().extend(s1, s2); + result = _(obj).chain().extend(s1, s2, customizer); + result = _(obj).chain().extend(s1, s2, customizer, any); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number}>; + + result = _(obj).chain().extend(s1, s2, s3); + result = _(obj).chain().extend(s1, s2, s3, customizer); + result = _(obj).chain().extend(s1, s2, s3, customizer, any); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + + result = _(obj).chain().extend(s1, s2, s3, s4); + result = _(obj).chain().extend(s1, s2, s3, s4, customizer); + result = _(obj).chain().extend(s1, s2, s3, s4, customizer, any); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + + result = _(obj).chain().extend(s1, s2, s3, s4, s5); + result = _(obj).chain().extend(s1, s2, s3, s4, s5, customizer); + result = _(obj).chain().extend(s1, s2, s3, s4, s5, customizer, any); + } +} + // _.findKey module TestFindKey { let result: string; diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..05c3f43b9 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -8922,195 +8922,191 @@ declare module _ { **********/ //_.assign + interface AssignCustomizer { + (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}): any; + } + interface LoDashStatic { /** - * Assigns own enumerable properties of source object(s) to the destination object. Subsequent - * sources will overwrite property assignments of previous sources. If a callback is provided - * it will be executed to produce the assigned values. The callback is bound to thisArg and - * invoked with two arguments; (objectValue, sourceValue). - * @param object The destination object. - * @param s1-8 The source object(s) - * @param callback The function to customize merging properties. - * @param thisArg The this binding of callback. - * @return The destination object. - **/ - assign( - object: T, - s1: S1, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; + * Assigns own enumerable properties of source object(s) to the destination object. Subsequent sources + * overwrite property assignments of previous sources. If customizer is provided it’s invoked to produce the + * assigned values. The customizer is bound to thisArg and invoked with five arguments: + * (objectValue, sourceValue, key, object, source). + * + * Note: This method mutates object and is based on Object.assign. + * + * @alias _.extend + * + * @param object The destination object. + * @param source The source objects. + * @param customizer The function to customize assigned values. + * @param thisArg The this binding of callback. + * @return The destination object. + */ + assign( + object: TObject, + source: TSource, + customizer?: AssignCustomizer, + thisArg?: any + ): TResult; /** - * @see _.assign - **/ - assign( - object: T, - s1: S1, - s2: S2, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; + * @see assign + */ + assign( + object: TObject, + source1: TSource1, + source2: TSource2, + customizer?: AssignCustomizer, + thisArg?: any + ): TResult; /** - * @see _.assign - **/ - assign( - object: T, - s1: S1, - s2: S2, - s3: S3, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; + * @see assign + */ + assign( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer?: AssignCustomizer, + thisArg?: any + ): TResult; /** - * @see _.assign - **/ - assign( - object: T, - s1: S1, - s2: S2, - s3: S3, - s4: S4, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; + * @see assign + */ + assign + ( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer?: AssignCustomizer, + thisArg?: any + ): TResult; /** - * @see _.assign - **/ - extend( - object: T, - s1: S1, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; + * @see _.assign + */ + assign(object: TObject): TObject; /** - * @see _.assign - **/ - extend( - object: T, - s1: S1, - s2: S2, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - - /** - * @see _.assign - **/ - extend( - object: T, - s1: S1, - s2: S2, - s3: S3, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; - - /** - * @see _.assign - **/ - extend( - object: T, - s1: S1, - s2: S2, - s3: S3, - s4: S4, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): Result; + * @see _.assign + */ + assign( + object: TObject, ...otherArgs: any[] + ): TResult; } interface LoDashImplicitObjectWrapper { /** - * @see _.assign - **/ - assign( - s1: S1, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; + * @see _.assign + */ + assign( + source: TSource, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashImplicitObjectWrapper; /** - * @see _.assign - **/ - assign( - s1: S1, - s2: S2, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - /** - * @see _.assign - **/ - assign( - s1: S1, - s2: S2, - s3: S3, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - /** - * @see _.assign - **/ - assign( - s1: S1, - s2: S2, - s3: S3, - s4: S4, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - /** - * @see _.assign - **/ - assign( - s1: S1, - s2: S2, - s3: S3, - s4: S4, - s5: S5, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; + * @see assign + */ + assign( + source1: TSource1, + source2: TSource2, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashImplicitObjectWrapper; /** - * @see _.assign - **/ - extend( - s1: S1, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; + * @see assign + */ + assign( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashImplicitObjectWrapper; /** - * @see _.assign - **/ - extend( - s1: S1, - s2: S2, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - /** - * @see _.assign - **/ - extend( - s1: S1, - s2: S2, - s3: S3, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - /** - * @see _.assign - **/ - extend( - s1: S1, - s2: S2, - s3: S3, - s4: S4, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; - /** - * @see _.assign - **/ - extend( - s1: S1, - s2: S2, - s3: S3, - s4: S4, - s5: S5, - callback?: (objectValue: Value, sourceValue: Value) => Value, - thisArg?: any): TResult; + * @see assign + */ + assign( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashImplicitObjectWrapper; + /** + * @see _.assign + */ + assign(): LoDashImplicitObjectWrapper; + + /** + * @see _.assign + */ + assign(...otherArgs: any[]): LoDashImplicitObjectWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.assign + */ + assign( + source: TSource, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashExplicitObjectWrapper; + + /** + * @see assign + */ + assign( + source1: TSource1, + source2: TSource2, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashExplicitObjectWrapper; + + /** + * @see assign + */ + assign( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashExplicitObjectWrapper; + + /** + * @see assign + */ + assign( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashExplicitObjectWrapper; + + /** + * @see _.assign + */ + assign(): LoDashExplicitObjectWrapper; + + /** + * @see _.assign + */ + assign(...otherArgs: any[]): LoDashExplicitObjectWrapper; } //_.create @@ -9174,6 +9170,177 @@ declare module _ { defaultsDeep(...sources: any[]): LoDashImplicitObjectWrapper } + //_.extend + interface LoDashStatic { + /** + * @see assign + */ + extend( + object: TObject, + source: TSource, + customizer?: AssignCustomizer, + thisArg?: any + ): TResult; + + /** + * @see assign + */ + extend( + object: TObject, + source1: TSource1, + source2: TSource2, + customizer?: AssignCustomizer, + thisArg?: any + ): TResult; + + /** + * @see assign + */ + extend( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer?: AssignCustomizer, + thisArg?: any + ): TResult; + + /** + * @see assign + */ + extend + ( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer?: AssignCustomizer, + thisArg?: any + ): TResult; + + /** + * @see _.assign + */ + extend(object: TObject): TObject; + + /** + * @see _.assign + */ + extend( + object: TObject, ...otherArgs: any[] + ): TResult; + } + + interface LoDashImplicitObjectWrapper { + /** + * @see _.assign + */ + extend( + source: TSource, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashImplicitObjectWrapper; + + /** + * @see assign + */ + extend( + source1: TSource1, + source2: TSource2, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashImplicitObjectWrapper; + + /** + * @see assign + */ + extend( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashImplicitObjectWrapper; + + /** + * @see assign + */ + extend( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashImplicitObjectWrapper; + + /** + * @see _.assign + */ + extend(): LoDashImplicitObjectWrapper; + + /** + * @see _.assign + */ + extend(...otherArgs: any[]): LoDashImplicitObjectWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.assign + */ + extend( + source: TSource, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashExplicitObjectWrapper; + + /** + * @see assign + */ + extend( + source1: TSource1, + source2: TSource2, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashExplicitObjectWrapper; + + /** + * @see assign + */ + extend( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashExplicitObjectWrapper; + + /** + * @see assign + */ + extend( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer?: AssignCustomizer, + thisArg?: any + ): LoDashExplicitObjectWrapper; + + /** + * @see _.assign + */ + extend(): LoDashExplicitObjectWrapper; + + /** + * @see _.assign + */ + extend(...otherArgs: any[]): LoDashExplicitObjectWrapper; + } + //_.findKey interface LoDashStatic { /** From 00d496b4c45cc4050ebc0943729b5ce03951fd4e Mon Sep 17 00:00:00 2001 From: bgrieder Date: Sat, 7 Nov 2015 08:27:42 +0100 Subject: [PATCH 45/86] added FlexStyle and ImageProperties --- react-native/react-native.d.ts | 584 ++++++++++++++++++--------------- 1 file changed, 326 insertions(+), 258 deletions(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index ad6b132ea..592cecdaf 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -33,14 +33,14 @@ declare namespace ReactNative { * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ - then(onfulfilled?: (value: T) => TResult | Promise, onrejected?: (reason: any) => TResult | Promise): Promise; + then( onfulfilled?: ( value: T ) => TResult | Promise, onrejected?: ( reason: any ) => TResult | Promise ): Promise; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ - catch(onrejected?: (reason: any) => T | Promise): Promise; + catch( onrejected?: ( reason: any ) => T | Promise ): Promise; // not in lib.es6.d.ts but called by react-native @@ -59,9 +59,9 @@ declare namespace ReactNative { * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ - new (init: (resolve: (value?: T | Promise) => void, reject: (reason?: any) => void) => void): Promise; + new ( init: ( resolve: ( value?: T | Promise ) => void, reject: ( reason?: any ) => void ) => void ): Promise; - (init: (resolve: (value?: T | Promise) => void, reject: (reason?: any) => void) => void): Promise; + ( init: ( resolve: ( value?: T | Promise ) => void, reject: ( reason?: any ) => void ) => void ): Promise; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises @@ -69,7 +69,7 @@ declare namespace ReactNative { * @param values An array of Promises. * @returns A new Promise. */ - all(values: (T | Promise)[]): Promise; + all( values: (T | Promise)[] ): Promise; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises @@ -77,7 +77,7 @@ declare namespace ReactNative { * @param values An array of values. * @returns A new Promise. */ - all(values: Promise[]): Promise; + all( values: Promise[] ): Promise; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved @@ -85,28 +85,28 @@ declare namespace ReactNative { * @param values An array of Promises. * @returns A new Promise. */ - race(values: (T | Promise)[]): Promise; + race( values: (T | Promise)[] ): Promise; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject( reason: any ): Promise; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject( reason: any ): Promise; /** * Creates a new resolved promise for the provided value. * @param value A promise. * @returns A promise whose internal state matches the provided promise. */ - resolve(value: T | Promise): Promise; + resolve( value: T | Promise ): Promise; /** * Creates a new resolved promise . @@ -119,19 +119,17 @@ declare namespace ReactNative { export var Promise: PromiseConstructor; // node_modules/react-tools/src/classic/class/ReactClass.js - export interface ReactClass - { + export interface ReactClass { // TODO: } // see react-jsx.d.ts - export function createElement

( - type: React.ReactType, - props?: P, - ...children: React.ReactNode[]): React.ReactElement

; + export function createElement

( type: React.ReactType, + props?: P, + ...children: React.ReactNode[] ): React.ReactElement

; - export type Runnable = (appParameters:any) => void; + export type Runnable = ( appParameters: any ) => void; export type AppConfig = { appKey: string; @@ -140,12 +138,14 @@ declare namespace ReactNative { } // https://github.com/facebook/react-native/blob/master/Libraries/AppRegistry/AppRegistry.js - export class AppRegistry - { - static registerConfig(config: AppConfig[]): void; - static registerComponent(appKey: string, getComponentFunc: () => React.ComponentClass): string; - static registerRunnable(appKey: string, func: Runnable): string; - static runApplication(appKey: string, appParameters: any): void; + export class AppRegistry { + static registerConfig( config: AppConfig[] ): void; + + static registerComponent( appKey: string, getComponentFunc: () => React.ComponentClass ): string; + + static registerRunnable( appKey: string, func: Runnable ): string; + + static runApplication( appKey: string, appParameters: any ): void; } /* @@ -160,14 +160,52 @@ declare namespace ReactNative { } */ + /** + * Flex Prop Types + * @see https://facebook.github.io/react-native/docs/flexbox.html#proptypes + */ + export interface FlexStyle { - export interface StyleSheetProperties - { + alignItems?: string; //enum('flex-start', 'flex-end', 'center', 'stretch') + alignSelf?: string// enum('auto', 'flex-start', 'flex-end', 'center', 'stretch') + borderBottomWidth?: number + borderLeftWidth?: number + borderRightWidth?: number + borderTopWidth?: number + borderWidth?: number + bottom?: number + flex?: number + flexDirection?: string // enum('row', 'column') + flexWrap?: string // enum('wrap', 'nowrap') + height?: number + justifyContent?: string // enum('flex-start', 'flex-end', 'center', 'space-between', 'space-around') + left?: number + margin?: number + marginBottom?: number + marginHorizontal?: number + marginLeft?: number + marginRight?: number + marginTop?: number + marginVertical?: number + padding?: number + paddingBottom?: number + paddingHorizontal?: number + paddingLeft?: number + paddingRight?: number + paddingTop?: number + paddingVertical?: number + position?: string // enum('absolute', 'relative') + right?: number + top?: number + width?: number + } + + + export interface StyleSheetProperties { // TODO: } - export interface LayoutRectangle - { + export interface LayoutRectangle { x: number; y: number; width: number; @@ -175,16 +213,14 @@ declare namespace ReactNative { } // @see TextProperties.onLayout - export interface LayoutChangeEvent - { + export interface LayoutChangeEvent { nativeEvent: { layout: LayoutRectangle } } // @see https://facebook.github.io/react-native/docs/text.html#style - export interface TextStyle - { + export interface TextStyle extends FlexStyle{ color?: string; containerBackgroundColor?: string; fontFamily?: string; @@ -198,8 +234,7 @@ declare namespace ReactNative { } // https://facebook.github.io/react-native/docs/text.html#props - export interface TextProperties - { + export interface TextProperties { /** * numberOfLines number * @@ -214,7 +249,7 @@ declare namespace ReactNative { * * {nativeEvent: { layout: {x, y, width, height}}}. */ - onLayout?: (event: LayoutChangeEvent) => void; + onLayout?: ( event: LayoutChangeEvent ) => void; /** * onPress function @@ -229,14 +264,12 @@ declare namespace ReactNative { style?: TextStyle; } - export interface AccessibilityTraits - { + export interface AccessibilityTraits { // TODO } // @see https://facebook.github.io/react-native/docs/view.html#style - export interface ViewStyle - { + export interface ViewStyle extends FlexStyle { backgroundColor?: string; borderBottomColor?: string; borderBottomLeftRadius?: number; @@ -259,8 +292,7 @@ declare namespace ReactNative { /** * @see https://facebook.github.io/react-native/docs/view.html#props */ - export interface ViewProperties - { + export interface ViewProperties { /** * accessibilityLabel string * @@ -301,7 +333,7 @@ declare namespace ReactNative { * * {nativeEvent: { layout: {x, y, width, height}}}. */ - onLayout?: (event: LayoutChangeEvent) => void; + onLayout?: ( event: LayoutChangeEvent ) => void; /** * onMagicTap function @@ -397,8 +429,7 @@ declare namespace ReactNative { /** * @see https://facebook.github.io/react-native/docs/activityindicatorios.html#props */ - export interface AlertIOSProperties - { + export interface AlertIOSProperties { /** * animating bool * @@ -429,7 +460,7 @@ declare namespace ReactNative { * * {nativeEvent: { layout: {x, y, width, height}}}. */ - onLayout?: (event: LayoutChangeEvent) => void; + onLayout?: ( event: LayoutChangeEvent ) => void; /** * size enum('small', 'large') @@ -442,40 +473,35 @@ declare namespace ReactNative { /** * @see */ - export interface SegmentedControlIOSProperties - { + export interface SegmentedControlIOSProperties { /// TODO } /** * @see */ - export interface SwitchIOSProperties - { + export interface SwitchIOSProperties { /// TODO } /** * @see */ - export interface NavigatorProperties - { + export interface NavigatorProperties { /// TODO } /** * @see */ - export interface ActivityIndicatorIOSProperties - { + export interface ActivityIndicatorIOSProperties { /// TODO } /** * @see https://facebook.github.io/react-native/docs/sliderios.html */ - export interface SliderIOSProperties - { + export interface SliderIOSProperties { /** maximumTrackTintColor string The color used for the track to the right of the button. Overrides the default blue gradient image. @@ -511,7 +537,7 @@ declare namespace ReactNative { onValueChange function Callback continuously called while the user is dragging the slider. */ - onValueChange?: (value: number) => void; + onValueChange?: ( value: number ) => void; /** value number @@ -525,32 +551,124 @@ declare namespace ReactNative { /** * @see */ - export interface CameraRollProperties - { + export interface CameraRollProperties { /// TODO } + /** + * Image style + * @see https://facebook.github.io/react-native/docs/image.html#style + */ + export interface ImageStyle extends FlexStyle{ + color?: string; + containerBackgroundColor?: string; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; // 'normal' | 'italic'; + fontWeight?: string; // enum("normal", 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900') + letterSpacing?: number; + lineHeight?: number; + textAlign?: string; // enum("auto", 'left', 'right', 'center') + writingDirection?: string; //enum("auto", 'ltr', 'rtl') + } + + /** + * @see https://facebook.github.io/react-native/docs/image.html + */ + export interface ImageProperties { + /** + * onLayout function + * + * Invoked on mount and layout changes with + * + * {nativeEvent: { layout: {x, y, width, height}}}. + */ + onLayout?: ( event: LayoutChangeEvent ) => void; + + + /** + * Determines how to resize the image when the frame doesn't match the raw image dimensions. + */ + resizeMode?: string; // enum('cover', 'contain', 'stretch') + + /** + * uri is a string representing the resource identifier for the image, + * which could be an http address, a local file path, + * or the name of a static image resource (which should be wrapped in the require('image!name') function). + */ + source: {uri: string} | string; + + /** + * + * Style + */ + style?: ImageStyle; + + /** + * A unique identifier for this element to be used in UI Automation testing scripts. + */ + testID?: string; + + /** + * The text that's read by the screen reader when the user interacts with the image. + */ + iosaccessibilityLabel?: string; + + /** + * When true, indicates the image is an accessibility element. + */ + iosaccessible?: boolean; + + /** + * When the image is resized, the corners of the size specified by capInsets will stay a fixed size, + * but the center content and borders of the image will be stretched. + * This is useful for creating resizable rounded buttons, shadows, and other resizable assets. + * More info on Apple documentation + */ + ioscapInsets?: {top: number, left: number, bottom: number, right: number} + + /** + * A static image to display while downloading the final image off the network. + */ + iosdefaultSource?: {uri: string} + + /** + * Invoked on load error with {nativeEvent: {error}} + */ + iosonError?: ( error: {nativeEvent: any} ) => void + + /** + * Invoked when load completes successfully + */ + iosonLoad?: () => void + + /** + * Invoked when load either succeeds or fails + */ + iosonLoadEnd?: () => void + + /** + * Invoked on load start + */ + iosonLoadStart?: () => void + + /** + * Invoked on download progress with {nativeEvent: {loaded, total}} + */ + iosonProgress?: ()=> void + } + /** * @see */ - export interface ImageProperties - { - /// TODO - } - - /** - * @see - */ - export interface ListViewProperties - { + export interface ListViewProperties { /// TODO } /** * @see https://facebook.github.io/react-native/docs/touchablehighlight.html#props */ - export interface TouchableHighlightProperties - { + export interface TouchableHighlightProperties { /** * activeOpacity number * @@ -591,8 +709,7 @@ declare namespace ReactNative { /** * @see https://facebook.github.io/react-native/docs/touchablewithoutfeedback.html */ - export interface TouchableWithoutFeedbackProperties - { + export interface TouchableWithoutFeedbackProperties { /* accessible bool @@ -645,8 +762,7 @@ declare namespace ReactNative { /** * @see https://facebook.github.io/react-native/docs/touchableopacity.html#props */ - export interface TouchableOpacityProperties - { + export interface TouchableOpacityProperties { /** * activeOpacity number * @@ -656,19 +772,16 @@ declare namespace ReactNative { } - export interface LeftToRightGesture - { + export interface LeftToRightGesture { } - export interface AnimationInterpolator - { + export interface AnimationInterpolator { } // see /NavigatorSceneConfigs.js - export interface SceneConfig - { + export interface SceneConfig { // A list of all gestures that are enabled on this scene gestures: { pop: LeftToRightGesture, @@ -690,8 +803,7 @@ declare namespace ReactNative { } // see /NavigatorSceneConfigs.js - export interface SceneConfigs - { + export interface SceneConfigs { FloatFromBottom: SceneConfig; FloatFromRight: SceneConfig; PushFromRight: SceneConfig; @@ -707,22 +819,19 @@ declare namespace ReactNative { /** * @see */ - export interface NavigatorBarProperties - { + export interface NavigatorBarProperties { } - export interface NavigationBar extends React.ComponentClass - { + export interface NavigationBar extends React.ComponentClass { } - export interface NavigatorStatic extends React.ComponentClass - { + export interface NavigatorStatic extends React.ComponentClass { SceneConfigs: SceneConfigs; - getContext(self:any): NavigatorStatic; + getContext( self: any ): NavigatorStatic; - push(route: Route): void; + push( route: Route ): void; pop(): void; popToTop(): void; popToRoute( route: Route ): void; @@ -732,78 +841,65 @@ declare namespace ReactNative { NavigationBar: NavigationBar; } - export interface StyleSheetStatic extends React.ComponentClass - { - create(styles:T): T; + export interface StyleSheetStatic extends React.ComponentClass { + create( styles: T ): T; } - export interface DataSourceAssetCallback - { - rowHasChanged: (r1: any[], r2: any[]) => boolean; + export interface DataSourceAssetCallback { + rowHasChanged: ( r1: any[], r2: any[] ) => boolean; } - export interface ListViewDataSource - { - new(onAsset: DataSourceAssetCallback): ListViewDataSource; - cloneWithRows(rowList:T[][]): void; + export interface ListViewDataSource { + new( onAsset: DataSourceAssetCallback ): ListViewDataSource; + cloneWithRows( rowList: T[][] ): void; } - export interface ListViewStatic extends React.ComponentClass - { + export interface ListViewStatic extends React.ComponentClass { DataSource: ListViewDataSource; } - export interface ImageStatic extends React.ComponentClass - { + export interface ImageStatic extends React.ComponentClass { uri: string; } /** * @see */ - export interface TabBarItemProperties - { + export interface TabBarItemProperties { } - export interface TabBarItem extends React.ComponentClass - { + export interface TabBarItem extends React.ComponentClass { } /** * @see */ - export interface TabBarIOSProperties - { + export interface TabBarIOSProperties { } - export interface TabBarIOSStatic extends React.ComponentClass - { + export interface TabBarIOSStatic extends React.ComponentClass { Item: TabBarItem; } - export interface CameraRollFetchParams - { + export interface CameraRollFetchParams { first: number; groupTypes: string; after?: string; } - export interface CameraRollNodeInfo - { + export interface CameraRollNodeInfo { image: Image; group_name: string; timestamp: number; location: any; } - export interface CameraRollEdgeInfo - { + export interface CameraRollEdgeInfo { node: CameraRollNodeInfo; } - export interface CameraRollAssetInfo - { + export interface CameraRollAssetInfo { edges: CameraRollEdgeInfo[]; page_info: { has_next_page: boolean; @@ -811,25 +907,21 @@ declare namespace ReactNative { }; } - export interface CameraRollStatic extends React.ComponentClass - { - getPhotos(fetch: CameraRollFetchParams, - onAsset: (assetInfo: CameraRollAssetInfo) => void, - logError: ()=> void): void; + export interface CameraRollStatic extends React.ComponentClass { + getPhotos( fetch: CameraRollFetchParams, + onAsset: ( assetInfo: CameraRollAssetInfo ) => void, + logError: ()=> void ): void; } - export interface PanHandlers - { + export interface PanHandlers { } - export interface PanResponderEvent - { + export interface PanResponderEvent { } - export interface PanResponderGestureState - { + export interface PanResponderGestureState { stateID: number; moveX: number; moveY: number; @@ -875,104 +967,90 @@ declare namespace ReactNative { * accordingly. (numberActiveTouches) may not be totally accurate unless you * are the responder. */ - export interface PanResponderCallbacks - { - onMoveShouldSetPanResponder?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => boolean; - onStartShouldSetPanResponder?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; - onPanResponderGrant?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; - onPanResponderMove?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; - onPanResponderRelease?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; - onPanResponderTerminate?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; + export interface PanResponderCallbacks { + onMoveShouldSetPanResponder?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => boolean; + onStartShouldSetPanResponder?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderGrant?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderMove?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderRelease?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderTerminate?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; - onMoveShouldSetPanResponderCapture?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => boolean; - onStartShouldSetPanResponderCapture?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => boolean; - onPanResponderReject?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; - onPanResponderStart?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; - onPanResponderEnd?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; - onPanResponderTerminationRequest?: (e: PanResponderEvent, gestureState: PanResponderGestureState) => void; + onMoveShouldSetPanResponderCapture?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => boolean; + onStartShouldSetPanResponderCapture?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => boolean; + onPanResponderReject?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderStart?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderEnd?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderTerminationRequest?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; } - export interface PanResponderInstance - { + export interface PanResponderInstance { panHandlers: PanHandlers; } - export interface PanResponderStatic - { - create(callbacks: PanResponderCallbacks): PanResponderInstance; + export interface PanResponderStatic { + create( callbacks: PanResponderCallbacks ): PanResponderInstance; } - export interface PixelRatioStatic - { + export interface PixelRatioStatic { get(): number; } - export interface DeviceEventSubscriptionStatic - { + export interface DeviceEventSubscriptionStatic { remove(): void; } - export interface DeviceEventEmitterStatic - { - addListener(type:string, onReceived: (data:T) => void): DeviceEventSubscription; + export interface DeviceEventEmitterStatic { + addListener( type: string, onReceived: ( data: T ) => void ): DeviceEventSubscription; } // Used by Dimensions below - export interface ScaledSize - { + export interface ScaledSize { width: number; height: number; scale: number; } // @see https://facebook.github.io/react-native/docs/asyncstorage.html#content - export interface AsyncStorageStatic - { - getItem(key: string, callback?: (error?: Error, result?: string) => void): Promise; - setItem(key: string, value: string, callback?: (error?: Error) => void): Promise; - removeItem(key: string, callback?: (error?: Error) => void): Promise; - mergeItem(key: string, value: string, callback?: (error?: Error) => void): Promise; - clear(callback?: (error?: Error) => void): Promise; - getAllKeys(callback?: (error?: Error, keys?: string[]) => void): Promise; - multiGet(keys: string[], callback?: (errors?: Error[], result?: string[][]) => void): Promise; - multiSet(keyValuePairs: string[][], callback?: (errors?: Error[]) => void): Promise; - multiRemove(keys: string[], callback?: (errors?: Error[]) => void): Promise; - multiMerge(keyValuePairs: string[][], callback?: (errors?: Error[]) => void): Promise; + export interface AsyncStorageStatic { + getItem( key: string, callback?: ( error?: Error, result?: string ) => void ): Promise; + setItem( key: string, value: string, callback?: ( error?: Error ) => void ): Promise; + removeItem( key: string, callback?: ( error?: Error ) => void ): Promise; + mergeItem( key: string, value: string, callback?: ( error?: Error ) => void ): Promise; + clear( callback?: ( error?: Error ) => void ): Promise; + getAllKeys( callback?: ( error?: Error, keys?: string[] ) => void ): Promise; + multiGet( keys: string[], callback?: ( errors?: Error[], result?: string[][] ) => void ): Promise; + multiSet( keyValuePairs: string[][], callback?: ( errors?: Error[] ) => void ): Promise; + multiRemove( keys: string[], callback?: ( errors?: Error[] ) => void ): Promise; + multiMerge( keyValuePairs: string[][], callback?: ( errors?: Error[] ) => void ): Promise; } - export interface InteractionManagerStatic - { + export interface InteractionManagerStatic { runAfterInteractions( fn: () => void ): void; } - export interface ScrollViewProperties - { + export interface ScrollViewProperties { } - export interface NativeScrollRectangle - { + export interface NativeScrollRectangle { left: number; top: number; bottom: number; right: number; } - export interface NativeScrollPoint - { + export interface NativeScrollPoint { x: number; y: number; } - export interface NativeScrollSize - { + export interface NativeScrollSize { height: number; width: number; } - export interface NativeScrollEvent - { + export interface NativeScrollEvent { contentInset: NativeScrollRectangle; contentOffset: NativeScrollPoint; contentSize: NativeScrollSize; @@ -980,11 +1058,10 @@ declare namespace ReactNative { zoomScale: number; } - export interface AppStateIOSStatic - { + export interface AppStateIOSStatic { currentState: string; - addEventListener( type: string, listener: (state: string) => void ): void; - removeEventListener( type: string, listener: (state: string) => void ): void; + addEventListener( type: string, listener: ( state: string ) => void ): void; + removeEventListener( type: string, listener: ( state: string ) => void ): void; } // exported singletons: @@ -1025,11 +1102,11 @@ declare namespace ReactNative { //react re-exported export type ReactType = React.ReactType; - export interface ReactElement

extends React.ReactElement

{} + export interface ReactElement

extends React.ReactElement

{} - export interface ClassicElement

extends React.ClassicElement

{} + export interface ClassicElement

extends React.ClassicElement

{} - export interface DOMElement

extends React.DOMElement

{} + export interface DOMElement

extends React.DOMElement

{} export type HTMLElement =React.HTMLElement; export type SVGElement = React.SVGElement; @@ -1038,11 +1115,11 @@ declare namespace ReactNative { // Factories // ---------------------------------------------------------------------- - export interface Factory

extends React.Factory

{} + export interface Factory

extends React.Factory

{} - export interface ClassicFactory

extends React.ClassicFactory

{} + export interface ClassicFactory

extends React.ClassicFactory

{} - export interface DOMFactory

extends React.DOMFactory

{} + export interface DOMFactory

extends React.DOMFactory

{} export type HTMLFactory = React.HTMLFactory; export type SVGFactory = React.SVGFactory; @@ -1064,39 +1141,33 @@ declare namespace ReactNative { // Top Level API // ---------------------------------------------------------------------- - export function createClass(spec: React.ComponentSpec): React.ClassicComponentClass

; + export function createClass( spec: React.ComponentSpec ): React.ClassicComponentClass

; - export function createFactory

(type: string): React.DOMFactory

; - export function createFactory

(type: React.ClassicComponentClass

| string): React.ClassicFactory

; - export function createFactory

(type: React.ComponentClass

): React.Factory

; + export function createFactory

( type: string ): React.DOMFactory

; + export function createFactory

( type: React.ClassicComponentClass

| string ): React.ClassicFactory

; + export function createFactory

( type: React.ComponentClass

): React.Factory

; - export function createElement

( - type: string, - props?: P, - ...children: React.ReactNode[]): React.DOMElement

; - export function createElement

( - type: React.ClassicComponentClass

| string, - props?: P, - ...children: React.ReactNode[]): React.ClassicElement

; - export function createElement

( - type: React.ComponentClass

, - props?: P, - ...children: React.ReactNode[]): React.ReactElement

; + export function createElement

( type: string, + props?: P, + ...children: React.ReactNode[] ): React.DOMElement

; + export function createElement

( type: React.ClassicComponentClass

| string, + props?: P, + ...children: React.ReactNode[] ): React.ClassicElement

; + export function createElement

( type: React.ComponentClass

, + props?: P, + ...children: React.ReactNode[] ): React.ReactElement

; - export function cloneElement

( - element: React.DOMElement

, - props?: P, - ...children: React.ReactNode[]): React.DOMElement

; - export function cloneElement

( - element: React.ClassicElement

, - props?: P, - ...children: React.ReactNode[]): React.ClassicElement

; - export function cloneElement

( - element: React.ReactElement

, - props?: P, - ...children: React.ReactNode[]): React.ReactElement

; + export function cloneElement

( element: React.DOMElement

, + props?: P, + ...children: React.ReactNode[] ): React.DOMElement

; + export function cloneElement

( element: React.ClassicElement

, + props?: P, + ...children: React.ReactNode[] ): React.ClassicElement

; + export function cloneElement

( element: React.ReactElement

, + props?: P, + ...children: React.ReactNode[] ): React.ReactElement

; - export function isValidElement(object: {}): boolean; + export function isValidElement( object: {} ): boolean; export var DOM: React.ReactDOM; export var PropTypes: React.ReactPropTypes; @@ -1107,7 +1178,7 @@ declare namespace ReactNative { // ---------------------------------------------------------------------- // Base component for plain JS classes - export class Component extends React.Component{} + export class Component extends React.Component {} export interface ClassicComponent extends React.ClassicComponent {} @@ -1118,40 +1189,40 @@ declare namespace ReactNative { export type HTMLComponent = React.HTMLComponent; export type SVGComponent = React.SVGComponent - export interface ChildContextProvider extends React.ChildContextProvider{} + export interface ChildContextProvider extends React.ChildContextProvider {} // // Class Interfaces // ---------------------------------------------------------------------- - export interface ComponentClass

extends React.ComponentClass

{} + export interface ComponentClass

extends React.ComponentClass

{} - export interface ClassicComponentClass

extends React.ClassicComponentClass

{} + export interface ClassicComponentClass

extends React.ClassicComponentClass

{} // // Component Specs and Lifecycle // ---------------------------------------------------------------------- - export interface ComponentLifecycle extends React.ComponentLifecycle{} + export interface ComponentLifecycle extends React.ComponentLifecycle {} - export interface Mixin extends React.Mixin{} + export interface Mixin extends React.Mixin {} - export interface ComponentSpec extends React.ComponentSpec{} + export interface ComponentSpec extends React.ComponentSpec {} // // Event System // ---------------------------------------------------------------------- - export interface SyntheticEvent extends React.SyntheticEvent{} + export interface SyntheticEvent extends React.SyntheticEvent {} - export interface DragEvent extends React.DragEvent{} + export interface DragEvent extends React.DragEvent {} - export interface ClipboardEvent extends React.ClipboardEvent{} + export interface ClipboardEvent extends React.ClipboardEvent {} - export interface KeyboardEvent extends React.KeyboardEvent{} + export interface KeyboardEvent extends React.KeyboardEvent {} - export interface FocusEvent extends React.FocusEvent{} + export interface FocusEvent extends React.FocusEvent {} export interface FormEvent extends React.FormEvent {} @@ -1167,7 +1238,7 @@ declare namespace ReactNative { // Event Handler Types // ---------------------------------------------------------------------- - export interface EventHandler extends React.EventHandler{} + export interface EventHandler extends React.EventHandler {} export interface DragEventHandler extends React.DragEventHandler {} export interface ClipboardEventHandler extends React.ClipboardEventHandler {} @@ -1177,67 +1248,67 @@ declare namespace ReactNative { export interface MouseEventHandler extends React.MouseEventHandler {} export interface TouchEventHandler extends React.TouchEventHandler {} export interface UIEventHandler extends React.UIEventHandler {} - export interface WheelEventHandler extends React.WheelEventHandler{} + export interface WheelEventHandler extends React.WheelEventHandler {} // // Props / DOM Attributes // ---------------------------------------------------------------------- - export interface Props extends React.Props{} + export interface Props extends React.Props {} - export interface DOMAttributesBase extends React.DOMAttributesBase{} + export interface DOMAttributesBase extends React.DOMAttributesBase {} - export interface DOMAttributes extends React.DOMAttributes{} + export interface DOMAttributes extends React.DOMAttributes {} // This interface is not complete. Only properties accepting // unitless numbers are listed here (see CSSProperty.js in React) - export interface CSSProperties extends React.CSSProperties{} + export interface CSSProperties extends React.CSSProperties {} - export interface HTMLAttributesBase extends React.HTMLAttributesBase{} + export interface HTMLAttributesBase extends React.HTMLAttributesBase {} - export interface HTMLAttributes extends React.HTMLAttributes{} + export interface HTMLAttributes extends React.HTMLAttributes {} - export interface SVGElementAttributes extends React.SVGElementAttributes{} + export interface SVGElementAttributes extends React.SVGElementAttributes {} - export interface SVGAttributes extends React.SVGAttributes{} + export interface SVGAttributes extends React.SVGAttributes {} // // React.DOM // ---------------------------------------------------------------------- - export interface ReactDOM extends React.ReactDOM{} + export interface ReactDOM extends React.ReactDOM {} // // React.PropTypes // ---------------------------------------------------------------------- - export interface Validator extends React.Validator{} + export interface Validator extends React.Validator {} export interface Requireable extends React.Requireable {} - export interface ValidationMap extends React.ValidationMap{} + export interface ValidationMap extends React.ValidationMap {} - export interface ReactPropTypes extends React.ReactPropTypes{} + export interface ReactPropTypes extends React.ReactPropTypes {} // // React.Children // ---------------------------------------------------------------------- - export interface ReactChildren extends React.ReactChildren{} + export interface ReactChildren extends React.ReactChildren {} // // Browser Interfaces // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts // ---------------------------------------------------------------------- - export interface AbstractView extends React.AbstractView{} + export interface AbstractView extends React.AbstractView {} - export interface Touch extends React.Touch{} + export interface Touch extends React.Touch {} - export interface TouchList extends React.TouchList{} + export interface TouchList extends React.TouchList {} - export function __spread(target:any, ...sources:any[]): any; + export function __spread( target: any, ...sources: any[] ): any; } declare module "react-native" { @@ -1246,14 +1317,11 @@ declare module "react-native" { } - -declare module "Dimensions" -{ +declare module "Dimensions" { import React from 'react-native'; - interface Dimensions - { - get(what:string): React.ScaledSize; + interface Dimensions { + get( what: string ): React.ScaledSize; } var ExportDimensions: Dimensions; From f1449a07df55d3aec69410c8fb4311c402716068 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 7 Nov 2015 12:33:57 +0500 Subject: [PATCH 46/86] lodash: signatures of the method _.defaults have been changed --- lodash/lodash-tests.ts | 129 ++++++++++++++++++++++++++++-- lodash/lodash.d.ts | 173 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 283 insertions(+), 19 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..588eb0300 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -4331,13 +4331,130 @@ result = <{}>_(testCreateProto).create(testCreateProps).value(); result = _(testCreateProto).create().value(); result = _(testCreateProto).create(testCreateProps).value(); -interface Food { - name: string; - type: string; +// _.defaults +module TestDefaults { + interface Obj {a: string}; + interface S1 {a: number}; + interface S2 {b: number}; + interface S3 {c: number}; + interface S4 {d: number}; + interface S5 {e: number}; + + let obj: Obj; + let s1: S1; + let s2: S2; + let s3: S3; + let s4: S4; + let s5: S5; + + { + let result: Obj; + + result = _.defaults(obj); + } + + { + let result: {a: string}; + + result = _.defaults(obj, s1); + } + + { + let result: {a: string, b: number}; + + result = _.defaults(obj, s1, s2); + } + + { + let result: {a: string, b: number, c: number}; + + result = _.defaults(obj, s1, s2, s3); + } + + { + let result: {a: string, b: number, c: number, d: number}; + + result = _.defaults(obj, s1, s2, s3, s4); + } + + { + let result: {a: string, b: number, c: number, d: number, e: number}; + + result = _.defaults(obj, s1, s2, s3, s4, s5); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _(obj).defaults(); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: string}>; + + result = _(obj).defaults(s1); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: string, b: number}>; + + result = _(obj).defaults(s1, s2); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: string, b: number, c: number}>; + + result = _(obj).defaults(s1, s2, s3); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: string, b: number, c: number, d: number}>; + + result = _(obj).defaults(s1, s2, s3, s4); + } + + { + let result: _.LoDashImplicitObjectWrapper<{a: string, b: number, c: number, d: number, e: number}>; + + result = _(obj).defaults<{a: string, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(obj).chain().defaults(); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: string}>; + + result = _(obj).chain().defaults(s1); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: string, b: number}>; + + result = _(obj).chain().defaults(s1, s2); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: string, b: number, c: number}>; + + result = _(obj).chain().defaults(s1, s2, s3); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: string, b: number, c: number, d: number}>; + + result = _(obj).chain().defaults(s1, s2, s3, s4); + } + + { + let result: _.LoDashExplicitObjectWrapper<{a: string, b: number, c: number, d: number, e: number}>; + + result = _(obj).chain().defaults<{a: string, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); + } } -var foodDefaults = { 'name': 'apple' }; -result = _.defaults(foodDefaults, { 'name': 'banana', 'type': 'fruit' }); -result = <_.LoDashImplicitObjectWrapper>_(foodDefaults).defaults({ 'name': 'banana', 'type': 'fruit' }); //_.defaultsDeep interface DefaultsDeepResult { diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..fc26d183a 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -9135,23 +9135,170 @@ declare module _ { //_.defaults interface LoDashStatic { /** - * Assigns own enumerable properties of source object(s) to the destination object for all - * destination properties that resolve to undefined. Once a property is set, additional defaults - * of the same property will be ignored. - * @param object The destination object. - * @param sources The source objects. - * @return The destination object. - **/ - defaults( - object: T, - ...sources: any[]): TResult; + * Assigns own enumerable properties of source object(s) to the destination object for all destination + * properties that resolve to undefined. Once a property is set, additional values of the same property are + * ignored. + * + * Note: This method mutates object. + * + * @param object The destination object. + * @param sources The source objects. + * @return The destination object. + */ + defaults( + object: Obj, + ...sources: {}[] + ): TResult; + + /** + * @see _.defaults + */ + defaults( + object: Obj, + source1: S1, + ...sources: {}[] + ): TResult; + + /** + * @see _.defaults + */ + defaults( + object: Obj, + source1: S1, + source2: S2, + ...sources: {}[] + ): TResult; + + /** + * @see _.defaults + */ + defaults( + object: Obj, + source1: S1, + source2: S2, + source3: S3, + ...sources: {}[] + ): TResult; + + /** + * @see _.defaults + */ + defaults( + object: Obj, + source1: S1, + source2: S2, + source3: S3, + source4: S4, + ...sources: {}[] + ): TResult; + + /** + * @see _.defaults + */ + defaults( + object: {}, + ...sources: {}[] + ): TResult; } interface LoDashImplicitObjectWrapper { /** - * @see _.defaults - **/ - defaults(...sources: any[]): LoDashImplicitObjectWrapper + * @see _.defaults + */ + defaults( + source1: S1, + ...sources: {}[] + ): LoDashImplicitObjectWrapper; + + /** + * @see _.defaults + */ + defaults( + source1: S1, + source2: S2, + ...sources: {}[] + ): LoDashImplicitObjectWrapper; + + /** + * @see _.defaults + */ + defaults( + source1: S1, + source2: S2, + source3: S3, + ...sources: {}[] + ): LoDashImplicitObjectWrapper; + + /** + * @see _.defaults + */ + defaults( + source1: S1, + source2: S2, + source3: S3, + source4: S4, + ...sources: {}[] + ): LoDashImplicitObjectWrapper; + + /** + * @see _.defaults + */ + defaults(): LoDashImplicitObjectWrapper; + + /** + * @see _.defaults + */ + defaults(...sources: {}[]): LoDashImplicitObjectWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.defaults + */ + defaults( + source1: S1, + ...sources: {}[] + ): LoDashExplicitObjectWrapper; + + /** + * @see _.defaults + */ + defaults( + source1: S1, + source2: S2, + ...sources: {}[] + ): LoDashExplicitObjectWrapper; + + /** + * @see _.defaults + */ + defaults( + source1: S1, + source2: S2, + source3: S3, + ...sources: {}[] + ): LoDashExplicitObjectWrapper; + + /** + * @see _.defaults + */ + defaults( + source1: S1, + source2: S2, + source3: S3, + source4: S4, + ...sources: {}[] + ): LoDashExplicitObjectWrapper; + + /** + * @see _.defaults + */ + defaults(): LoDashExplicitObjectWrapper; + + /** + * @see _.defaults + */ + defaults(...sources: {}[]): LoDashExplicitObjectWrapper; } //_.defaultsDeep From 3f679d1bd95d9f03bc34dc8d7a3e2520ad8c0c9d Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 7 Nov 2015 12:42:12 +0500 Subject: [PATCH 47/86] lodash: signatures of the method _.takeRight have been changed --- lodash/lodash-tests.ts | 45 +++++++++++++++++++++++++++++++----------- lodash/lodash.d.ts | 16 ++++++++++++++- 2 files changed, 48 insertions(+), 13 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..fa9951979 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1151,18 +1151,39 @@ module TestTake { } // _.takeRight -{ - let testTakeRightArray: TResult[]; - let testTakeRightList: _.List; - let result: TResult[]; - result = _.takeRight(testTakeRightArray); - result = _.takeRight(testTakeRightArray, 42); - result = _.takeRight(testTakeRightList); - result = _.takeRight(testTakeRightList, 42); - result = _(testTakeRightArray).takeRight().value(); - result = _(testTakeRightArray).takeRight(42).value(); - result = _(testTakeRightList).takeRight().value(); - result = _(testTakeRightList).takeRight(42).value(); +module TestTakeRight { + let array: TResult[]; + let list: _.List; + + { + let result: TResult[]; + + result = _.takeRight(array); + result = _.takeRight(array, 42); + + result = _.takeRight(list); + result = _.takeRight(list, 42); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _(array).takeRight(); + result = _(array).takeRight(42); + + result = _(list).takeRight(); + result = _(list).takeRight(42); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + result = _(array).chain().takeRight(); + result = _(array).chain().takeRight(42); + + result = _(list).chain().takeRight(); + result = _(list).chain().takeRight(42); + } } // _.takeRightWhile diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..4980ff4de 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -1994,7 +1994,7 @@ declare module _ { * @return Returns the slice of array. */ takeRight( - array: T[]|List, + array: List, n?: number ): T[]; } @@ -2013,6 +2013,20 @@ declare module _ { takeRight(n?: number): LoDashImplicitArrayWrapper; } + interface LoDashExplicitArrayWrapper { + /** + * @see _.takeRight + */ + takeRight(n?: number): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.takeRight + */ + takeRight(n?: number): LoDashExplicitArrayWrapper; + } + //_.takeRightWhile interface LoDashStatic { /** From 51f1a0a6271989b76a09bc5301e8397526ee0a06 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 7 Nov 2015 12:48:44 +0500 Subject: [PATCH 48/86] lodash: signatures of the method _.takeWhile have been changed --- lodash/lodash-tests.ts | 75 ++++++++++++++++++++++++++++-------------- lodash/lodash.d.ts | 50 ++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 25 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..7951c6b6d 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1231,35 +1231,60 @@ module TestTakeWhile { let array: TResult[]; let list: _.List; let predicateFn: (value: TResult, index: number, collection: _.List) => boolean; - let result: TResult[]; - result = _.takeWhile(array); - result = _.takeWhile(array, predicateFn); - result = _.takeWhile(array, predicateFn, any); - result = _.takeWhile(array, ''); - result = _.takeWhile(array, '', any); - result = _.takeWhile<{a: number;}, TResult>(array, {a: 42}); + { + let result: TResult[]; - result = _.takeWhile(list); - result = _.takeWhile(list, predicateFn); - result = _.takeWhile(list, predicateFn, any); - result = _.takeWhile(list, ''); - result = _.takeWhile(list, '', any); - result = _.takeWhile<{a: number;}, TResult>(list, {a: 42}); + result = _.takeWhile(array); + result = _.takeWhile(array, predicateFn); + result = _.takeWhile(array, predicateFn, any); + result = _.takeWhile(array, ''); + result = _.takeWhile(array, '', any); + result = _.takeWhile<{a: number;}, TResult>(array, {a: 42}); - result = _(array).takeWhile().value(); - result = _(array).takeWhile(predicateFn).value(); - result = _(array).takeWhile(predicateFn, any).value(); - result = _(array).takeWhile('').value(); - result = _(array).takeWhile('', any).value(); - result = _(array).takeWhile<{a: number;}>({a: 42}).value(); + result = _.takeWhile(list); + result = _.takeWhile(list, predicateFn); + result = _.takeWhile(list, predicateFn, any); + result = _.takeWhile(list, ''); + result = _.takeWhile(list, '', any); + result = _.takeWhile<{a: number;}, TResult>(list, {a: 42}); + } - result = _(list).takeWhile().value(); - result = _(list).takeWhile(predicateFn).value(); - result = _(list).takeWhile(predicateFn, any).value(); - result = _(list).takeWhile('').value(); - result = _(list).takeWhile('', any).value(); - result = _(list).takeWhile<{a: number;}, TResult>({a: 42}).value(); + { + let result: _.LoDashImplicitArrayWrapper; + + result = _(array).takeWhile(); + result = _(array).takeWhile(predicateFn); + result = _(array).takeWhile(predicateFn, any); + result = _(array).takeWhile(''); + result = _(array).takeWhile('', any); + result = _(array).takeWhile<{a: number;}>({a: 42}); + + result = _(list).takeWhile(); + result = _(list).takeWhile(predicateFn); + result = _(list).takeWhile(predicateFn, any); + result = _(list).takeWhile(''); + result = _(list).takeWhile('', any); + result = _(list).takeWhile<{a: number;}, TResult>({a: 42}); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + result = _(array).chain().takeWhile(); + result = _(array).chain().takeWhile(predicateFn); + result = _(array).chain().takeWhile(predicateFn, any); + result = _(array).chain().takeWhile(''); + result = _(array).chain().takeWhile('', any); + result = _(array).chain().takeWhile<{a: number;}>({a: 42}); + + result = _(list).chain().takeWhile(); + result = _(list).chain().takeWhile(predicateFn); + result = _(list).chain().takeWhile(predicateFn, any); + result = _(list).chain().takeWhile(''); + result = _(list).chain().takeWhile('', any); + result = _(list).chain().takeWhile<{a: number;}, TResult>({a: 42}); + } } // _.union diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..3f72b7e1f 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -2251,6 +2251,56 @@ declare module _ { ): LoDashImplicitArrayWrapper; } + interface LoDashExplicitArrayWrapper { + /** + * @see _.takeWhile + */ + takeWhile( + predicate?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.takeWhile + */ + takeWhile( + predicate?: string, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.takeWhile + */ + takeWhile( + predicate?: TWhere + ): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.takeWhile + */ + takeWhile( + predicate?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.takeWhile + */ + takeWhile( + predicate?: string, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.takeWhile + */ + takeWhile( + predicate?: TWhere + ): LoDashExplicitArrayWrapper; + } + //_.union interface LoDashStatic { /** From d3860cb406c8dc685a68f4e1a62f28673a9a7618 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 7 Nov 2015 13:00:37 +0500 Subject: [PATCH 49/86] lodash: signatures of the method _.last have been changed --- lodash/lodash-tests.ts | 26 +++++++++++++++++++++----- lodash/lodash.d.ts | 14 ++++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..1b03228e5 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -744,12 +744,28 @@ module TestIntersection { module TestLast { let array: TResult[]; let list: _.List; - let result: TResult; - result = _.last(array); - result = _.last(list); - result = _(array).last(); - result = _(list).last(); + { + let result: TResult; + + result = _.last(array); + result = _.last(list); + + result = _(array).last(); + result = _(list).last(); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + result = _(array).chain().last(); + } + + { + let result: _.LoDashExplicitObjectWrapper<_.List>; + + result = _(list).chain().last<_.List>(); + } } // _.lastIndexOf diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..eda63233e 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -1326,6 +1326,20 @@ declare module _ { last(): T; } + interface LoDashExplicitArrayWrapper { + /** + * @see _.last + */ + last(): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.last + */ + last(): LoDashExplicitObjectWrapper; + } + //_.lastIndexOf interface LoDashStatic { /** From f3aecb497b5408aac58ad58484b73b558f6a1656 Mon Sep 17 00:00:00 2001 From: Andrej T Date: Fri, 6 Nov 2015 17:35:41 +0100 Subject: [PATCH 50/86] added definitions for anydb-sql and anydb-sql-migrations --- .../anydb-sql-migrations-tests.ts | 17 ++ .../anydb-sql-migrations.d.ts | 34 +++ anydb-sql/anydb-sql-tests.ts | 70 +++++++ anydb-sql/anydb-sql.d.ts | 194 ++++++++++++++++++ 4 files changed, 315 insertions(+) create mode 100644 anydb-sql-migrations/anydb-sql-migrations-tests.ts create mode 100644 anydb-sql-migrations/anydb-sql-migrations.d.ts create mode 100644 anydb-sql/anydb-sql-tests.ts create mode 100644 anydb-sql/anydb-sql.d.ts diff --git a/anydb-sql-migrations/anydb-sql-migrations-tests.ts b/anydb-sql-migrations/anydb-sql-migrations-tests.ts new file mode 100644 index 000000000..f9c3da03a --- /dev/null +++ b/anydb-sql-migrations/anydb-sql-migrations-tests.ts @@ -0,0 +1,17 @@ +/// +/// +import anydbsql = require('anydb-sql'); +import { Table, Column } from 'anydb-sql' +import migrator = require('anydb-sql-migrations'); + +function do_not_run() { + + var db = anydbsql({ + url: 'postgres://user:pass@host:port/database', + connections: { min: 2, max: 20 } + }); + + migrator + .create(db, '/path/to/migrations/dir') + .run(); +} diff --git a/anydb-sql-migrations/anydb-sql-migrations.d.ts b/anydb-sql-migrations/anydb-sql-migrations.d.ts new file mode 100644 index 000000000..9ab421c3a --- /dev/null +++ b/anydb-sql-migrations/anydb-sql-migrations.d.ts @@ -0,0 +1,34 @@ +// Type definitions for anydb-sql-migrations +// Project: https://github.com/spion/anydb-sql-migrations +// Definitions by: Gorgi Kosev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module "anydb-sql-migrations" { + import Promise = require('bluebird'); + import { Column, Table, Transaction, AnydbSql } from 'anydb-sql'; + export interface Migration { + version: string; + } + export interface MigrationsTable extends Table { + version: Column; + } + export interface MigFn { + (tx: Transaction): Promise; + } + export interface MigrationTask { + up: MigFn; + down: MigFn; + name: string; + } + export function create(db: AnydbSql, tasks: any): { + run: () => Promise; + migrateTo: (target?: string) => Promise; + check: (f: (m: { + type: string; + items: MigrationTask[]; + }) => any) => Promise; + }; +} \ No newline at end of file diff --git a/anydb-sql/anydb-sql-tests.ts b/anydb-sql/anydb-sql-tests.ts new file mode 100644 index 000000000..9e0264f7b --- /dev/null +++ b/anydb-sql/anydb-sql-tests.ts @@ -0,0 +1,70 @@ +/// +import anydbsql = require('anydb-sql'); +import { Table, Column } from 'anydb-sql' + +function do_not_run() { + + var db = anydbsql({ + url: 'postgres://user:pass@host:port/database', + connections: { min: 2, max: 20 } + }); + + // Table Post + + interface Post { + content: string; + userId: string; + date: string; + } + + interface PostTable extends Table { + content: Column; + userId: Column; + date: Column; + } + + var post = db.define({ + name: 'posts', + columns: { + content: {}, + userId: {}, + date: {} + } + }); + + // Table User + + interface User { + id: string; + email: string; + password: string; + name: string; + } + + interface UserTable extends Table { + id: Column; + email: Column; + password: Column; + name: Column; + } + + var user = db.define({ + name: 'users', + columns: { + id: { primaryKey: true }, + email: {}, + password: {}, + name: {}, + date: {} + }, + has: { + posts: { from: 'posts', many: true }, + group: { from: 'groups'} + } + }); + + user.select(user.name, post.content) + .from(user.join(post).on(user.id.equals(post.userId))) + .where(post.date.gt('123')) + .all() +} \ No newline at end of file diff --git a/anydb-sql/anydb-sql.d.ts b/anydb-sql/anydb-sql.d.ts new file mode 100644 index 000000000..d8bce402b --- /dev/null +++ b/anydb-sql/anydb-sql.d.ts @@ -0,0 +1,194 @@ +// Type definitions for anydb-sql +// Project: https://github.com/doxout/anydb-sql +// Definitions by: Gorgi Kosev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "anydb-sql" { + import Promise = require('bluebird'); + + interface AnyDBPool extends anydbSQL.DatabaseConnection { + query:(text:string, values:any[], callback:(err:Error, result:any)=>void)=>void + begin:()=>anydbSQL.Transaction + close:(err:Error)=>void + } + + interface Dictionary { [key:string]:T; } + + module anydbSQL { + export interface OrderByValueNode {} + export interface ColumnDefinition { + primaryKey?:boolean; + dataType?:string; + references?: {table:string; column: string} + notNull?:boolean + } + + export interface TableDefinition { + name:string + columns:Dictionary + has?:Dictionary<{from:string; many?:boolean}> + } + + + export interface QueryLike { + query:string; + values: any[] + text:string + } + export interface DatabaseConnection { + queryAsync(query:string, ...params:any[]):Promise<{rowCount:number;rows:T[]}> + queryAsync(query:QueryLike):Promise<{rowCount:number;rows:T[]}> + } + + export interface Transaction extends DatabaseConnection { + rollback():void + commitAsync():Promise + } + + export interface SubQuery { + select(node:Column):SubQuery + where(...nodes:any[]):SubQuery + from(table:TableNode):SubQuery + group(...nodes:any[]):SubQuery + order(criteria:OrderByValueNode):SubQuery + notExists(subQuery:SubQuery):SubQuery + } + + interface Executable { + get():Promise + getWithin(tx:DatabaseConnection):Promise + exec():Promise + all():Promise + execWithin(tx:DatabaseConnection):Promise + allWithin(tx:DatabaseConnection):Promise + toQuery():QueryLike; + } + + interface Queryable { + where(...nodes:any[]):Query + delete():ModifyingQuery + select(...nodes:any[]):Query + selectDeep(table: Table): Query + selectDeep(...nodesOrTables:any[]):Query + } + + export interface Query extends Executable, Queryable { + from(table:TableNode):Query + update(o:Dictionary):ModifyingQuery + update(o:{}):ModifyingQuery + group(...nodes:any[]):Query + order(...criteria:OrderByValueNode[]):Query + limit(l:number):Query + offset(o:number):Query + } + + export interface ModifyingQuery extends Executable { + returning(...nodes:any[]):Query + where(...nodes:any[]):ModifyingQuery + } + + export interface TableNode { + join(table:TableNode):JoinTableNode + leftJoin(table:TableNode):JoinTableNode + } + + export interface JoinTableNode extends TableNode { + on(filter:BinaryNode):TableNode + on(filter:string):TableNode + } + + interface CreateQuery extends Executable { + ifNotExists():Executable + } + interface DropQuery extends Executable { + ifExists():Executable + } + export interface Table extends TableNode, Queryable { + create():CreateQuery + drop():DropQuery + as(name:string):Table + update(o:any):ModifyingQuery + insert(row:T):ModifyingQuery + insert(rows:T[]):ModifyingQuery + select():Query + select(...nodes:any[]):Query + from(table:TableNode):Query + star():Column + subQuery():SubQuery + eventEmitter:{emit:(type:string, ...args:any[])=>void + on:(eventName:string, handler:Function)=>void} + columns:Column[] + sql: SQL; + alter():AlterQuery + } + export interface AlterQuery extends Executable { + addColumn(column:Column): AlterQuery; + addColumn(name: string, options:string): AlterQuery; + dropColumn(column: Column): AlterQuery; + renameColumn(column: Column, newColumn: Column):AlterQuery; + renameColumn(column: Column, newName: string):AlterQuery; + renameColumn(name: string, newName: string):AlterQuery; + rename(newName: string): AlterQuery + } + + export interface SQL { + functions: { + LOWER(c:Column):Column + } + } + + export interface BinaryNode { + and(node:BinaryNode):BinaryNode + or(node:BinaryNode):BinaryNode + } + + export interface Column { + in(arr:T[]):BinaryNode + in(subQuery:SubQuery):BinaryNode + notIn(arr:T[]):BinaryNode + equals(node:any):BinaryNode + notEquals(node:any):BinaryNode + gte(node:any):BinaryNode + lte(node:any):BinaryNode + gt(node:any):BinaryNode + lt(node:any):BinaryNode + like(str:string):BinaryNode + multiply:{ + (node:Column):Column + (n:number):Column + } + isNull():BinaryNode + isNotNull():BinaryNode + sum():Column + count():Column + count(name:string):Column + distinct():Column + as(name:string):Column + ascending:OrderByValueNode + descending:OrderByValueNode + asc:OrderByValueNode + desc:OrderByValueNode + } + + export interface AnydbSql extends DatabaseConnection { + define(map:TableDefinition):Table; + transaction(fn:(tx:Transaction)=>Promise):Promise + allOf(...tables:Table[]):any + models:Dictionary> + functions:{LOWER:(name:Column)=>Column + RTRIM:(name:Column)=>Column} + makeFunction(name:string):Function + begin():Transaction + open():void; + close():void; + getPool():AnyDBPool; + dialect():string; + } + } + + function anydbSQL(config:Object):anydbSQL.AnydbSql; + + export = anydbSQL; +} \ No newline at end of file From 7a4b73270589c003e3e79ab2f0bd8bb022054653 Mon Sep 17 00:00:00 2001 From: kwiateusz Date: Sat, 7 Nov 2015 20:34:16 +0100 Subject: [PATCH 51/86] Update toastr.d.ts Add target in options --- toastr/toastr.d.ts | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/toastr/toastr.d.ts b/toastr/toastr.d.ts index 321177ec2..39be5a21b 100644 --- a/toastr/toastr.d.ts +++ b/toastr/toastr.d.ts @@ -113,17 +113,18 @@ interface ToastrOptions { * Set newest toast to appear on top **/ newestOnTop?: boolean; - - /** - * Rather than having identical toasts stack, set the preventDuplicates property to true. Duplicates are matched to the previous toast based on their message content. - */ - preventDuplicates?: boolean; - - /** - * Visually indicates how long before a toast expires. - */ - progressBar?: boolean; - + /** + * The element to put the toastr container + **/ + target?: string; + /** + * Rather than having identical toasts stack, set the preventDuplicates property to true. Duplicates are matched to the previous toast based on their message content. + */ + preventDuplicates?: boolean; + /** + * Visually indicates how long before a toast expires. + */ + progressBar?: boolean; /** * Function to execute on toast click */ From a36e6ad2f472741b1c22c2af955bf13b7c62e146 Mon Sep 17 00:00:00 2001 From: kwiateusz Date: Sat, 7 Nov 2015 22:28:15 +0100 Subject: [PATCH 52/86] Update toastr.d.ts --- toastr/toastr.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/toastr/toastr.d.ts b/toastr/toastr.d.ts index 39be5a21b..e7cd15f92 100644 --- a/toastr/toastr.d.ts +++ b/toastr/toastr.d.ts @@ -129,6 +129,10 @@ interface ToastrOptions { * Function to execute on toast click */ onclick?: () => void; + /** + * Set if toastr should parse containing html + **/ + allowHtml?: boolean; } interface ToastrDisplayMethod { From 645583cb7842f9aa069a1efd7e7951c41998991a Mon Sep 17 00:00:00 2001 From: David Lloyd Date: Sun, 8 Nov 2015 12:32:48 +1030 Subject: [PATCH 53/86] "Bellow [sic]" should be "Below". Typo. --- angularjs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/README.md b/angularjs/README.md index 510f304f5..e1256e905 100644 --- a/angularjs/README.md +++ b/angularjs/README.md @@ -42,7 +42,7 @@ To avoid cluttering the list of suggestions as you type in your IDE, all interfa **ngMockE2E** does not define a new namespace, but rather modifies some of **ng**'s interfaces. -Bellow is an example of how to use the interfaces: +Below is an example of how to use the interfaces: ```ts function MainController($scope: ng.IScope, $http: ng.IHttpService) { // code assistance will now be available for $scope and $http From a3e2d01e19f060646bfeaf12b46ec4985265bdfc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C3=BA?= Date: Sun, 8 Nov 2015 09:53:56 +0700 Subject: [PATCH 54/86] path-to-regexp: `keys` should be optional --- path-to-regexp/path-to-regexp.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/path-to-regexp/path-to-regexp.d.ts b/path-to-regexp/path-to-regexp.d.ts index 1cea46d85..f8c90c99e 100644 --- a/path-to-regexp/path-to-regexp.d.ts +++ b/path-to-regexp/path-to-regexp.d.ts @@ -5,7 +5,7 @@ declare module "path-to-regexp" { - function pathToRegexp(path: string, keys: string[], options?: pathToRegexp.Options): RegExp; + function pathToRegexp(path: string, keys?: string[], options?: pathToRegexp.Options): RegExp; module pathToRegexp { @@ -14,7 +14,9 @@ declare module "path-to-regexp" { strict?: boolean; end?: boolean; } + } export = pathToRegexp; + } From a2bba58e82e5b14117598536f8fea715434a144f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C3=BA?= Date: Sun, 8 Nov 2015 10:26:58 +0700 Subject: [PATCH 55/86] Create credential.d.ts --- credential/credential.d.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 credential/credential.d.ts diff --git a/credential/credential.d.ts b/credential/credential.d.ts new file mode 100644 index 000000000..d8497ec14 --- /dev/null +++ b/credential/credential.d.ts @@ -0,0 +1,18 @@ +// Type definitions for credential +// Project: https://github.com/ericelliott/credential +// Definitions by: Phú +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'credential' { + + type HashCallback = (err: Error, hash: string) => void; + type VerifyCallback = (err: Error, isValid: boolean) => void; + + module credential { + function hash(password: string, callback: HashCallback): void; + function verify(hash: string, password: string, callback: VerifyCallback): void; + } + + export = credential; + +} From 462461d1fb805462351cd83f0d9f44eccab9c9a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C3=BA?= Date: Sun, 8 Nov 2015 10:38:06 +0700 Subject: [PATCH 56/86] Create credential-tests.ts --- credential/credential-tests.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 credential/credential-tests.ts diff --git a/credential/credential-tests.ts b/credential/credential-tests.ts new file mode 100644 index 000000000..6adec112f --- /dev/null +++ b/credential/credential-tests.ts @@ -0,0 +1,16 @@ +/// + +import * as credential from 'credential'; + +credential.hash('password', function(err: Error, hash: string) { + if (err) console.error(err); + else console.log(hash); +}); + +const hash = '{}'; +const password = 'test'; + +credential.verify(hash, password, function(err: Error, isValid: boolean) { + if (err) console.error(err); + else console.log(isValid ? 'Password match' : 'Incorrect password'); +}); From 8fc20c0d16934a9429d387a7e5cf6639070cef78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C3=BA?= Date: Sun, 8 Nov 2015 10:51:09 +0700 Subject: [PATCH 57/86] Fix reference syntax --- credential/credential-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/credential/credential-tests.ts b/credential/credential-tests.ts index 6adec112f..6013436b0 100644 --- a/credential/credential-tests.ts +++ b/credential/credential-tests.ts @@ -1,4 +1,4 @@ -/// +/// import * as credential from 'credential'; From 0e571efd35ca06e9061757ec9b46b236ded348b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C3=BA?= Date: Sun, 8 Nov 2015 11:21:39 +0700 Subject: [PATCH 58/86] flow.js: fix `testChunks` in definition --- flowjs/flowjs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flowjs/flowjs.d.ts b/flowjs/flowjs.d.ts index e9e90055b..186cd2579 100644 --- a/flowjs/flowjs.d.ts +++ b/flowjs/flowjs.d.ts @@ -44,7 +44,7 @@ declare module flowjs { uploadMethod?: string; allowDuplicateUploads?: boolean; prioritizeFirstAndLastChunk?: boolean; - testchunks?: boolean; + testChunks?: boolean; preprocess?: Function; initFileFn?: Function; generateUniqueIdentifier?: Function; From a3f2c72f889120e46c0bcd382190da2e77303207 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C3=BA?= Date: Sun, 8 Nov 2015 11:22:15 +0700 Subject: [PATCH 59/86] flow.js: fix `testChunks` in test --- flowjs/flowjs-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flowjs/flowjs-tests.ts b/flowjs/flowjs-tests.ts index 8bedad003..b89625b48 100644 --- a/flowjs/flowjs-tests.ts +++ b/flowjs/flowjs-tests.ts @@ -41,7 +41,7 @@ flowOptions.testMethod = ""; flowOptions.uploadMethod = ""; flowOptions.allowDuplicateUploads = true; flowOptions.prioritizeFirstAndLastChunk = true; -flowOptions.testchunks = true; +flowOptions.testChunks = true; flowOptions.preprocess = () => {}; flowOptions.initFileFn = () => {}; flowOptions.generateUniqueIdentifier = () => {}; From e4a4c668061c43ed9bb07b79c4f7fe7d0b56e18c Mon Sep 17 00:00:00 2001 From: bgrieder Date: Sun, 8 Nov 2015 07:46:36 +0100 Subject: [PATCH 60/86] additional definitions for Navigator and NavigatorIOS --- react-native/react-native.d.ts | 131 ++++++++++++++++++++++++++++++--- 1 file changed, 121 insertions(+), 10 deletions(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index 592cecdaf..1432026c2 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -220,7 +220,7 @@ declare namespace ReactNative { } // @see https://facebook.github.io/react-native/docs/text.html#style - export interface TextStyle extends FlexStyle{ + export interface TextStyle extends FlexStyle { color?: string; containerBackgroundColor?: string; fontFamily?: string; @@ -485,12 +485,109 @@ declare namespace ReactNative { } /** - * @see + * @see https://facebook.github.io/react-native/docs/navigator.html#content */ export interface NavigatorProperties { - /// TODO + /** + * Optional function that allows configuration about scene animations and gestures. + * Will be invoked with the route and should return a scene configuration object + * @param route + */ + configureScene?: ( route: Route ) => SceneConfig + /** + * Specify a route to start on. + * A route is an object that the navigator will use to identify each scene to render. + * initialRoute must be a route in the initialRouteStack if both props are provided. + * The initialRoute will default to the last item in the initialRouteStack. + */ + initialRoute?: Route + /** + * Provide a set of routes to initially mount. + * Required if no initialRoute is provided. + * Otherwise, it will default to an array containing only the initialRoute + */ + initialRouteStack?: Route[] + + /** + * Optionally provide a navigation bar that persists across scene transitions + */ + navigationBar?: NavigationBar + + /** + * Optionally provide the navigator object from a parent Navigator + */ + navigator?: Navigator + + /** + * @deprecated Use navigationContext.addListener('willfocus', callback) instead. + */ + onDidFocus?: Function + + /** + * @deprecated Use navigationContext.addListener('willfocus', callback) instead. + */ + onWillFocus?: Function + + /** + * Required function which renders the scene for a given route. + * Will be invoked with the route and the navigator object + * @param route + * @param navigator + */ + renderScene: (route: Route, navigator: Navigator) => React.ComponentClass + + /** + * Styles to apply to the container of each scene + */ + sceneStyle: ViewStyle } + export interface NavigatorIOSProperties { + + /** + * NavigatorIOS uses "route" objects to identify child views, their props, and navigation bar configuration. + * "push" and all the other navigation operations expect routes to be like this + */ + initialRoute?: Route + + /** + * The default wrapper style for components in the navigator. + * A common use case is to set the backgroundColor for every page + */ + itemWrapperStyle?: ViewStyle + + /** + * A Boolean value that indicates whether the navigation bar is hidden + */ + navigationBarHidden?: boolean + + /** + * A Boolean value that indicates whether to hide the 1px hairline shadow + */ + shadowHidden?: boolean + + /** + * The color used for buttons in the navigation bar + */ + tintColor?: string + + /** + * The text color of the navigation bar title + */ + titleTextColor?: string + + /** + * A Boolean value that indicates whether the navigation bar is translucent + */ + translucent?: boolean + + /** + * NOT IN THE DOC BUT IN THE EXAMPLES + */ + style?: ViewStyle + } + + /** * @see */ @@ -559,7 +656,7 @@ declare namespace ReactNative { * Image style * @see https://facebook.github.io/react-native/docs/image.html#style */ - export interface ImageStyle extends FlexStyle{ + export interface ImageStyle extends FlexStyle { color?: string; containerBackgroundColor?: string; fontFamily?: string; @@ -812,8 +909,10 @@ declare namespace ReactNative { } export interface Route { - id: string; + component?: ComponentClass + id?: string; title?: string; + passProps?: Object } /** @@ -827,18 +926,26 @@ declare namespace ReactNative { } + /** + * @see https://facebook.github.io/react-native/docs/navigator.html + */ export interface NavigatorStatic extends React.ComponentClass { SceneConfigs: SceneConfigs; + NavigationBar: NavigationBar; getContext( self: any ): NavigatorStatic; + getCurrentRoutes(): Route[]; + jumpBack(): void; + jumpForward(): void; + jumpTo( route: Route ): void; push( route: Route ): void; pop(): void; - popToTop(): void; - popToRoute( route: Route ): void; + replace( route: Route ): void; + replaceAtIndex( route: Route, index: number ): void; + replacePrevious( route: Route ): void; immediatelyResetRouteStack( routes: Route[] ): void; - getCurrentRoutes(): Route[]; - - NavigationBar: NavigationBar; + popToRoute( route: Route ): void; + popToTop(): void; } export interface StyleSheetStatic extends React.ComponentClass { @@ -1079,6 +1186,7 @@ declare namespace ReactNative { export var Text: React.ComponentClass; export var View: React.ComponentClass; + export var NavigatorIOS: React.ComponentClass; export var AlertIOS: React.ComponentClass; export var SegmentedControlIOS: React.ComponentClass; export var SwitchIOS: React.ComponentClass; @@ -1307,6 +1415,9 @@ declare namespace ReactNative { export interface TouchList extends React.TouchList {} + // + // Additional ( and controversial) + // export function __spread( target: any, ...sources: any[] ): any; } From a5264ccb8a0521f704baf8ea91ad46d3f450ff56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elis=C3=A9e=20Maurer?= Date: Sun, 8 Nov 2015 09:49:01 +0100 Subject: [PATCH 61/86] three: Add SphereBufferGeometry, update webgl_custom_attributes test --- .../tests/webgl/webgl_custom_attributes.ts | 56 ++++++++----------- threejs/three.d.ts | 27 ++++++--- 2 files changed, 41 insertions(+), 42 deletions(-) diff --git a/threejs/tests/webgl/webgl_custom_attributes.ts b/threejs/tests/webgl/webgl_custom_attributes.ts index e7819f568..94c892f62 100644 --- a/threejs/tests/webgl/webgl_custom_attributes.ts +++ b/threejs/tests/webgl/webgl_custom_attributes.ts @@ -8,29 +8,20 @@ var renderer, scene, camera, stats; - var sphere, uniforms, attributes; + var sphere, uniforms; - var noise = []; - - var WIDTH = window.innerWidth, - HEIGHT = window.innerHeight; + var displacement, noise; init(); animate(); function init() { - camera = new THREE.PerspectiveCamera(30, WIDTH / HEIGHT, 1, 10000); + camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 1, 10000); camera.position.z = 300; scene = new THREE.Scene(); - attributes = { - - displacement: { type: 'f', value: [] } - - }; - uniforms = { amplitude: { type: "f", value: 1.0 }, @@ -44,7 +35,6 @@ var shaderMaterial = new THREE.ShaderMaterial({ uniforms: uniforms, - attributes: attributes, vertexShader: document.getElementById('vertexshader').textContent, fragmentShader: document.getElementById('fragmentshader').textContent @@ -52,27 +42,27 @@ var radius = 50, segments = 128, rings = 64; - var geometry = new THREE.SphereGeometry(radius, segments, rings); - geometry.dynamic = true; - sphere = new THREE.Mesh(geometry, shaderMaterial); + var geometry = new THREE.SphereBufferGeometry( radius, segments, rings ); - var vertices = sphere.geometry.vertices; - var values = attributes.displacement.value; + displacement = new Float32Array( geometry.attributes["position"].count ); + noise = new Float32Array( geometry.attributes["position"].count ); - for (var v = 0; v < vertices.length; v++) { + for ( var i = 0; i < displacement.length; i ++ ) { - values[v] = 0; - noise[v] = Math.random() * 5; + noise[ i ] = Math.random() * 5; } + geometry.addAttribute( 'displacement', new THREE.BufferAttribute( displacement, 1 ) ); + + sphere = new THREE.Mesh(geometry, shaderMaterial); scene.add(sphere); renderer = new THREE.WebGLRenderer(); renderer.setClearColor(0x050505); renderer.setPixelRatio(window.devicePixelRatio); - renderer.setSize(WIDTH, HEIGHT); + renderer.setSize(window.innerWidth, window.innerHeight); var container = document.getElementById('container'); container.appendChild(renderer.domElement); @@ -114,19 +104,19 @@ uniforms.amplitude.value = 2.5 * Math.sin(sphere.rotation.y * 0.125); uniforms.color.value.offsetHSL(0.0005, 0, 0); - - for (var i = 0; i < attributes.displacement.value.length; i++) { - - attributes.displacement.value[i] = Math.sin(0.1 * i + time); - - noise[i] += 0.5 * (0.5 - Math.random()); - noise[i] = THREE.Math.clamp(noise[i], -5, 5); - - attributes.displacement.value[i] += noise[i]; - + + for ( var i = 0; i < displacement.length; i ++ ) { + + displacement[ i ] = Math.sin( 0.1 * i + time ); + + noise[ i ] += 0.5 * ( 0.5 - Math.random() ); + noise[ i ] = THREE.Math.clamp( noise[ i ], -5, 5 ); + + displacement[ i ] += noise[ i ]; + } - attributes.displacement.needsUpdate = true; + sphere.geometry.attributes.displacement.needsUpdate = true; renderer.render(scene, camera); diff --git a/threejs/three.d.ts b/threejs/three.d.ts index ec353c507..433f17078 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -5618,6 +5618,23 @@ declare module THREE { addShape(shape: Shape, options?: any): void; } + interface SphereParameters { + radius: number; + widthSegments: number; + heightSegments: number; + phiStart: number; + phiLength: number; + thetaStart: number; + thetaLength: number; + } + + export class SphereBufferGeometry extends BufferGeometry { + constructor(radius: number, widthSegments?: number, heightSegments?: number, phiStart?: number, phiLength?: number, thetaStart?: number, thetaLength?: number); + + parameters: SphereParameters; + + } + /** * A class for generating sphere geometries */ @@ -5635,15 +5652,7 @@ declare module THREE { */ constructor(radius: number, widthSegments?: number, heightSegments?: number, phiStart?: number, phiLength?: number, thetaStart?: number, thetaLength?: number); - parameters: { - radius: number; - widthSegments: number; - heightSegments: number; - phiStart: number; - phiLength: number; - thetaStart: number; - thetaLength: number; - }; + parameters: SphereParameters; } export class TetrahedronGeometry extends PolyhedronGeometry { From 17d5157eb89cc9f1fbfa74bbb134bbd873152398 Mon Sep 17 00:00:00 2001 From: kwiateusz Date: Sun, 8 Nov 2015 12:08:35 +0100 Subject: [PATCH 62/86] Update mCustomScrollbar.d.ts Add more missing options --- mCustomScrollbar/mCustomScrollbar.d.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/mCustomScrollbar/mCustomScrollbar.d.ts b/mCustomScrollbar/mCustomScrollbar.d.ts index 3d354ee45..e20384968 100644 --- a/mCustomScrollbar/mCustomScrollbar.d.ts +++ b/mCustomScrollbar/mCustomScrollbar.d.ts @@ -21,6 +21,17 @@ declare module MCustomScrollbar { */ axis?: string; /** + * Always keep scrollbar(s) visible, even when there’s nothing to scroll. + * 0 – disable (default) + * 1 – keep dragger rail visible + * 2 – keep all scrollbar components (dragger, rail, buttons etc.) visible + */ + alwaysShowScrollbar?: number; + /** + * Enable or disable auto-expanding the scrollbar when cursor is over or dragging the scrollbar. + */ + autoExpandScrollbar?: boolean; + /** * Scrolling inertia (easing), value in milliseconds (0 for no scrolling inertia) */ scrollInertia?: number; @@ -120,6 +131,12 @@ declare module MCustomScrollbar { * User defined callback function, triggered while scrolling */ whileScrolling?: () => void; + /** + * Set the behavior of calling onTotalScroll and onTotalScrollBack offsets. + * By default, callback offsets will trigger repeatedly while content is scrolling within the offsets. + * Set alwaysTriggerOffsets: false when you need to trigger onTotalScroll and onTotalScrollBack callbacks once, each time scroll end or beginning is reached. + */ + alwaysTriggerOffsets?: boolean; } /** * Set a scrollbar ready-to-use theme. See themes demo for all themes - http://manos.malihu.gr/tuts/custom-scrollbar-plugin/scrollbar_themes_demo.html From 068fe69bbcba02f852856b0582b5ee8b8fab585a Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sun, 8 Nov 2015 19:09:21 +0500 Subject: [PATCH 63/86] lodash: signatures of the method _.flowRight have been changed --- lodash/lodash-tests.ts | 96 ++++++++++++++++++++++++++++++++++++------ lodash/lodash.d.ts | 29 ++++++++++++- 2 files changed, 111 insertions(+), 14 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..5f92e5f56 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -3279,10 +3279,34 @@ result = ['6', '8', '10'].map(_.ary<(s: string) => number>(parseInt, 1 result = ['6', '8', '10'].map(_(parseInt).ary<(s: string) => number>(1).value()); // _.backflow -var testBackflowSquareFn = (n: number) => n * n; -var testBackflowAddFn = (n: number, m: number) => n + m; -result = _.backflow<(n: number, m: number) => number>(testBackflowSquareFn, testBackflowAddFn)(1, 2); -result = _(testBackflowSquareFn).backflow<(n: number, m: number) => number>(testBackflowAddFn).value()(1, 2); +module TestBackflow { + let Fn1: (n: number) => number; + let Fn2: (m: number, n: number) => number; + + { + let result: (m: number, n: number) => number; + + result = _.backflow<(m: number, n: number) => number>(Fn1, Fn2); + result = _.backflow<(m: number, n: number) => number>(Fn1, Fn1, Fn2); + result = _.backflow<(m: number, n: number) => number>(Fn1, Fn1, Fn1, Fn2); + } + + { + let result: _.LoDashImplicitObjectWrapper<(m: number, n: number) => number>; + + result = _(Fn1).backflow<(m: number, n: number) => number>(Fn2); + result = _(Fn1).backflow<(m: number, n: number) => number>(Fn1, Fn2); + result = _(Fn1).backflow<(m: number, n: number) => number>(Fn1, Fn1, Fn2); + } + + { + let result: _.LoDashExplicitObjectWrapper<(m: number, n: number) => number>; + + result = _(Fn1).chain().backflow<(m: number, n: number) => number>(Fn2); + result = _(Fn1).chain().backflow<(m: number, n: number) => number>(Fn1, Fn2); + result = _(Fn1).chain().backflow<(m: number, n: number) => number>(Fn1, Fn1, Fn2); + } +} // _.before var testBeforeFn = ((n: number) => () => ++n)(0); @@ -3344,10 +3368,34 @@ funcBindKey = _(objectBindKey).bindKey('greet', 'hi').value(); funcBindKey(); // _.compose -var testComposeSquareFn = (n: number) => n * n; -var testComposeAddFn = (n: number, m: number) => n + m; -result = _.compose<(n: number, m: number) => number>(testComposeSquareFn, testComposeAddFn)(1, 2); -result = _(testComposeSquareFn).compose<(n: number, m: number) => number>(testComposeAddFn).value()(1, 2); +module TestCompose { + let Fn1: (n: number) => number; + let Fn2: (m: number, n: number) => number; + + { + let result: (m: number, n: number) => number; + + result = _.compose<(m: number, n: number) => number>(Fn1, Fn2); + result = _.compose<(m: number, n: number) => number>(Fn1, Fn1, Fn2); + result = _.compose<(m: number, n: number) => number>(Fn1, Fn1, Fn1, Fn2); + } + + { + let result: _.LoDashImplicitObjectWrapper<(m: number, n: number) => number>; + + result = _(Fn1).compose<(m: number, n: number) => number>(Fn2); + result = _(Fn1).compose<(m: number, n: number) => number>(Fn1, Fn2); + result = _(Fn1).compose<(m: number, n: number) => number>(Fn1, Fn1, Fn2); + } + + { + let result: _.LoDashExplicitObjectWrapper<(m: number, n: number) => number>; + + result = _(Fn1).chain().compose<(m: number, n: number) => number>(Fn2); + result = _(Fn1).chain().compose<(m: number, n: number) => number>(Fn1, Fn2); + result = _(Fn1).chain().compose<(m: number, n: number) => number>(Fn1, Fn1, Fn2); + } +} var createCallbackObj: { [index: string]: string; } = { name: 'Joe' }; result = <() => any>_.createCallback('name'); @@ -3445,10 +3493,34 @@ result = _.flow<(n: number, m: number) => number>(testFlowAddFn, testFlo result = _(testFlowAddFn).flow<(n: number, m: number) => number>(testFlowSquareFn).value()(1, 2); // _.flowRight -var testFlowRightSquareFn = (n: number) => n * n; -var testFlowRightAddFn = (n: number, m: number) => n + m; -result = _.flowRight<(n: number, m: number) => number>(testFlowRightSquareFn, testFlowRightAddFn)(1, 2); -result = _(testFlowRightSquareFn).flowRight<(n: number, m: number) => number>(testFlowRightAddFn).value()(1, 2); +module TestFlowRight { + let Fn1: (n: number) => number; + let Fn2: (m: number, n: number) => number; + + { + let result: (m: number, n: number) => number; + + result = _.flowRight<(m: number, n: number) => number>(Fn1, Fn2); + result = _.flowRight<(m: number, n: number) => number>(Fn1, Fn1, Fn2); + result = _.flowRight<(m: number, n: number) => number>(Fn1, Fn1, Fn1, Fn2); + } + + { + let result: _.LoDashImplicitObjectWrapper<(m: number, n: number) => number>; + + result = _(Fn1).flowRight<(m: number, n: number) => number>(Fn2); + result = _(Fn1).flowRight<(m: number, n: number) => number>(Fn1, Fn2); + result = _(Fn1).flowRight<(m: number, n: number) => number>(Fn1, Fn1, Fn2); + } + + { + let result: _.LoDashExplicitObjectWrapper<(m: number, n: number) => number>; + + result = _(Fn1).chain().flowRight<(m: number, n: number) => number>(Fn2); + result = _(Fn1).chain().flowRight<(m: number, n: number) => number>(Fn1, Fn2); + result = _(Fn1).chain().flowRight<(m: number, n: number) => number>(Fn1, Fn1, Fn2); + } +} // _.memoize var testMemoizedFunction: _.MemoizedFunction; diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..2b89be20e 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6827,10 +6827,17 @@ declare module _ { interface LoDashImplicitObjectWrapper { /** * @see _.flowRight - **/ + */ backflow(...funcs: Function[]): LoDashImplicitObjectWrapper; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.flowRight + */ + backflow(...funcs: Function[]): LoDashExplicitObjectWrapper; + } + //_.before interface LoDashStatic { /** @@ -6941,6 +6948,13 @@ declare module _ { compose(...funcs: Function[]): LoDashImplicitObjectWrapper; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.flowRight + */ + compose(...funcs: Function[]): LoDashExplicitObjectWrapper; + } + //_.createCallback interface LoDashStatic { /** @@ -7268,6 +7282,9 @@ declare module _ { /** * This method is like _.flow except that it creates a function that invokes the provided functions from right * to left. + * + * @alias _.backflow, _.compose + * * @param funcs Functions to invoke. * @return Returns the new function. */ @@ -7277,10 +7294,18 @@ declare module _ { interface LoDashImplicitObjectWrapper { /** * @see _.flowRight - **/ + */ flowRight(...funcs: Function[]): LoDashImplicitObjectWrapper; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.flowRight + */ + flowRight(...funcs: Function[]): LoDashExplicitObjectWrapper; + } + + //_.memoize interface MemoizedFunction extends Function { cache: MapCache; From cc3afb220ccec886ff0eb715ad22167de19084d2 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 7 Nov 2015 13:14:10 +0500 Subject: [PATCH 64/86] lodash: signatures of the method _.after have been changed --- lodash/lodash-tests.ts | 34 +++++++++++++++++++++++++--------- lodash/lodash.d.ts | 26 +++++++++++++++++--------- 2 files changed, 42 insertions(+), 18 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..da04e9a9c 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -3262,17 +3262,33 @@ module TestNow { /************* * Functions * *************/ -var saves = ['profile', 'settings']; -var asyncSave = (obj: any) => obj.done(); -var done: Function; -done = _.after(saves.length, function () { - console.log('Done saving!'); -}); +// _after +module TestAfter { + interface Func { + (a: string, b: number): boolean; + } -done = _(saves.length).after(function () { - console.log('Done saving!'); -}).value(); + let func: Func; + + { + let result: Func; + + _.after(42, func); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + _(42).after(func); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + _(42).chain().after(func); + } +} // _.ary result = ['6', '8', '10'].map(_.ary<(s: string) => number>(parseInt, 1)); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..93ea9733f 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6779,22 +6779,30 @@ declare module _ { //_.after interface LoDashStatic { /** - * Creates a function that executes func, with the this binding and arguments of the - * created function, only after being called n times. - * @param n The number of times the function must be called before func is executed. - * @param func The function to restrict. - * @return The new restricted function. - **/ - after( + * The opposite of _.before; this method creates a function that invokes func once it’s called n or more times. + * + * @param n The number of calls before func is invoked. + * @param func The function to restrict. + * @return Returns the new restricted function. + */ + after( n: number, - func: Function): Function; + func: TFunc + ): TFunc; } interface LoDashImplicitWrapper { /** * @see _.after **/ - after(func: Function): LoDashImplicitObjectWrapper; + after(func: TFunc): LoDashImplicitObjectWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.after + **/ + after(func: TFunc): LoDashExplicitObjectWrapper; } //_.ary From f8f1b6e06788ec8f344e8ded099c543ce9649df6 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sun, 8 Nov 2015 19:22:56 +0500 Subject: [PATCH 65/86] lodash: signatures of the method _.once have been changed --- lodash/lodash-tests.ts | 27 +++++++++++++++++++++++++-- lodash/lodash.d.ts | 9 ++++++++- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..63abc1839 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -3501,8 +3501,31 @@ result = _(testNegatePredicate).negate().value(); result = _(testNegatePredicate).negate().value(); // _.once -result = <() => void>_.once<() => void>(function () {}); -result = <() => void>(_(function () {}).once().value()); +module TestOnce { + interface Func { + (a: number, b: string): boolean; + } + + let func: Func; + + { + let result: Func; + + result = _.once(func); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _(func).once(); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(func).chain().once(); + } +} var returnedOnce = _.throttle(function (a: any) { return a * 5; }, 5); returnedOnce(4); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..9abc16c71 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7376,10 +7376,10 @@ declare module _ { /** * Creates a function that is restricted to invoking func once. Repeat calls to the function return the value * of the first call. The func is invoked with the this binding and arguments of the created function. + * * @param func The function to restrict. * @return Returns the new restricted function. */ - once(func: T): T; } @@ -7390,6 +7390,13 @@ declare module _ { once(): LoDashImplicitObjectWrapper; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.once + */ + once(): LoDashExplicitObjectWrapper; + } + //_.partial interface LoDashStatic { /** From 336552c44fa16e5c745ece423f3183ca0f91e117 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Mon, 9 Nov 2015 09:49:13 +0500 Subject: [PATCH 66/86] lodash: signatures of the methods _.forEach and _.forEachRight have been changed --- lodash/lodash-tests.ts | 206 +++++++++++++++++++++++++++-- lodash/lodash.d.ts | 289 ++++++++++++++++++++++++++++------------- 2 files changed, 392 insertions(+), 103 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..2d156b0c1 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -2427,9 +2427,9 @@ module TestEach { let list: _.List; let dictionary: _.Dictionary; - let stringIterator: (char: string, index: number, string: string) => boolean|void; - let listIterator: (value: TResult, index: number, collection: _.List) => boolean|void; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => boolean|void; + let stringIterator: (char: string, index: number, string: string) => any; + let listIterator: (value: TResult, index: number, collection: _.List) => any; + let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any; { let result: string; @@ -2516,6 +2516,101 @@ module TestEach { } } +// _.eachRight +module TestEachRight { + let array: TResult[]; + let list: _.List; + let dictionary: _.Dictionary; + + let stringIterator: (char: string, index: number, string: string) => any; + let listIterator: (value: TResult, index: number, collection: _.List) => any; + let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any; + + { + let result: string; + + _.eachRight('', stringIterator); + _.eachRight('', stringIterator, any); + } + + { + let result: TResult[]; + + _.eachRight(array, listIterator); + _.eachRight(array, listIterator, any); + } + + { + let result: _.List; + + _.eachRight(list, listIterator); + _.eachRight(list, listIterator, any); + } + + { + let result: _.Dictionary; + + _.eachRight(dictionary, dictionaryIterator); + _.eachRight(dictionary, dictionaryIterator, any); + } + + { + let result: _.LoDashImplicitWrapper; + + _('').eachRight(stringIterator); + _('').eachRight(stringIterator, any); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + _(array).eachRight(listIterator); + _(array).eachRight(listIterator, any); + } + + { + let result: _.LoDashImplicitObjectWrapper<_.List>; + + _(list).eachRight(listIterator); + _(list).eachRight(listIterator, any); + } + + { + let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; + + _(dictionary).eachRight(dictionaryIterator); + _(dictionary).eachRight(dictionaryIterator, any); + } + + { + let result: _.LoDashExplicitWrapper; + + _('').chain().eachRight(stringIterator); + _('').chain().eachRight(stringIterator, any); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + _(array).chain().eachRight(listIterator); + _(array).chain().eachRight(listIterator, any); + } + + { + let result: _.LoDashExplicitObjectWrapper<_.List>; + + _(list).chain().eachRight(listIterator); + _(list).chain().eachRight(listIterator, any); + } + + { + let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; + + _(dictionary).chain().eachRight(dictionaryIterator); + _(dictionary).chain().eachRight(dictionaryIterator, any); + } +} + // _.every module TestEvery { let array: TResult[]; @@ -2677,9 +2772,9 @@ module TestForEach { let list: _.List; let dictionary: _.Dictionary; - let stringIterator: (char: string, index: number, string: string) => boolean|void; - let listIterator: (value: TResult, index: number, collection: _.List) => boolean|void; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => boolean|void; + let stringIterator: (char: string, index: number, string: string) => any; + let listIterator: (value: TResult, index: number, collection: _.List) => any; + let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any; { let result: string; @@ -2766,17 +2861,100 @@ module TestForEach { } } -result = _.forEachRight([1, 2, 3], function (num) { console.log(num); }); -result = <_.Dictionary>_.forEachRight({ 'one': 1, 'two': 2, 'three': 3 }, function (num) { console.log(num); }); +// _.forEachRight +module TestForEachRight { + let array: TResult[]; + let list: _.List; + let dictionary: _.Dictionary; -result = _.eachRight([1, 2, 3], function (num) { console.log(num); }); -result = <_.Dictionary>_.eachRight({ 'one': 1, 'two': 2, 'three': 3 }, function (num) { console.log(num); }); + let stringIterator: (char: string, index: number, string: string) => any; + let listIterator: (value: TResult, index: number, collection: _.List) => any; + let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any; -result = <_.LoDashImplicitArrayWrapper>_([1, 2, 3]).forEachRight(function (num) { console.log(num); }); -result = <_.LoDashImplicitObjectWrapper<_.Dictionary>>_(<{ [index: string]: number; }>{ 'one': 1, 'two': 2, 'three': 3 }).forEachRight(function (num) { console.log(num); }); + { + let result: string; -result = <_.LoDashImplicitArrayWrapper>_([1, 2, 3]).eachRight(function (num) { console.log(num); }); -result = <_.LoDashImplicitObjectWrapper<_.Dictionary>>_(<{ [index: string]: number; }>{ 'one': 1, 'two': 2, 'three': 3 }).eachRight(function (num) { console.log(num); }); + _.forEachRight('', stringIterator); + _.forEachRight('', stringIterator, any); + } + + { + let result: TResult[]; + + _.forEachRight(array, listIterator); + _.forEachRight(array, listIterator, any); + } + + { + let result: _.List; + + _.forEachRight(list, listIterator); + _.forEachRight(list, listIterator, any); + } + + { + let result: _.Dictionary; + + _.forEachRight(dictionary, dictionaryIterator); + _.forEachRight(dictionary, dictionaryIterator, any); + } + + { + let result: _.LoDashImplicitWrapper; + + _('').forEachRight(stringIterator); + _('').forEachRight(stringIterator, any); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + _(array).forEachRight(listIterator); + _(array).forEachRight(listIterator, any); + } + + { + let result: _.LoDashImplicitObjectWrapper<_.List>; + + _(list).forEachRight(listIterator); + _(list).forEachRight(listIterator, any); + } + + { + let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; + + _(dictionary).forEachRight(dictionaryIterator); + _(dictionary).forEachRight(dictionaryIterator, any); + } + + { + let result: _.LoDashExplicitWrapper; + + _('').chain().forEachRight(stringIterator); + _('').chain().forEachRight(stringIterator, any); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + _(array).chain().forEachRight(listIterator); + _(array).chain().forEachRight(listIterator, any); + } + + { + let result: _.LoDashExplicitObjectWrapper<_.List>; + + _(list).chain().forEachRight(listIterator); + _(list).chain().forEachRight(listIterator, any); + } + + { + let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; + + _(dictionary).chain().forEachRight(dictionaryIterator); + _(dictionary).chain().forEachRight(dictionaryIterator, any); + } +} result = <_.Dictionary>_.groupBy([4.2, 6.1, 6.4], function (num) { return Math.floor(num); }); result = <_.Dictionary>_.groupBy([4.2, 6.1, 6.4], function (num) { return this.floor(num); }, Math); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..a0827098d 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -4031,7 +4031,7 @@ declare module _ { */ each( collection: string, - iteratee?: StringIterator, + iteratee?: StringIterator, thisArg?: any ): string; @@ -4040,7 +4040,7 @@ declare module _ { */ each( collection: T[], - iteratee?: ListIterator, + iteratee?: ListIterator, thisArg?: any ): T[]; @@ -4049,7 +4049,7 @@ declare module _ { */ each( collection: List, - iteratee?: ListIterator, + iteratee?: ListIterator, thisArg?: any ): List; @@ -4058,7 +4058,7 @@ declare module _ { */ each( collection: Dictionary, - iteratee?: DictionaryIterator, + iteratee?: DictionaryIterator, thisArg?: any ): Dictionary; } @@ -4068,7 +4068,7 @@ declare module _ { * @see _.forEach */ each( - iteratee: StringIterator, + iteratee: StringIterator, thisArg?: any ): LoDashImplicitWrapper; } @@ -4078,7 +4078,7 @@ declare module _ { * @see _.forEach */ each( - iteratee: ListIterator, + iteratee: ListIterator, thisArg?: any ): LoDashImplicitArrayWrapper; } @@ -4088,7 +4088,7 @@ declare module _ { * @see _.forEach */ each( - iteratee?: ListIterator|DictionaryIterator, + iteratee?: ListIterator|DictionaryIterator, thisArg?: any ): LoDashImplicitObjectWrapper; } @@ -4098,7 +4098,7 @@ declare module _ { * @see _.forEach */ each( - iteratee: StringIterator, + iteratee: StringIterator, thisArg?: any ): LoDashExplicitWrapper; } @@ -4108,7 +4108,7 @@ declare module _ { * @see _.forEach */ each( - iteratee: ListIterator, + iteratee: ListIterator, thisArg?: any ): LoDashExplicitArrayWrapper; } @@ -4118,7 +4118,106 @@ declare module _ { * @see _.forEach */ each( - iteratee?: ListIterator|DictionaryIterator, + iteratee?: ListIterator|DictionaryIterator, + thisArg?: any + ): LoDashExplicitObjectWrapper; + } + + //_.eachRight + interface LoDashStatic { + /** + * @see _.forEachRight + */ + eachRight( + collection: string, + iteratee?: StringIterator, + thisArg?: any + ): string; + + /** + * @see _.forEachRight + */ + eachRight( + collection: T[], + iteratee?: ListIterator, + thisArg?: any + ): T[]; + + /** + * @see _.forEachRight + */ + eachRight( + collection: List, + iteratee?: ListIterator, + thisArg?: any + ): List; + + /** + * @see _.forEachRight + */ + eachRight( + collection: Dictionary, + iteratee?: DictionaryIterator, + thisArg?: any + ): Dictionary; + } + + interface LoDashImplicitWrapper { + /** + * @see _.forEachRight + */ + eachRight( + iteratee: StringIterator, + thisArg?: any + ): LoDashImplicitWrapper; + } + + interface LoDashImplicitArrayWrapper { + /** + * @see _.forEachRight + */ + eachRight( + iteratee: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; + } + + interface LoDashImplicitObjectWrapper { + /** + * @see _.forEachRight + */ + eachRight( + iteratee?: ListIterator|DictionaryIterator, + thisArg?: any + ): LoDashImplicitObjectWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.forEachRight + */ + eachRight( + iteratee: StringIterator, + thisArg?: any + ): LoDashExplicitWrapper; + } + + interface LoDashExplicitArrayWrapper { + /** + * @see _.forEachRight + */ + eachRight( + iteratee: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.forEachRight + */ + eachRight( + iteratee?: ListIterator|DictionaryIterator, thisArg?: any ): LoDashExplicitObjectWrapper; } @@ -4854,7 +4953,7 @@ declare module _ { */ forEach( collection: string, - iteratee?: StringIterator, + iteratee?: StringIterator, thisArg?: any ): string; @@ -4863,7 +4962,7 @@ declare module _ { */ forEach( collection: T[], - iteratee?: ListIterator, + iteratee?: ListIterator, thisArg?: any ): T[]; @@ -4872,7 +4971,7 @@ declare module _ { */ forEach( collection: List, - iteratee?: ListIterator, + iteratee?: ListIterator, thisArg?: any ): List; @@ -4881,7 +4980,7 @@ declare module _ { */ forEach( collection: Dictionary, - iteratee?: DictionaryIterator, + iteratee?: DictionaryIterator, thisArg?: any ): Dictionary; } @@ -4891,7 +4990,7 @@ declare module _ { * @see _.forEach */ forEach( - iteratee: StringIterator, + iteratee: StringIterator, thisArg?: any ): LoDashImplicitWrapper; } @@ -4901,7 +5000,7 @@ declare module _ { * @see _.forEach */ forEach( - iteratee: ListIterator, + iteratee: ListIterator, thisArg?: any ): LoDashImplicitArrayWrapper; } @@ -4911,7 +5010,7 @@ declare module _ { * @see _.forEach */ forEach( - iteratee?: ListIterator|DictionaryIterator, + iteratee?: ListIterator|DictionaryIterator, thisArg?: any ): LoDashImplicitObjectWrapper; } @@ -4921,7 +5020,7 @@ declare module _ { * @see _.forEach */ forEach( - iteratee: StringIterator, + iteratee: StringIterator, thisArg?: any ): LoDashExplicitWrapper; } @@ -4931,7 +5030,7 @@ declare module _ { * @see _.forEach */ forEach( - iteratee: ListIterator, + iteratee: ListIterator, thisArg?: any ): LoDashExplicitArrayWrapper; } @@ -4941,7 +5040,7 @@ declare module _ { * @see _.forEach */ forEach( - iteratee?: ListIterator|DictionaryIterator, + iteratee?: ListIterator|DictionaryIterator, thisArg?: any ): LoDashExplicitObjectWrapper; } @@ -4949,94 +5048,106 @@ declare module _ { //_.forEachRight interface LoDashStatic { /** - * This method is like _.forEach except that it iterates over elements of a - * collection from right to left. - * @param collection The collection to iterate over. - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - **/ - forEachRight( - collection: Array, - callback: ListIterator, - thisArg?: any): Array; + * This method is like _.forEach except that it iterates over elements of collection from right to left. + * + * @alias _.eachRight + * + * @param collection The collection to iterate over. + * @param iteratee The function called per iteration. + * @param thisArg The this binding of callback. + */ + forEachRight( + collection: string, + iteratee?: StringIterator, + thisArg?: any + ): string; /** - * @see _.forEachRight - **/ + * @see _.forEachRight + */ + forEachRight( + collection: T[], + iteratee?: ListIterator, + thisArg?: any + ): T[]; + + /** + * @see _.forEachRight + */ forEachRight( collection: List, - callback: ListIterator, - thisArg?: any): List; + iteratee?: ListIterator, + thisArg?: any + ): List; /** - * @see _.forEachRight - **/ - forEachRight( - object: Dictionary, - callback: DictionaryIterator, - thisArg?: any): Dictionary; + * @see _.forEachRight + */ + forEachRight( + collection: Dictionary, + iteratee?: DictionaryIterator, + thisArg?: any + ): Dictionary; + } + interface LoDashImplicitWrapper { /** - * @see _.forEachRight - **/ - eachRight( - collection: Array, - callback: ListIterator, - thisArg?: any): Array; - - /** - * @see _.forEachRight - **/ - eachRight( - collection: List, - callback: ListIterator, - thisArg?: any): List; - - /** - * @see _.forEachRight - * @param object The object to iterate over - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - **/ - eachRight( - object: Dictionary, - callback: DictionaryIterator, - thisArg?: any): Dictionary; + * @see _.forEachRight + */ + forEachRight( + iteratee: StringIterator, + thisArg?: any + ): LoDashImplicitWrapper; } interface LoDashImplicitArrayWrapper { /** - * @see _.forEachRight - **/ + * @see _.forEachRight + */ forEachRight( - callback: ListIterator, - thisArg?: any): LoDashImplicitArrayWrapper; - - /** - * @see _.forEachRight - **/ - eachRight( - callback: ListIterator, - thisArg?: any): LoDashImplicitArrayWrapper; + iteratee: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; } interface LoDashImplicitObjectWrapper { /** - * @see _.forEachRight - **/ - forEachRight( - callback: ObjectIterator, - thisArg?: any): LoDashImplicitObjectWrapper>; + * @see _.forEachRight + */ + forEachRight( + iteratee?: ListIterator|DictionaryIterator, + thisArg?: any + ): LoDashImplicitObjectWrapper; + } + interface LoDashExplicitWrapper { /** - * @see _.forEachRight - * @param object The object to iterate over - * @param callback The function called per iteration. - * @param thisArg The this binding of callback. - **/ - eachRight( - callback: ObjectIterator, - thisArg?: any): LoDashImplicitObjectWrapper>; + * @see _.forEachRight + */ + forEachRight( + iteratee: StringIterator, + thisArg?: any + ): LoDashExplicitWrapper; + } + + interface LoDashExplicitArrayWrapper { + /** + * @see _.forEachRight + */ + forEachRight( + iteratee: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.forEachRight + */ + forEachRight( + iteratee?: ListIterator|DictionaryIterator, + thisArg?: any + ): LoDashExplicitObjectWrapper; } //_.groupBy From e6f19b91d05776697fc389ed71343dd8bf66fc72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Radek=20Hol=C3=BD?= Date: Mon, 9 Nov 2015 10:54:17 +0100 Subject: [PATCH 67/86] Add definitions for temp-fs. They don't want to include the definitions upstream thus I am publishing it at least here. See https://github.com/jakwings/node-temp-fs/pull/2 --- temp-fs/temp-fs-tests.ts | 31 ++++++ temp-fs/temp-fs.d.ts | 211 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 242 insertions(+) create mode 100644 temp-fs/temp-fs-tests.ts create mode 100644 temp-fs/temp-fs.d.ts diff --git a/temp-fs/temp-fs-tests.ts b/temp-fs/temp-fs-tests.ts new file mode 100644 index 000000000..9d01e31f3 --- /dev/null +++ b/temp-fs/temp-fs-tests.ts @@ -0,0 +1,31 @@ +// Copied from https://github.com/jakwings/node-temp-fs/blob/60a4d2586a81a7057bd4a395ec8c00b4100f84fe/README.md +// and slightly modified. + +/// + +// Create a tempfile in the system-provided tempdir. +tempfs.open(function (err:any, file:tempfs.file) { + if (err) { throw err; } + + console.log(file.path, file.fd); + // async + file.unlink(function () { + console.log('File delected'); + }); + // sync + // No problem even if unlink() is called twice. + file.unlink(); +}); + +// Create a tempdir in current directory. +tempfs.mkdir({ + dir: '.', + recursive: true, // It and its content will be remove recursively. + track: true // Track this directory. +}, function (err:any, dir:tempfs.dir) { + if (err) { throw err; } + + console.log(dir.path, dir.recursive); + throw new Error('Since it is tracked, tempfs will remove it for you.'); + dir.unlink(); +}); diff --git a/temp-fs/temp-fs.d.ts b/temp-fs/temp-fs.d.ts new file mode 100644 index 000000000..a833c773f --- /dev/null +++ b/temp-fs/temp-fs.d.ts @@ -0,0 +1,211 @@ +// Type definitions for temp-fs v0.9.8 +// Project: https://github.com/jakwings/node-temp-fs +// Definitions by: MEDIA CHECK s.r.o. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * A temporary file and directory creator. + */ +declare module tempfs { + + /** + * A tempdir. + */ + interface dir { + /** + * The absolute path to the tempdir. + */ + path: String; + + /** + * Whether {@link dir#unlink} will remove the tempdir recursively. + */ + recursive: Boolean; + + /** + * A special function for you to remove the directory. + * + * If the directory is not tracked, it may throw when an error occurs or + * the first argument of the callback function will be an Error object. + * + * @param callback makes it asynchronous. + */ + unlink(callback?:(error:Error)=>any): any; + } + + /** + * A tempfile. + */ + interface file { + /** + * The absolute path to the tempfile. + */ + path: String; + + /** + * An integer file descriptor. + */ + fd: Number; + + /** + * A special function for you to delete the file. + * + * If the file is not tracked, it may throw when an error occurs or the + * first argument of the callback function will be an Error object. + * + * @param callback makes it asynchronous. + */ + unlink(callback?:(error:Error)=>any): any; + } + + /** + * Options. + */ + interface options { + /** + * Where to put the generated tempfile or tempdir. + * + * Also see {@link options#name}. Default: tempfs.dir() + */ + dir?: String; + + /** + * The maximum number of chance to retry before throwing an error. + * + * It should be a finite number. Default: 5 + */ + limit?: Number; + + /** + * File mode (default: 0600) or directory mode (default: 0700) to use. + */ + mode?: Number; + + /** + * If set, join the two paths {@link options#dir} || + * tempfs.dir() and {@link options#name} together and use the + * result as the customized filename/pathname. + */ + name?: String; + + /** + * The prefix for the generated random name. + * + * Default: "tmp-" + */ + prefix?: String; + + /** + * Whether {@link dir#unlink} should remove a directory recursively. + * + * Default: false + */ + recursive?: Boolean; + + /** + * The suffix for the generated random name. + * + * Default: "" + */ + suffix?: String; + + /** + * A string containing some capital letters Xs for substitution with + * random characters. + * + * Then it is used as part of the filename/dirname. Just like what you + * do with the mktemp(3) function in the C library. + */ + template?: String; + + /** + * If set to true, let temp-fs manage the the current file/directory for + * you even if the global tracking is off. If set to false, don't let + * temp-fs manage it even if the global tracking is on. Otherwise, use + * the current global setting. + */ + track?: Boolean; + } + + /** + * Remove all tracked files and directories asynchronously. + */ + function clear(callback?:()=>any):any; + + /** + * Remove all tracked files and directories synchronously. + */ + function clearSync():any; + + /** + * Return the path of a system-provided tempdir as + * require('os').tmpdir() does. + * + * You should not make any assumption about whether the path contains a + * trailing path separator, or it is a real path. On most system it is not a + * fixed path, and it can be changed by the user environment. When in doubt, + * check it first. + */ + function dir():string; + + /** + * Try to create a new tempdir asynchronously. + * + * @param callback function receives two arguments error and + * dir. If error is + * null, dir has the properties of + * {@link dir}. + */ + function mkdir(options?:options, callback?:(err:any, dir:dir)=>any):any; + + /** + * The synchronous version of {@link mkdir}. + * + * @throws when an error happens. + */ + function mkdirSync(options?:options):dir; + + /** + * Return a customized/random filename/dirname. + */ + function name(options?:options):string; + + /** + * Try to open a unique tempfile asynchronously. + * + * @param callback function receives two arguments error and + * file. If error is + * null, file has the properties + * of {@link file}. + */ + function open(options?:options, callback?:(err:any, file:file)=>any):any; + + /** + * The synchronous version of {@link open}. + * + * @throws when an error happens. + */ + function openSync(options?:options):file; + + /** + * Use it to switch global files/directories tracking on or off. + * + * Turn it on if you don't want to manually delete everything. When it is + * turned off, all recorded files and directories will not be removed but + * still kept in case it is turned on again before the program exits. + * + * This switch does not affect manually tracked files through + * {@link options#track}. They will be removed automatically on exit. + * + * Note: When an uncaught exception occurs, all tracked temporary files + * and directories will be removed no matter it is on or off. + */ + function track(on?:Boolean):void; +} + +/** + * A temporary file and directory creator. + */ +declare module "temp-fs" { + export = tempfs; +} From a6758d638b885c37d7bd5ef34ef254337f9dce96 Mon Sep 17 00:00:00 2001 From: bgrieder Date: Mon, 9 Nov 2015 11:36:09 +0100 Subject: [PATCH 68/86] Lots of fixes + TextInput + ScrollView + LstView --- react-native/react-native.d.ts | 752 ++++++++++++++++++++++++++++++++- 1 file changed, 731 insertions(+), 21 deletions(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index 1432026c2..7f5832749 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -163,6 +163,7 @@ declare namespace ReactNative { /** * Flex Prop Types * @see https://facebook.github.io/react-native/docs/flexbox.html#proptypes + * @see LayoutPropTypes.js */ export interface FlexStyle { @@ -201,6 +202,19 @@ declare namespace ReactNative { } + export interface TransformsStyle { + + transform?: [{perspective: number}, {rotate: string}, {rotateX: string}, {rotateY: string}, {rotateZ: string}, {scale: number}, {scaleX: number}, {scaleY: number}, {translateX: number}, {translateY: number}, {skewX: string}, {skewY: string}] + transformMatrix?: Array + rotation?: number + scaleX?: number + scaleY?: number + translateX?: number + translateY?: number + + } + + export interface StyleSheetProperties { // TODO: } @@ -264,12 +278,230 @@ declare namespace ReactNative { style?: TextStyle; } + + /** + * IOS Specific properties for TextInput + * @see https://facebook.github.io/react-native/docs/textinput.html#props + */ + export interface TextInputIOSProperties { + + /** + * If true, the text field will blur when submitted. + * The default value is true. + */ + blurOnSubmit?: boolean + + /** + * enum('never', 'while-editing', 'unless-editing', 'always') + * When the clear button should appear on the right side of the text view + */ + clearButtonMode?: string + + /** + * If true, clears the text field automatically when editing begins + */ + clearTextOnFocus?: boolean + + /** + * If true, the keyboard disables the return key when there is no text and automatically enables it when there is text. + * The default value is false. + */ + enablesReturnKeyAutomatically?: boolean + + /** + * Callback that is called when a key is pressed. + * Pressed key value is passed as an argument to the callback handler. + * Fires before onChange callbacks. + */ + onKeyPress?: () => void + + /** + * enum('default', 'go', 'google', 'join', 'next', 'route', 'search', 'send', 'yahoo', 'done', 'emergency-call') + * Determines how the return key should look. + */ + returnKeyType?: string + + /** + * If true, all text will automatically be selected on focus + */ + selectTextOnFocus?: boolean + + /** + * //FIXME: require typing + * See DocumentSelectionState.js, some state that is responsible for maintaining selection information for a document + */ + selectionState?: any + + + } + + /** + * Android Specific properties for TextInput + * @see https://facebook.github.io/react-native/docs/textinput.html#props + */ + export interface TextInputAndroidProperties { + + /** + * Sets the number of lines for a TextInput. + * Use it with multiline set to true to be able to fill the lines. + */ + numberOfLines?: number + + /** + * enum('start', 'center', 'end') + * Set the position of the cursor from where editing will begin. + */ + textAlign?: string + + /** + * enum('top', 'center', 'bottom') + * Aligns text vertically within the TextInput. + */ + textAlignVertical?: string + + /** + * The color of the textInput underline. + */ + underlineColorAndroid?: string + } + + + /** + * @see https://facebook.github.io/react-native/docs/textinput.html#props + */ + export interface TextInputProperties extends TextInputIOSProperties, TextInputAndroidProperties { + + /** + * Can tell TextInput to automatically capitalize certain characters. + * characters: all characters, + * words: first letter of each word + * sentences: first letter of each sentence (default) + * none: don't auto capitalize anything + * + * https://facebook.github.io/react-native/docs/textinput.html#autocapitalize + */ + autoCapitalize?: string + + /** + * If false, disables auto-correct. + * The default value is true. + */ + autoCorrect?: boolean + + /** + * If true, focuses the input on componentDidMount. + * The default value is false. + */ + autoFocus?: boolean + + /** + * Provides an initial value that will change when the user starts typing. + * Useful for simple use-cases where you don't want to deal with listening to events + * and updating the value prop to keep the controlled state in sync. + */ + defaultValue?: string + + /** + * If false, text is not editable. The default value is true. + */ + editable?: boolean + + /** + * enum("default", 'numeric', 'email-address', "ascii-capable", 'numbers-and-punctuation', 'url', 'number-pad', 'phone-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search') + * Determines which keyboard to open, e.g.numeric. + * The following values work across platforms: - default - numeric - email-address + */ + keyboardType?: string + + /** + * Limits the maximum number of characters that can be entered. + * Use this instead of implementing the logic in JS to avoid flicker. + */ + maxLength?: number + + /** + * If true, the text input can be multiple lines. The default value is false. + */ + multiline?: boolean + + /** + * Callback that is called when the text input is blurred + */ + onBlur?: () => void + + /** + * Callback that is called when the text input's text changes. + */ + onChange?: () => void + + /** + * Callback that is called when the text input's text changes. + * Changed text is passed as an argument to the callback handler. + */ + onChangeText?: () => void + + /** + * Callback that is called when text input ends. + */ + onEndEditing?: () => void + + /** + * Callback that is called when the text input is focused + */ + onFocus?: () => void + + /** + * Invoked on mount and layout changes with {x, y, width, height}. + */ + onLayout?: () => void + + /** + * Callback that is called when the text input's submit button is pressed. + */ + onSubmitEditing?: () => void + + /** + * The string that will be rendered before text input has been entered + */ + placeholder?: string + + /** + * The text color of the placeholder string + */ + placeholderTextColor?: string + + /** + * If true, the text input obscures the text entered so that sensitive text like passwords stay secure. + * The default value is false. + */ + secureTextEntry?: boolean + + /** + * Styles + */ + style?: TextStyle + + /** + * Used to locate this view in end-to-end tests + */ + testID?: string + + /** + * The value to show for the text input. TextInput is a controlled component, + * which means the native value will be forced to match this value prop if provided. + * For most uses this works great, but in some cases this may cause flickering - one common cause is preventing edits by keeping value the same. + * In addition to simply setting the same value, either set editable={false}, + * or set/update maxLength to prevent unwanted edits without flicker. + */ + value?: string + } + export interface AccessibilityTraits { // TODO } // @see https://facebook.github.io/react-native/docs/view.html#style - export interface ViewStyle extends FlexStyle { + export interface ViewStyle extends FlexStyle, TransformsStyle { backgroundColor?: string; borderBottomColor?: string; borderBottomLeftRadius?: number; @@ -292,7 +524,7 @@ declare namespace ReactNative { /** * @see https://facebook.github.io/react-native/docs/view.html#props */ - export interface ViewProperties { + export interface ViewProperties extends React.Props { /** * accessibilityLabel string * @@ -426,6 +658,10 @@ declare namespace ReactNative { testID?: string; } + interface ViewStatic extends React.ComponentClass { + + } + /** * @see https://facebook.github.io/react-native/docs/activityindicatorios.html#props */ @@ -487,7 +723,7 @@ declare namespace ReactNative { /** * @see https://facebook.github.io/react-native/docs/navigator.html#content */ - export interface NavigatorProperties { + export interface NavigatorProperties extends React.Props { /** * Optional function that allows configuration about scene animations and gestures. * Will be invoked with the route and should return a scene configuration object @@ -534,7 +770,7 @@ declare namespace ReactNative { * @param route * @param navigator */ - renderScene: (route: Route, navigator: Navigator) => React.ComponentClass + renderScene: ( route: Route, navigator: Navigator ) => React.ComponentClass /** * Styles to apply to the container of each scene @@ -542,7 +778,7 @@ declare namespace ReactNative { sceneStyle: ViewStyle } - export interface NavigatorIOSProperties { + export interface NavigatorIOSProperties extends React.Props { /** * NavigatorIOS uses "route" objects to identify child views, their props, and navigation bar configuration. @@ -587,6 +823,10 @@ declare namespace ReactNative { style?: ViewStyle } + interface NavigatorIOSStatic extends React.ComponentClass { + + } + /** * @see @@ -598,7 +838,7 @@ declare namespace ReactNative { /** * @see https://facebook.github.io/react-native/docs/sliderios.html */ - export interface SliderIOSProperties { + export interface SliderIOSProperties extends React.Props { /** maximumTrackTintColor string The color used for the track to the right of the button. Overrides the default blue gradient image. @@ -645,6 +885,10 @@ declare namespace ReactNative { value?: number; } + interface SliderIOSStatic extends React.ComponentClass { + + } + /** * @see */ @@ -672,7 +916,7 @@ declare namespace ReactNative { /** * @see https://facebook.github.io/react-native/docs/image.html */ - export interface ImageProperties { + export interface ImageProperties extends React.Props { /** * onLayout function * @@ -758,8 +1002,113 @@ declare namespace ReactNative { /** * @see */ - export interface ListViewProperties { - /// TODO + export interface ListViewProperties extends ScrollViewProperties, React.Props{ + + dataSource?: ListViewDataSource + + /** + * How many rows to render on initial component mount. Use this to make + * it so that the first screen worth of data apears at one time instead of + * over the course of multiple frames. + */ + initialListSize?: number + + /** + * (visibleRows, changedRows) => void + * + * Called when the set of visible rows changes. `visibleRows` maps + * { sectionID: { rowID: true }} for all the visible rows, and + * `changedRows` maps { sectionID: { rowID: true | false }} for the rows + * that have changed their visibility, with true indicating visible, and + * false indicating the view has moved out of view. + */ + onChangeVisibleRows?: (visibleRows: Array<{[sectionId: string]: {[rowID: string]: boolean}}>, changedRows: Array<{[sectionId: string]: {[rowID: string]: boolean}}>) => void + + /** + * Called when all rows have been rendered and the list has been scrolled + * to within onEndReachedThreshold of the bottom. The native scroll + * event is provided. + */ + onEndReached?: () => void + + /** + * Threshold in pixels for onEndReached. + */ + onEndReachedThreshold?: number + + /** + * Number of rows to render per event loop. + */ + pageSize?: number + + /** + * An experimental performance optimization for improving scroll perf of + * large lists, used in conjunction with overflow: 'hidden' on the row + * containers. Use at your own risk. + */ + removeClippedSubviews?: boolean + + /** + * () => renderable + * + * The header and footer are always rendered (if these props are provided) + * on every render pass. If they are expensive to re-render, wrap them + * in StaticContainer or other mechanism as appropriate. Footer is always + * at the bottom of the list, and header at the top, on every render pass. + */ + renderFooter?: () => React.ReactElement + + /** + * () => renderable + * + * The header and footer are always rendered (if these props are provided) + * on every render pass. If they are expensive to re-render, wrap them + * in StaticContainer or other mechanism as appropriate. Footer is always + * at the bottom of the list, and header at the top, on every render pass. + */ + renderHeader?: () => React.ReactElement + + /** + * (rowData, sectionID, rowID) => renderable + * Takes a data entry from the data source and its ids and should return + * a renderable component to be rendered as the row. By default the data + * is exactly what was put into the data source, but it's also possible to + * provide custom extractors. + */ + renderRow?: (rowData: any, sectionID: string, rowID: string, highlightRow?: boolean) => React.ReactElement + + + /** + * A function that returns the scrollable component in which the list rows are rendered. + * Defaults to returning a ScrollView with the given props. + */ + renderScrollComponent?: (props: ScrollViewProperties) => React.ReactElement + + /** + * (sectionData, sectionID) => renderable + * + * If provided, a sticky header is rendered for this section. The sticky + * behavior means that it will scroll with the content at the top of the + * section until it reaches the top of the screen, at which point it will + * stick to the top until it is pushed off the screen by the next section + * header. + */ + renderSectionHeader?: (sectionData: any, sectionId: string) => React.ReactElement + + + /** + * (sectionID, rowID, adjacentRowHighlighted) => renderable + * If provided, a renderable component to be rendered as the separator below each row + * but not the last row if there is a section header below. + * Take a sectionID and rowID of the row above and whether its adjacent row is highlighted. + */ + renderSeparator?: (sectionID: string, rowID: string, adjacentRowHighlighted?: boolean) => React.ReactElement + + /** + * How early to start rendering rows before they come on screen, in + * pixels. + */ + scrollRenderAheadDistance?: number } /** @@ -952,13 +1301,85 @@ declare namespace ReactNative { create( styles: T ): T; } + /** + * //FIXME: Could not find docs. Inferred from examples and jscode : ListViewDataSource.js + */ export interface DataSourceAssetCallback { - rowHasChanged: ( r1: any[], r2: any[] ) => boolean; + rowHasChanged?: ( r1: any, r2: any ) => boolean + sectionHeaderHasChanged?: ( h1: any, h2: any ) => boolean + getRowData?: ( dataBlob: any, sectionID: number | string, rowID: number | string ) => T + getSectionHeaderData?: ( dataBlob: any, sectionID: number | string ) => T } + /** + * //FIXME: Could not find docs. Inferred from examples and js code: ListViewDataSource.js + */ export interface ListViewDataSource { new( onAsset: DataSourceAssetCallback ): ListViewDataSource; - cloneWithRows( rowList: T[][] ): void; + /** + * Clones this `ListViewDataSource` with the specified `dataBlob` and + * `rowIdentities`. The `dataBlob` is just an aribitrary blob of data. At + * construction an extractor to get the interesting informatoin was defined + * (or the default was used). + * + * The `rowIdentities` is is a 2D array of identifiers for rows. + * ie. [['a1', 'a2'], ['b1', 'b2', 'b3'], ...]. If not provided, it's + * assumed that the keys of the section data are the row identities. + * + * Note: This function does NOT clone the data in this data source. It simply + * passes the functions defined at construction to a new data source with + * the data specified. If you wish to maintain the existing data you must + * handle merging of old and new data separately and then pass that into + * this function as the `dataBlob`. + */ + cloneWithRows( dataBlob: Array | {[key: string]: any}, rowIdentities?: Array ): ListViewDataSource + + /** + * This performs the same function as the `cloneWithRows` function but here + * you also specify what your `sectionIdentities` are. If you don't care + * about sections you should safely be able to use `cloneWithRows`. + * + * `sectionIdentities` is an array of identifiers for sections. + * ie. ['s1', 's2', ...]. If not provided, it's assumed that the + * keys of dataBlob are the section identities. + * + * Note: this returns a new object! + */ + cloneWithRowsAndSections( dataBlob: Array | {[key: string]: any}, sectionIdentities?: Array, rowIdentities?: Array> ): ListViewDataSource + + getRowCount(): number + + /** + * Gets the data required to render the row. + */ + getRowData( sectionIndex: number, rowIndex: number ): any + + /** + * Gets the rowID at index provided if the dataSource arrays were flattened, + * or null of out of range indexes. + */ + getRowIDForFlatIndex( index: number ): string + + /** + * Gets the sectionID at index provided if the dataSource arrays were flattened, + * or null for out of range indexes. + */ + getSectionIDForFlatIndex( index: number ): string + + /** + * Returns an array containing the number of rows in each section + */ + getSectionLengths(): Array + + /** + * Returns if the section header is dirtied and needs to be rerendered + */ + sectionHeaderShouldUpdate( sectionIndex: number ): boolean + + /** + * Gets the data required to render the section header + */ + getSectionHeaderData( sectionIndex: number ): any } export interface ListViewStatic extends React.ComponentClass { @@ -1135,7 +1556,279 @@ declare namespace ReactNative { runAfterInteractions( fn: () => void ): void; } - export interface ScrollViewProperties { + + export interface ScrollViewStyle extends FlexStyle, TransformsStyle { + + backfaceVisibility?:string //enum('visible', 'hidden') + backgroundColor?: string + borderColor?: string + borderTopColor?: string + borderRightColor?: string + borderBottomColor?: string + borderLeftColor?: string + borderRadius?: number + borderTopLeftRadius?: number + borderTopRightRadius?: number + borderBottomLeftRadius?: number + borderBottomRightRadius?: number + borderStyle?: string //enum('solid', 'dotted', 'dashed') + borderWidth?: number + borderTopWidth?: number + borderRightWidth?: number + borderBottomWidth?: number + borderLeftWidth?: number + opacity?: number + overflow?: string //enum('visible', 'hidden') + shadowColor?: string + shadowOffset?: {width: number; height: number} + shadowOpacity?: number + shadowRadius?: number + } + + export interface EdgeInsetsProperties { + top: number + left: number + bottom: number + right: number + } + + export interface PointProperties { + x: number + y: number + } + + export interface ScrollViewIOSProperties { + + /** + * When true the scroll view bounces horizontally when it reaches the end + * even if the content is smaller than the scroll view itself. The default + * value is true when `horizontal={true}` and false otherwise. + */ + alwaysBounceHorizontal?: boolean + /** + * When true the scroll view bounces vertically when it reaches the end + * even if the content is smaller than the scroll view itself. The default + * value is false when `horizontal={true}` and true otherwise. + */ + alwaysBounceVertical?: boolean + + /** + * Controls whether iOS should automatically adjust the content inset for scroll views that are placed behind a navigation bar or tab bar/ toolbar. + * The default value is true. + */ + automaticallyAdjustContentInsets?: boolean // true + + /** + * When true the scroll view bounces when it reaches the end of the + * content if the content is larger then the scroll view along the axis of + * the scroll direction. When false it disables all bouncing even if + * the `alwaysBounce*` props are true. The default value is true. + */ + bounces?: boolean + /** + * When true gestures can drive zoom past min/max and the zoom will animate + * to the min/max value at gesture end otherwise the zoom will not exceed + * the limits. + */ + bouncesZoom?: boolean + + /** + * When false once tracking starts won't try to drag if the touch moves. + * The default value is true. + */ + canCancelContentTouches?: boolean + + /** + * When true the scroll view automatically centers the content when the + * content is smaller than the scroll view bounds; when the content is + * larger than the scroll view this property has no effect. The default + * value is false. + */ + centerContent?: boolean + + + /** + * The amount by which the scroll view content is inset from the edges of the scroll view. + * Defaults to {0, 0, 0, 0}. + */ + contentInset?: EdgeInsetsProperties // zeros + + /** + * Used to manually set the starting scroll offset. + * The default value is {x: 0, y: 0} + */ + contentOffset?: PointProperties // zeros + + /** + * A floating-point number that determines how quickly the scroll view + * decelerates after the user lifts their finger. Reasonable choices include + * - Normal: 0.998 (the default) + * - Fast: 0.9 + */ + decelerationRate?: number + + /** + * When true the ScrollView will try to lock to only vertical or horizontal + * scrolling while dragging. The default value is false. + */ + directionalLockEnabled?: boolean + + /** + * The maximum allowed zoom scale. The default value is 1.0. + */ + maximumZoomScale?: number + + /** + * The minimum allowed zoom scale. The default value is 1.0. + */ + minimumZoomScale?: number + + /** + * Called when a scrolling animation ends. + */ + onScrollAnimationEnd?: () => void + + /** + * When true the scroll view stops on multiples of the scroll view's size + * when scrolling. This can be used for horizontal pagination. The default + * value is false. + */ + pagingEnabled?: boolean + + /** + * When false, the content does not scroll. The default value is true + */ + scrollEnabled?: boolean // true + + /** + * This controls how often the scroll event will be fired while scrolling (in events per seconds). + * A higher number yields better accuracy for code that is tracking the scroll position, + * but can lead to scroll performance problems due to the volume of information being send over the bridge. + * The default value is zero, which means the scroll event will be sent only once each time the view is scrolled. + */ + scrollEventThrottle?: number // null + + /** + * The amount by which the scroll view indicators are inset from the edges of the scroll view. + * This should normally be set to the same value as the contentInset. + * Defaults to {0, 0, 0, 0}. + */ + scrollIndicatorInsets?: EdgeInsetsProperties //zeroes + + /** + * When true the scroll view scrolls to top when the status bar is tapped. + * The default value is true. + */ + scrollsToTop?: boolean + + /** + * When snapToInterval is set, snapToAlignment will define the relationship of the the snapping to the scroll view. + * - start (the default) will align the snap at the left (horizontal) or top (vertical) + * - center will align the snap in the center + * - end will align the snap at the right (horizontal) or bottom (vertical) + */ + snapToAlignment?: string + + /** + * When set, causes the scroll view to stop at multiples of the value of snapToInterval. + * This can be used for paginating through children that have lengths smaller than the scroll view. + * Used in combination with snapToAlignment. + */ + snapToInterval?: number + + /** + * An array of child indices determining which children get docked to the + * top of the screen when scrolling. For example passing + * `stickyHeaderIndices={[0]}` will cause the first child to be fixed to the + * top of the scroll view. This property is not supported in conjunction + * with `horizontal={true}`. + */ + stickyHeaderIndices?: number[] + + /** + * The current scale of the scroll view content. The default value is 1.0. + */ + zoomScale?: number + } + + export interface ScrollViewProperties extends ScrollViewIOSProperties { + + /** + * These styles will be applied to the scroll view content container which + * wraps all of the child views. Example: + * + * return ( + * + * + * ); + * ... + * var styles = StyleSheet.create({ + * contentContainer: { + * paddingVertical: 20 + * } + * }); + */ + contentContainerStyle?: ViewStyle + + /** + * When true the scroll view's children are arranged horizontally in a row + * instead of vertically in a column. The default value is false. + */ + horizontal?: boolean + + /** + * Determines whether the keyboard gets dismissed in response to a drag. + * - 'none' (the default) drags do not dismiss the keyboard. + * - 'onDrag' the keyboard is dismissed when a drag begins. + * - 'interactive' the keyboard is dismissed interactively with the drag + * and moves in synchrony with the touch; dragging upwards cancels the + * dismissal. + */ + keyboardDismissMode?: string + + /** + * When false tapping outside of the focused text input when the keyboard + * is up dismisses the keyboard. When true the scroll view will not catch + * taps and the keyboard will not dismiss automatically. The default value + * is false. + */ + keyboardShouldPersistTaps?: boolean + + /** + * Fires at most once per frame during scrolling. + * The frequency of the events can be contolled using the scrollEventThrottle prop. + */ + onScroll?: () => void + + /** + * Experimental: When true offscreen child views (whose `overflow` value is + * `hidden`) are removed from their native backing superview when offscreen. + * This canimprove scrolling performance on long lists. The default value is + * false. + */ + removeClippedSubviews?: boolean + + /** + * When true, shows a horizontal scroll indicator. + */ + showsHorizontalScrollIndicator?: boolean + + /** + * When true, shows a vertical scroll indicator. + */ + showsVerticalScrollIndicator?: boolean + + /** + * Style + */ + style?: ScrollViewStyle + } + + export interface ScrollViewProps extends ScrollViewProperties, React.Props { + + } + + interface ScrollViewStatic extends React.ComponentClass { } @@ -1173,20 +1866,23 @@ declare namespace ReactNative { // exported singletons: // export var AppRegistry: AppRegistryStatic; - export var StyleSheet: StyleSheetStatic; - export var Navigator: NavigatorStatic; - export type Navigator = NavigatorStatic; - export var ListView: ListViewStatic; + export var AsyncStorage: AsyncStorageStatic; export var CameraRoll: CameraRollStatic; export var Image: ImageStatic; export type Image = ImageStatic; + export var ListView: ListViewStatic; + export type Navigator = NavigatorStatic; + export var Navigator: NavigatorStatic; + export var NavigatorIOS: NavigatorIOSStatic; + export var SliderIOS: SliderIOSStatic; + export var ScrollView: ScrollViewStatic + export var StyleSheet: StyleSheetStatic; export var TabBarIOS: TabBarIOSStatic; export type TabBarIOS = TabBarIOSStatic; - export var AsyncStorage: AsyncStorageStatic; + export var View: ViewStatic; export var Text: React.ComponentClass; - export var View: React.ComponentClass; - export var NavigatorIOS: React.ComponentClass; + export var TextInput: React.ComponentClass; export var AlertIOS: React.ComponentClass; export var SegmentedControlIOS: React.ComponentClass; export var SwitchIOS: React.ComponentClass; @@ -1201,9 +1897,7 @@ declare namespace ReactNative { export var DeviceEventSubscription: DeviceEventSubscriptionStatic; export type DeviceEventSubscription = DeviceEventSubscriptionStatic; export var InteractionManager: InteractionManagerStatic; - export var ScrollView: React.ComponentClass; export var PanResponder: PanResponderStatic; - export var SliderIOS: React.ComponentClass; export var AppStateIOS: AppStateIOSStatic; @@ -1420,6 +2114,20 @@ declare namespace ReactNative { // export function __spread( target: any, ...sources: any[] ): any; + + + export interface GlobalStatic { + + /** + * Accepts a function as its only argument and calls that function before the next repaint. + * It is an essential building block for animations that underlies all of the JavaScript-based animation APIs. + * In general, you shouldn't need to call this yourself - the animation API's will manage frame updates for you. + * @see https://facebook.github.io/react-native/docs/animations.html#requestanimationframe + */ + requestAnimationFrame( fn: () => void ) : void; + + } + } declare module "react-native" { @@ -1438,3 +2146,5 @@ declare module "Dimensions" { var ExportDimensions: Dimensions; export = ExportDimensions; } + +declare var global: ReactNative.GlobalStatic From c4d09a5d1c0f09c27bceaebc7b96bd060234dd8c Mon Sep 17 00:00:00 2001 From: bgrieder Date: Mon, 9 Nov 2015 12:16:08 +0100 Subject: [PATCH 69/86] More Fixes + TouchableHighlight + TouchableOpacity + TouchableWithoutFeedback --- react-native/react-native.d.ts | 131 ++++++++++++++++++++------------- 1 file changed, 78 insertions(+), 53 deletions(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index 7f5832749..92ad7a217 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -369,7 +369,7 @@ declare namespace ReactNative { /** * @see https://facebook.github.io/react-native/docs/textinput.html#props */ - export interface TextInputProperties extends TextInputIOSProperties, TextInputAndroidProperties { + export interface TextInputProperties extends TextInputIOSProperties, TextInputAndroidProperties, React.Props { /** * Can tell TextInput to automatically capitalize certain characters. @@ -438,7 +438,7 @@ declare namespace ReactNative { * Callback that is called when the text input's text changes. * Changed text is passed as an argument to the callback handler. */ - onChangeText?: () => void + onChangeText?: (text: string) => void /** * Callback that is called when text input ends. @@ -496,6 +496,10 @@ declare namespace ReactNative { value?: string } + export interface TextInputStatic extends React.ComponentClass { + + } + export interface AccessibilityTraits { // TODO } @@ -658,7 +662,7 @@ declare namespace ReactNative { testID?: string; } - interface ViewStatic extends React.ComponentClass { + export interface ViewStatic extends React.ComponentClass { } @@ -823,7 +827,7 @@ declare namespace ReactNative { style?: ViewStyle } - interface NavigatorIOSStatic extends React.ComponentClass { + export interface NavigatorIOSStatic extends React.ComponentClass { } @@ -885,7 +889,7 @@ declare namespace ReactNative { value?: number; } - interface SliderIOSStatic extends React.ComponentClass { + export interface SliderIOSStatic extends React.ComponentClass { } @@ -1000,7 +1004,7 @@ declare namespace ReactNative { } /** - * @see + * @see https://facebook.github.io/react-native/docs/listview.html#props */ export interface ListViewProperties extends ScrollViewProperties, React.Props{ @@ -1111,47 +1115,12 @@ declare namespace ReactNative { scrollRenderAheadDistance?: number } - /** - * @see https://facebook.github.io/react-native/docs/touchablehighlight.html#props - */ - export interface TouchableHighlightProperties { - /** - * activeOpacity number - * - * Determines what the opacity of the wrapped view should be when touch is active. - */ - activeOpacity?: number; - - /** - * onHideUnderlay function - * - * Called immediately after the underlay is hidden - */ - - onHideUnderlay?: () => void; - - - /** - * onShowUnderlay function - * - * Called immediately after the underlay is shown - */ - - /** - * @see https://facebook.github.io/react-native/docs/view.html#style - */ - style?: ViewStyle; - - - /** - * underlayColor string - * - * The color of the underlay that will show through when the touch is active. - */ - underlayColor?: string; - + export interface ListViewStatic extends React.ComponentClass { + DataSource: ListViewDataSource; } + + /** * @see https://facebook.github.io/react-native/docs/touchablewithoutfeedback.html */ @@ -1205,10 +1174,65 @@ declare namespace ReactNative { } + export interface TouchableWithoutFeedbackProps extends TouchableWithoutFeedbackProperties, React.Props { + + } + + export interface TouchableWithoutFeedbackStatic extends React.ComponentClass { + + } + + + /** + * @see https://facebook.github.io/react-native/docs/touchablehighlight.html#props + */ + export interface TouchableHighlightProperties extends TouchableWithoutFeedbackProperties, React.Props { + /** + * activeOpacity number + * + * Determines what the opacity of the wrapped view should be when touch is active. + */ + activeOpacity?: number + + /** + * onHideUnderlay function + * + * Called immediately after the underlay is hidden + */ + + onHideUnderlay?: () => void + + + /** + * onShowUnderlay function + * + * Called immediately after the underlay is shown + */ + onShowUnderlay?: () => void + + /** + * @see https://facebook.github.io/react-native/docs/view.html#style + */ + style?: ViewStyle + + + /** + * underlayColor string + * + * The color of the underlay that will show through when the touch is active. + */ + underlayColor?: string + + } + + export interface TouchableHighlightStatic extends React.ComponentClass { + } + + /** * @see https://facebook.github.io/react-native/docs/touchableopacity.html#props */ - export interface TouchableOpacityProperties { + export interface TouchableOpacityProperties extends TouchableWithoutFeedbackProperties, React.Props { /** * activeOpacity number * @@ -1217,6 +1241,10 @@ declare namespace ReactNative { activeOpacity?: number; } + export interface TouchableOpacityStatic extends React.ComponentClass { + } + + export interface LeftToRightGesture { @@ -1382,9 +1410,6 @@ declare namespace ReactNative { getSectionHeaderData( sectionIndex: number ): any } - export interface ListViewStatic extends React.ComponentClass { - DataSource: ListViewDataSource; - } export interface ImageStatic extends React.ComponentClass { uri: string; @@ -1879,16 +1904,16 @@ declare namespace ReactNative { export var StyleSheet: StyleSheetStatic; export var TabBarIOS: TabBarIOSStatic; export type TabBarIOS = TabBarIOSStatic; + export var TextInput: TextInputStatic + export var TouchableHighlight: TouchableHighlightStatic; + export var TouchableOpacity:TouchableOpacityStatic; + export var TouchableWithoutFeedback: TouchableWithoutFeedbackStatic; export var View: ViewStatic; export var Text: React.ComponentClass; - export var TextInput: React.ComponentClass; export var AlertIOS: React.ComponentClass; export var SegmentedControlIOS: React.ComponentClass; export var SwitchIOS: React.ComponentClass; - export var TouchableHighlight: React.ComponentClass; - export var TouchableOpacity: React.ComponentClass; - export var TouchableWithoutFeedback: React.ComponentClass; export var ActivityIndicatorIOS: React.ComponentClass; From 6dedc3d5b555473b065579462865658358db11e3 Mon Sep 17 00:00:00 2001 From: bgrieder Date: Mon, 9 Nov 2015 12:35:14 +0100 Subject: [PATCH 70/86] Fixes to Text Component --- react-native/react-native.d.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index 92ad7a217..15cf5312b 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -5,12 +5,12 @@ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // -// This work is mostly based on the work made by Bernd Paradies: https://github.com/bparadie +// This work is based on an original work made by Bernd Paradies: https://github.com/bparadie // -// These definitions are meant to be used with the compiler target set to ES6 +// These definitions are meant to be used with the TSC compiler target set to ES6 // // WARNING: this work is very much beta: -// -it may be missing react-native definitions +// -it is still missing react-native definitions // -it re-exports the whole of react 0.14 which may not be what react-native actually does // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -248,7 +248,7 @@ declare namespace ReactNative { } // https://facebook.github.io/react-native/docs/text.html#props - export interface TextProperties { + export interface TextProperties extends React.Props { /** * numberOfLines number * @@ -278,6 +278,10 @@ declare namespace ReactNative { style?: TextStyle; } + export interface TextStatic extends React.ComponentClass { + + } + /** * IOS Specific properties for TextInput @@ -1904,13 +1908,13 @@ declare namespace ReactNative { export var StyleSheet: StyleSheetStatic; export var TabBarIOS: TabBarIOSStatic; export type TabBarIOS = TabBarIOSStatic; + export var Text: TextStatic; export var TextInput: TextInputStatic export var TouchableHighlight: TouchableHighlightStatic; export var TouchableOpacity:TouchableOpacityStatic; export var TouchableWithoutFeedback: TouchableWithoutFeedbackStatic; export var View: ViewStatic; - export var Text: React.ComponentClass; export var AlertIOS: React.ComponentClass; export var SegmentedControlIOS: React.ComponentClass; export var SwitchIOS: React.ComponentClass; From 34a93a77af56554417d960e7138fbc59514a889a Mon Sep 17 00:00:00 2001 From: bgrieder Date: Mon, 9 Nov 2015 14:48:00 +0100 Subject: [PATCH 71/86] Improvements to Route and NavigatorIOS --- react-native/react-native.d.ts | 69 +++++++++++++++++++++++++++++++++- 1 file changed, 67 insertions(+), 2 deletions(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index 15cf5312b..5a3481b1d 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -831,7 +831,62 @@ declare namespace ReactNative { style?: ViewStyle } - export interface NavigatorIOSStatic extends React.ComponentClass { + /** + * A navigator is an object of navigation functions that a view can call. + * It is passed as a prop to any component rendered by NavigatorIOS. + * + * Navigator functions are also available on the NavigatorIOS component: + * + * @see https://facebook.github.io/react-native/docs/navigatorios.html#navigator + */ + export interface NavigationIOS { + /** + * Navigate forward to a new route + */ + push: (route: Route) => void + + /** + * Go back one page + */ + pop: () => void + + /** + * Go back N pages at once. When N=1, behavior matches pop() + */ + popN: (n: number) => void + + /** + * Replace the route for the current page and immediately load the view for the new route + */ + replace: (route: Route) => void + + /** + * Replace the route/view for the previous page + */ + replacePrevious: (route: Route) => void + + /** + * Replaces the previous route/view and transitions back to it + */ + replacePreviousAndPop: (route: Route) => void + + /** + * Replaces the top item and popToTop + */ + resetTo: (route: Route) => void + + /** + * Go back to the item for a particular route object + */ + popToRoute(route: Route): void + + /** + * Go back to the top item + */ + popToTop(): void + } + + export interface NavigatorIOSStatic extends NavigationIOS, React.ComponentClass { } @@ -1293,7 +1348,17 @@ declare namespace ReactNative { component?: ComponentClass id?: string; title?: string; - passProps?: Object + passProps?: Object; + + //anything else + [key: string]: any + + //Commonly found properties + backButtonTitle?: string; + rightButtonTitle?: string; + onRightButtonPress?: () => void; + wrapperStyle?: any; //FIXME needs typing + index?: number; } /** From b946c431e959b37fbb13576d0784a4cf805645db Mon Sep 17 00:00:00 2001 From: Lars Date: Mon, 9 Nov 2015 20:52:01 +0100 Subject: [PATCH 72/86] Update c3.d.ts My gulp-typescript task showed many errors because there was a `,` and not a `;` With this file all works fine --- c3/c3.d.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/c3/c3.d.ts b/c3/c3.d.ts index 3c7469b0a..160e0b169 100644 --- a/c3/c3.d.ts +++ b/c3/c3.d.ts @@ -177,7 +177,7 @@ declare module c3 { * Set threshold to show/hide labels. */ threshold?: number - }, + }; /** * Enable or disable expanding pie pieces. */ @@ -198,7 +198,7 @@ declare module c3 { * Set threshold to show/hide labels. */ threshold?: number - }, + }; /** * Enable or disable expanding pie pieces. */ @@ -223,7 +223,7 @@ declare module c3 { * Set formatter for the label on gauge. */ format?: (value: any, ratio: number) => string; - }, + }; /** * Enable or disable expanding gauge. */ @@ -686,7 +686,7 @@ declare module c3 { /** * Set custom position for the tooltip. This option can be used to modify the tooltip position by returning object that has top and left. */ - position?: (data: any, width: number, height: number, element: any) => { top: number, left: number }; + position?: (data: any, width: number, height: number, element: any) => { top: number; left: number }; /** * Set custom HTML for the tooltip. * Specified function receives data, defaultTitleFormat, defaultValueFormat and color of the data point to show. If tooltip.grouped is true, data includes multiple data points. @@ -909,7 +909,7 @@ declare module c3 { * Remove regions. This API removes regions. * @param args This argument should include classes. If classes is given, the regions that have one of the specified classes will be removed. If args is not given, all of regions will be removed. */ - remove(args?: { value?: number | string, class?: string }): void; + remove(args?: { value?: number | string; class?: string }): void; }; data: { @@ -995,7 +995,7 @@ declare module c3 { * Get and set axis min and max value. * @param range If range is given, specified axis' min and max value will be updated. If no argument is given, the current min and max values for each axis will be returned. */ - range(range?: { min?: number | { [key: string]: number }, max?: number | { [key: string]: number } }): { min: number | { [key: string]: number }, max: number | { [key: string]: number } } + range(range?: { min?: number | { [key: string]: number }; max?: number | { [key: string]: number } }): { min: number | { [key: string]: number }; max: number | { [key: string]: number } } }; legend: { @@ -1034,7 +1034,7 @@ declare module c3 { * Resize the chart. If no size is specified it will resize to fit. * @param size This argument should include width and height in pixels. */ - resize(size?: { width?: number, height?: number }): void; + resize(size?: { width?: number; height?: number }): void; /** * Force to redraw. @@ -1062,7 +1062,7 @@ declare module c3 { * Remove x/y grid lines. This API removes x/y grid lines. * @param args This argument should include value or class. If value is given, the x/y grid lines that have specified x/y value will be removed. If class is given, the x/y grid lines that have specified class will be removed. If args is not given, all of x/y grid lines will be removed. */ - remove(args?: { class?: string, value?: number | string }): void; + remove(args?: { class?: string; value?: number | string }): void; } export function generate(config: ChartConfiguration): ChartAPI; From d6c0b99afe073160a05902efb7e526cc87e65e8b Mon Sep 17 00:00:00 2001 From: bgrieder Date: Tue, 10 Nov 2015 08:53:19 +0100 Subject: [PATCH 73/86] Fixes to Navigator. Added NavigatorStatic.NavigationBar --- react-native/react-native.d.ts | 300 +++++++++++++++++++++++---------- 1 file changed, 208 insertions(+), 92 deletions(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index 5a3481b1d..c82a94013 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -442,7 +442,7 @@ declare namespace ReactNative { * Callback that is called when the text input's text changes. * Changed text is passed as an argument to the callback handler. */ - onChangeText?: (text: string) => void + onChangeText?: ( text: string ) => void /** * Callback that is called when text input ends. @@ -728,63 +728,6 @@ declare namespace ReactNative { /// TODO } - /** - * @see https://facebook.github.io/react-native/docs/navigator.html#content - */ - export interface NavigatorProperties extends React.Props { - /** - * Optional function that allows configuration about scene animations and gestures. - * Will be invoked with the route and should return a scene configuration object - * @param route - */ - configureScene?: ( route: Route ) => SceneConfig - /** - * Specify a route to start on. - * A route is an object that the navigator will use to identify each scene to render. - * initialRoute must be a route in the initialRouteStack if both props are provided. - * The initialRoute will default to the last item in the initialRouteStack. - */ - initialRoute?: Route - /** - * Provide a set of routes to initially mount. - * Required if no initialRoute is provided. - * Otherwise, it will default to an array containing only the initialRoute - */ - initialRouteStack?: Route[] - - /** - * Optionally provide a navigation bar that persists across scene transitions - */ - navigationBar?: NavigationBar - - /** - * Optionally provide the navigator object from a parent Navigator - */ - navigator?: Navigator - - /** - * @deprecated Use navigationContext.addListener('willfocus', callback) instead. - */ - onDidFocus?: Function - - /** - * @deprecated Use navigationContext.addListener('willfocus', callback) instead. - */ - onWillFocus?: Function - - /** - * Required function which renders the scene for a given route. - * Will be invoked with the route and the navigator object - * @param route - * @param navigator - */ - renderScene: ( route: Route, navigator: Navigator ) => React.ComponentClass - - /** - * Styles to apply to the container of each scene - */ - sceneStyle: ViewStyle - } export interface NavigatorIOSProperties extends React.Props { @@ -843,7 +786,7 @@ declare namespace ReactNative { /** * Navigate forward to a new route */ - push: (route: Route) => void + push: ( route: Route ) => void /** * Go back one page @@ -853,32 +796,32 @@ declare namespace ReactNative { /** * Go back N pages at once. When N=1, behavior matches pop() */ - popN: (n: number) => void + popN: ( n: number ) => void /** * Replace the route for the current page and immediately load the view for the new route */ - replace: (route: Route) => void + replace: ( route: Route ) => void /** * Replace the route/view for the previous page */ - replacePrevious: (route: Route) => void + replacePrevious: ( route: Route ) => void /** * Replaces the previous route/view and transitions back to it */ - replacePreviousAndPop: (route: Route) => void + replacePreviousAndPop: ( route: Route ) => void /** * Replaces the top item and popToTop */ - resetTo: (route: Route) => void + resetTo: ( route: Route ) => void /** * Go back to the item for a particular route object */ - popToRoute(route: Route): void + popToRoute( route: Route ): void /** * Go back to the top item @@ -887,7 +830,6 @@ declare namespace ReactNative { } export interface NavigatorIOSStatic extends NavigationIOS, React.ComponentClass { - } @@ -979,7 +921,7 @@ declare namespace ReactNative { /** * @see https://facebook.github.io/react-native/docs/image.html */ - export interface ImageProperties extends React.Props { + export interface ImageProperties extends React.Props { /** * onLayout function * @@ -1065,7 +1007,7 @@ declare namespace ReactNative { /** * @see https://facebook.github.io/react-native/docs/listview.html#props */ - export interface ListViewProperties extends ScrollViewProperties, React.Props{ + export interface ListViewProperties extends ScrollViewProperties, React.Props { dataSource?: ListViewDataSource @@ -1085,7 +1027,7 @@ declare namespace ReactNative { * that have changed their visibility, with true indicating visible, and * false indicating the view has moved out of view. */ - onChangeVisibleRows?: (visibleRows: Array<{[sectionId: string]: {[rowID: string]: boolean}}>, changedRows: Array<{[sectionId: string]: {[rowID: string]: boolean}}>) => void + onChangeVisibleRows?: ( visibleRows: Array<{[sectionId: string]: {[rowID: string]: boolean}}>, changedRows: Array<{[sectionId: string]: {[rowID: string]: boolean}}> ) => void /** * Called when all rows have been rendered and the list has been scrolled @@ -1138,14 +1080,14 @@ declare namespace ReactNative { * is exactly what was put into the data source, but it's also possible to * provide custom extractors. */ - renderRow?: (rowData: any, sectionID: string, rowID: string, highlightRow?: boolean) => React.ReactElement + renderRow?: ( rowData: any, sectionID: string, rowID: string, highlightRow?: boolean ) => React.ReactElement /** * A function that returns the scrollable component in which the list rows are rendered. * Defaults to returning a ScrollView with the given props. */ - renderScrollComponent?: (props: ScrollViewProperties) => React.ReactElement + renderScrollComponent?: ( props: ScrollViewProperties ) => React.ReactElement /** * (sectionData, sectionID) => renderable @@ -1156,7 +1098,7 @@ declare namespace ReactNative { * stick to the top until it is pushed off the screen by the next section * header. */ - renderSectionHeader?: (sectionData: any, sectionId: string) => React.ReactElement + renderSectionHeader?: ( sectionData: any, sectionId: string ) => React.ReactElement /** @@ -1165,7 +1107,7 @@ declare namespace ReactNative { * but not the last row if there is a section header below. * Take a sectionID and rowID of the row above and whether its adjacent row is highlighted. */ - renderSeparator?: (sectionID: string, rowID: string, adjacentRowHighlighted?: boolean) => React.ReactElement + renderSeparator?: ( sectionID: string, rowID: string, adjacentRowHighlighted?: boolean ) => React.ReactElement /** * How early to start rendering rows before they come on screen, in @@ -1179,7 +1121,6 @@ declare namespace ReactNative { } - /** * @see https://facebook.github.io/react-native/docs/touchablewithoutfeedback.html */ @@ -1237,7 +1178,7 @@ declare namespace ReactNative { } - export interface TouchableWithoutFeedbackStatic extends React.ComponentClass { + export interface TouchableWithoutFeedbackStatic extends React.ComponentClass { } @@ -1304,7 +1245,6 @@ declare namespace ReactNative { } - export interface LeftToRightGesture { } @@ -1346,54 +1286,202 @@ declare namespace ReactNative { export interface Route { component?: ComponentClass - id?: string; - title?: string; + id?: string + title?: string passProps?: Object; //anything else [key: string]: any //Commonly found properties - backButtonTitle?: string; - rightButtonTitle?: string; - onRightButtonPress?: () => void; - wrapperStyle?: any; //FIXME needs typing - index?: number; + backButtonTitle?: string + content?: string + message?: string; + index?: number + onRightButtonPress?: () => void + rightButtonTitle?: string + sceneConfig?: SceneConfig + wrapperStyle?: any } + /** - * @see + * @see https://facebook.github.io/react-native/docs/navigator.html#content */ - export interface NavigatorBarProperties { + export interface NavigatorProperties extends React.Props { + /** + * Optional function that allows configuration about scene animations and gestures. + * Will be invoked with the route and should return a scene configuration object + * @param route + */ + configureScene?: ( route: Route ) => SceneConfig + /** + * Specify a route to start on. + * A route is an object that the navigator will use to identify each scene to render. + * initialRoute must be a route in the initialRouteStack if both props are provided. + * The initialRoute will default to the last item in the initialRouteStack. + */ + initialRoute?: Route + /** + * Provide a set of routes to initially mount. + * Required if no initialRoute is provided. + * Otherwise, it will default to an array containing only the initialRoute + */ + initialRouteStack?: Route[] - } + /** + * Optionally provide a navigation bar that persists across scene transitions + */ + navigationBar?: React.ReactElement - export interface NavigationBar extends React.ComponentClass { + /** + * Optionally provide the navigator object from a parent Navigator + */ + navigator?: Navigator + + /** + * @deprecated Use navigationContext.addListener('willfocus', callback) instead. + */ + onDidFocus?: Function + + /** + * @deprecated Use navigationContext.addListener('willfocus', callback) instead. + */ + onWillFocus?: Function + + /** + * Required function which renders the scene for a given route. + * Will be invoked with the route and the navigator object + * @param route + * @param navigator + */ + renderScene?: ( route: Route, navigator: Navigator ) => React.ReactElement + + /** + * Styles to apply to the container of each scene + */ + sceneStyle?: ViewStyle + + /** + * //FIXME: not found in doc but found in examples + */ + debugOverlay?: boolean } /** + * Use Navigator to transition between different scenes in your app. + * To accomplish this, provide route objects to the navigator to identify each scene, + * and also a renderScene function that the navigator can use to render the scene for a given route. + * + * To change the animation or gesture properties of the scene, provide a configureScene prop to get the config object for a given route. + * See Navigator.SceneConfigs for default animations and more info on scene config options. * @see https://facebook.github.io/react-native/docs/navigator.html */ export interface NavigatorStatic extends React.ComponentClass { SceneConfigs: SceneConfigs; - NavigationBar: NavigationBar; + NavigationBar: NavigatorStatic.NavigationBar; + getContext( self: any ): NavigatorStatic; + /** + * returns the current list of routes + */ getCurrentRoutes(): Route[]; + + /** + * Jump backward without unmounting the current scen + */ jumpBack(): void; + + /** + * Jump forward to the next scene in the route stack + */ jumpForward(): void; + + /** + * Transition to an existing scene without unmounting + */ jumpTo( route: Route ): void; + + /** + * Navigate forward to a new scene, squashing any scenes that you could jumpForward to + */ push( route: Route ): void; + + /** + * Transition back and unmount the current scene + */ pop(): void; + + /** + * Replace the current scene with a new route + */ replace( route: Route ): void; + + /** + * Replace a scene as specified by an index + */ replaceAtIndex( route: Route, index: number ): void; + + /** + * Replace the previous scene + */ replacePrevious( route: Route ): void; + + /** + * Reset every scene with an array of routes + */ immediatelyResetRouteStack( routes: Route[] ): void; + + /** + * Pop to a particular scene, as specified by its route. All scenes after it will be unmounted + */ popToRoute( route: Route ): void; + + /** + * Pop to the first scene in the stack, unmounting every other scene + */ popToTop(): void; } + module NavigatorStatic { + + + export interface NavState { + routeStack: Route[] + idStack: number[] + presentedIndex: number + } + + export interface NavigationBarStyle { + //TODO @see NavigationBarStyle.ios.js + } + + /** + * @see NavigatorNavigationBar.js + */ + export interface NavigationBarProperties extends React.Props{ + navigator?: Navigator + routeMapper?: ({ + Title: ( route: Route, nav: Navigator, index: number, navState: NavState ) => React.ReactElement; + LeftButton: ( route: Route, nav: Navigator, index: number, navState: NavState )=> React.ReactElement; + RightButton: ( route: Route, nav: Navigator, index: number, navState: NavState )=> React.ReactElement; + }) + navState?: NavState + style?: ViewStyle + } + + export interface NavigationBarStatic extends React.ComponentClass { + Styles?: NavigationBarStyle + + } + + export var NavigationBar: NavigationBarStatic + export type NavigationBar = NavigationBarStatic + } + + export interface StyleSheetStatic extends React.ComponentClass { create( styles: T ): T; } @@ -1961,30 +2049,56 @@ declare namespace ReactNative { // exported singletons: // export var AppRegistry: AppRegistryStatic; export var AsyncStorage: AsyncStorageStatic; + export type AsyncStorage = AsyncStorageStatic; + export var CameraRoll: CameraRollStatic; + export type CameraRoll = CameraRollStatic; + export var Image: ImageStatic; export type Image = ImageStatic; + export var ListView: ListViewStatic; - export type Navigator = NavigatorStatic; + export type ListView = ListViewStatic; + export var Navigator: NavigatorStatic; + export type Navigator = NavigatorStatic; + export var NavigatorIOS: NavigatorIOSStatic; + export type NavigatorIOS = NavigatorIOSStatic; + export var SliderIOS: SliderIOSStatic; + export type SliderIOS = SliderIOSStatic; + export var ScrollView: ScrollViewStatic + export type ScrollView = ScrollViewStatic + export var StyleSheet: StyleSheetStatic; + export type StyleSheet = StyleSheetStatic; + export var TabBarIOS: TabBarIOSStatic; export type TabBarIOS = TabBarIOSStatic; + export var Text: TextStatic; + export type Text = TextStatic; + export var TextInput: TextInputStatic + export type TextInput = TextInputStatic + export var TouchableHighlight: TouchableHighlightStatic; - export var TouchableOpacity:TouchableOpacityStatic; + export type TouchableHighlight = TouchableHighlightStatic; + + export var TouchableOpacity: TouchableOpacityStatic; + export type TouchableOpacity = TouchableOpacityStatic; + export var TouchableWithoutFeedback: TouchableWithoutFeedbackStatic; + export type TouchableWithoutFeedback= TouchableWithoutFeedbackStatic; + export var View: ViewStatic; + export type View = ViewStatic; export var AlertIOS: React.ComponentClass; export var SegmentedControlIOS: React.ComponentClass; export var SwitchIOS: React.ComponentClass; - - export var ActivityIndicatorIOS: React.ComponentClass; export var PixelRatio: PixelRatioStatic; export var DeviceEventEmitter: DeviceEventEmitterStatic; @@ -2242,3 +2356,5 @@ declare module "Dimensions" { } declare var global: ReactNative.GlobalStatic + +declare function require(name: string): any From 99b1f1c4bbf66a40bfba65dd740bc45a8f2be133 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 10 Nov 2015 13:36:30 +0500 Subject: [PATCH 74/86] lodash: signatures of the method _.isEqual have been changed --- lodash/lodash-tests.ts | 50 ++++++++++++++++++++++++++++++------------ lodash/lodash.d.ts | 22 +++++++++++++++++++ 2 files changed, 58 insertions(+), 14 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 876547fd6..e52a8c60c 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -3658,15 +3658,26 @@ var testCloneDeepCustomizerFn: TestCloneDeepCustomizerFn; // _.eq module TestEq { let customizer: (value: any, other: any, indexOrKey?: number|string) => boolean; - let result: boolean; - result = _.eq(any, any); - result = _.eq(any, any, customizer); - result = _.eq(any, any, customizer, any); + { + let result: boolean; - result = _(any).eq(any); - result = _(any).eq(any, customizer); - result = _(any).eq(any, customizer, any) + result = _.eq(any, any); + result = _.eq(any, any, customizer); + result = _.eq(any, any, customizer, any); + + result = _(any).eq(any); + result = _(any).eq(any, customizer); + result = _(any).eq(any, customizer, any); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(any).chain().eq(any); + result = _(any).chain().eq(any, customizer); + result = _(any).chain().eq(any, customizer, any); + } } // _.gt @@ -3766,15 +3777,26 @@ result = _('').isEmpty(); // _.isEqual module TestIsEqual { let customizer: (value: any, other: any, indexOrKey?: number|string) => boolean; - let result: boolean; - result = _.isEqual(any, any); - result = _.isEqual(any, any, customizer); - result = _.isEqual(any, any, customizer, any); + { + let result: boolean; - result = _(any).isEqual(any); - result = _(any).isEqual(any, customizer); - result = _(any).isEqual(any, customizer, any) + result = _.isEqual(any, any); + result = _.isEqual(any, any, customizer); + result = _.isEqual(any, any, customizer, any); + + result = _(any).isEqual(any); + result = _(any).isEqual(any, customizer); + result = _(any).isEqual(any, customizer, any); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(any).chain().isEqual(any); + result = _(any).chain().isEqual(any, customizer); + result = _(any).chain().isEqual(any, customizer, any); + } } // _.isError diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 359cc0fb9..782c0712f 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7796,6 +7796,17 @@ declare module _ { ): boolean; } + interface LoDashExplicitWrapperBase { + /** + * @see _.isEqual + */ + eq( + other: any, + customizer?: IsEqualCustomizer, + thisArg?: any + ): LoDashExplicitWrapper; + } + //_.gt interface LoDashStatic { /** @@ -7978,6 +7989,17 @@ declare module _ { ): boolean; } + interface LoDashExplicitWrapperBase { + /** + * @see _.isEqual + */ + isEqual( + other: any, + customizer?: IsEqualCustomizer, + thisArg?: any + ): LoDashExplicitWrapper; + } + //_.isError interface LoDashStatic { /** From a98de81735a643f9d076f8ab18ab1356da13773a Mon Sep 17 00:00:00 2001 From: Andrew Camilleri Date: Tue, 10 Nov 2015 13:58:14 +0100 Subject: [PATCH 75/86] Renamed ts file to match bower component to make it easier to query --- angular-httpi/{httpi-tests.ts => angular-httpi-tests.ts} | 2 +- angular-httpi/{httpi.d.ts => angular-httpi.d.ts} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename angular-httpi/{httpi-tests.ts => angular-httpi-tests.ts} (97%) rename angular-httpi/{httpi.d.ts => angular-httpi.d.ts} (100%) diff --git a/angular-httpi/httpi-tests.ts b/angular-httpi/angular-httpi-tests.ts similarity index 97% rename from angular-httpi/httpi-tests.ts rename to angular-httpi/angular-httpi-tests.ts index 2d8ffa84f..47ac25228 100644 --- a/angular-httpi/httpi-tests.ts +++ b/angular-httpi/angular-httpi-tests.ts @@ -1,4 +1,4 @@ -/// +/// (function() { 'use strict'; diff --git a/angular-httpi/httpi.d.ts b/angular-httpi/angular-httpi.d.ts similarity index 100% rename from angular-httpi/httpi.d.ts rename to angular-httpi/angular-httpi.d.ts From bf8b0be21ef5fb4c74108329eb6001c060aff7b5 Mon Sep 17 00:00:00 2001 From: Alain Sahli Date: Tue, 10 Nov 2015 15:55:03 +0100 Subject: [PATCH 76/86] add namespace declaration to allow es6 imports --- chai-as-promised/chai-as-promised.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/chai-as-promised/chai-as-promised.d.ts b/chai-as-promised/chai-as-promised.d.ts index 51255b490..d7f1472c7 100644 --- a/chai-as-promised/chai-as-promised.d.ts +++ b/chai-as-promised/chai-as-promised.d.ts @@ -8,6 +8,7 @@ declare module 'chai-as-promised' { function chaiAsPromised(chai: any, utils: any): void; + namespace chaiAsPromised {} export = chaiAsPromised; } From 303486394ff000e036ffce9472b74e4b5be00861 Mon Sep 17 00:00:00 2001 From: bgrieder Date: Tue, 10 Nov 2015 17:26:29 +0100 Subject: [PATCH 77/86] Fixes to NavigationBar and BreadcrumbNavigationBar --- react-native/react-native.d.ts | 62 ++++++++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 10 deletions(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index c82a94013..f3120c004 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -1380,7 +1380,8 @@ declare namespace ReactNative { */ export interface NavigatorStatic extends React.ComponentClass { SceneConfigs: SceneConfigs; - NavigationBar: NavigatorStatic.NavigationBar; + NavigationBar: NavigatorStatic.NavigationBarStatic; + BreadcrumbNavigationBar: NavigatorStatic.BreadcrumbNavigationBarStatic getContext( self: any ): NavigatorStatic; @@ -1443,9 +1444,10 @@ declare namespace ReactNative { * Pop to the first scene in the stack, unmounting every other scene */ popToTop(): void; + } - module NavigatorStatic { + namespace NavigatorStatic { export interface NavState { @@ -1458,27 +1460,61 @@ declare namespace ReactNative { //TODO @see NavigationBarStyle.ios.js } + + export interface NavigationBarRouteMapper { + Title: ( route: Route, nav: Navigator, index: number, navState: NavState ) => React.ReactElement; + LeftButton: ( route: Route, nav: Navigator, index: number, navState: NavState )=> React.ReactElement; + RightButton: ( route: Route, nav: Navigator, index: number, navState: NavState )=> React.ReactElement; + } + /** * @see NavigatorNavigationBar.js */ - export interface NavigationBarProperties extends React.Props{ + export interface NavigationBarProperties extends React.Props{ navigator?: Navigator - routeMapper?: ({ - Title: ( route: Route, nav: Navigator, index: number, navState: NavState ) => React.ReactElement; - LeftButton: ( route: Route, nav: Navigator, index: number, navState: NavState )=> React.ReactElement; - RightButton: ( route: Route, nav: Navigator, index: number, navState: NavState )=> React.ReactElement; - }) + routeMapper?: NavigationBarRouteMapper navState?: NavState style?: ViewStyle } export interface NavigationBarStatic extends React.ComponentClass { - Styles?: NavigationBarStyle + Styles: NavigationBarStyle } - export var NavigationBar: NavigationBarStatic export type NavigationBar = NavigationBarStatic + export var NavigationBar: NavigationBarStatic + + + export interface BreadcrumbNavigationBarStyle { + //TODO &see NavigatorBreadcrumbNavigationBar.js + } + + export interface BreadcrumbNavigationBarRouteMapper { + rightContentForRoute: (route: Route, navigator: Navigator) => React.ReactElement + titleContentForRoute: (route: Route, navigator: Navigator) => React.ReactElement + iconForRoute: (route: Route, navigator: Navigator) => React.ReactElement + //in samples... + separatorForRoute: (route: Route, navigator: Navigator) => React.ReactElement + } + + /** + * @see NavigatorNavigationBar.js + */ + export interface BreadcrumbNavigationBarProperties extends React.Props{ + navigator?: Navigator + routeMapper?: BreadcrumbNavigationBarRouteMapper + navState?: NavState + style?: ViewStyle + } + + export interface BreadcrumbNavigationBarStatic extends React.ComponentClass { + Styles: BreadcrumbNavigationBarStyle + } + + export type BreadcrumbNavigationBar = BreadcrumbNavigationBarStatic + var BreadcrumbNavigationBar: BreadcrumbNavigationBarStatic + } @@ -2063,6 +2099,12 @@ declare namespace ReactNative { export var Navigator: NavigatorStatic; export type Navigator = NavigatorStatic; + //export var NavigationBar: NavigationBarStatic + //export type NavigationBar = NavigationBarStatic + + //export var BreadcrumbNavigationBar: BreadcrumbNavigationBarStatic + //export type BreadcrumbNavigationBar = BreadcrumbNavigationBarStatic + export var NavigatorIOS: NavigatorIOSStatic; export type NavigatorIOS = NavigatorIOSStatic; From 56c85ef59b6ccf8c8c6ff88587557a1c53593909 Mon Sep 17 00:00:00 2001 From: Alex Eagle Date: Tue, 10 Nov 2015 10:37:37 -0800 Subject: [PATCH 78/86] Fix jasmine: message is optional in CustomMatcherResult. See http://jasmine.github.io/2.2/custom_matcher.html#section-Failure_Messages --- jasmine/jasmine-tests.ts | 2 +- jasmine/jasmine.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/jasmine/jasmine-tests.ts b/jasmine/jasmine-tests.ts index 9f57219b8..2e8e55a45 100644 --- a/jasmine/jasmine-tests.ts +++ b/jasmine/jasmine-tests.ts @@ -813,7 +813,7 @@ var customMatchers: jasmine.CustomMatcherFactories = { if (expected === undefined) { expected = ''; } - var result: jasmine.CustomMatcherResult = { pass: false, message: ''}; + var result: jasmine.CustomMatcherResult = { pass: false }; result.pass = util.equals(actual.hyuk, "gawrsh" + expected, customEqualityTesters); diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index 184875fa2..ed8591488 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -129,7 +129,7 @@ declare module jasmine { interface CustomMatcherResult { pass: boolean; - message: string; + message?: string; } interface MatchersUtil { From d790ef9894dacd1a9fab997d6a058aef45cf549e Mon Sep 17 00:00:00 2001 From: Yonezawa-T2 Date: Wed, 11 Nov 2015 13:34:55 +0900 Subject: [PATCH 79/86] Added definitions for Kii Cloud SDK --- kii-cloud-sdk/kii-cloud-sdk-tests.ts | 49 + kii-cloud-sdk/kii-cloud-sdk.d.ts | 7279 ++++++++++++++++++++++++++ 2 files changed, 7328 insertions(+) create mode 100644 kii-cloud-sdk/kii-cloud-sdk-tests.ts create mode 100644 kii-cloud-sdk/kii-cloud-sdk.d.ts diff --git a/kii-cloud-sdk/kii-cloud-sdk-tests.ts b/kii-cloud-sdk/kii-cloud-sdk-tests.ts new file mode 100644 index 000000000..f92642538 --- /dev/null +++ b/kii-cloud-sdk/kii-cloud-sdk-tests.ts @@ -0,0 +1,49 @@ +/// + +function main() { + Kii.initializeWithSite("abc", "def", KiiSite.JP); + + var user = KiiUser.userWithUsername("name", "password"); + + user.register({ + success(user: KiiUser) { + }, + failure(user: KiiUser, message: string) { + } + }); + + user.register({ + success: (user: KiiUser) => 123, + failure: (user: KiiUser, message: string) => 456 + }); + + user.register() + .then(function (user: KiiUser) { + }); + + var bucket = Kii.bucketWithName("foo"); + var clause1 = KiiClause.lessThan("x", 1); + var clause2 = KiiClause.greaterThan("y", 1); + var clause3 = KiiClause.and(clause1, clause2); + var query = KiiQuery.queryWithClause(clause3); + + bucket.executeQuery(query, { + success: function (query: KiiQuery, + results: KiiObject[], + nextQuery: KiiQuery) { + }, + failure: function (bucket: KiiBucket, message: string) { + } + }); + + bucket.executeQuery(query) + .then(function (params: [KiiQuery, KiiObject[], KiiQuery]) { + var [query, results, nextQuery] = params; + }); + + var object = bucket.createObject(); + + object.set("foo", 1); + + object.save(); +} diff --git a/kii-cloud-sdk/kii-cloud-sdk.d.ts b/kii-cloud-sdk/kii-cloud-sdk.d.ts new file mode 100644 index 000000000..57c8f50b1 --- /dev/null +++ b/kii-cloud-sdk/kii-cloud-sdk.d.ts @@ -0,0 +1,7279 @@ +// Type definitions for Kii Cloud SDK v2.3.0 +// Project: http://en.kii.com/ +// Definitions by: Kii Consortium +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module KiiCloud { + enum KiiACLAction { + KiiACLBucketActionCreateObjects, + KiiACLBucketActionQueryObjects, + KiiACLBucketActionDropBucket, + KiiACLObjectActionRead, + KiiACLObjectActionWrite, + } + + export enum KiiSite { + US, + JP, + CN, + SG, + CN3 + } + + export enum KiiAnalyticsSite { + US, + JP, + CN, + SG, + CN3 + } + + enum KiiSocialNetworkName { + FACEBOOK = 1, + TWITTER = 2, + QQ = 3, + GOOGLEPLUS = 4, + RENREN = 5 + } + + type KiiSocialConnectOptions = { + access_token: string, + openID?: string + } | { + oauth_token: string, + oauth_token_secret: string + } + + interface KiiSocialAccountInfo { + createdAt: number; + provider: KiiSocialNetworkName; + socialAccountId: string; + } + + interface KiiThingFields { + /** + * thing identifier given by thing vendor. + */ + _vendorThingID: string; + + /** + * thing password given by thing vendor. + */ + _password: string; + + /** + * thing type given by thing vendor. + */ + _thingType?: string; + + /** + * vendor identifier given by thing vendor. + */ + _vendor?: string; + + /** + * firmware version given by thing vendor. + */ + _firmwareVersion?: string; + + /** + * lot identifier given by thing vendor. + */ + _lot?: string; + + /** + * arbitrary string field. + */ + _stringField1?: string; + + /** + * arbitrary string field. + */ + _stringField2?: string; + + /** + * arbitrary string field. + */ + _stringField3?: string; + + /** + * arbitrary string field. + */ + _stringField4?: string; + + /** + * arbitrary string field. + */ + _stringField5?: string; + + /** + * arbitrary number field. + */ + _numberField1?: number; + + /** + * arbitrary number field. + */ + _numberField2?: number; + + /** + * arbitrary number field. + */ + _numberField3?: number; + + /** + * arbitrary number field. + */ + _numberField4?: number; + + /** + * arbitrary number field. + */ + _numberField5?: number; + + /** + * custom fields. + */ + [name: string]: any; + } + + type KiiACLSubject = + KiiGroup | + KiiUser | + KiiAnyAuthenticatedUser | + KiiAnonymousUser | + KiiThing; + + interface APNSAlert { + title: string; + body: string; + "title-loc-key": string; + "title-loc-args": string[]; + "action-loc-key": string; + "loc-key": string; + "loc-args": string[]; + "launch-image": string; + } + + interface identityData { + emailAddress?: string; + phoneNumber?: string; + username?: string; + } + + /** + * The main SDK class + */ + export class Kii { + /** + * Kii SDK Build Number + * + * @return current build number of the SDK + */ + static getBuildNumber(): string; + + /** + * Kii SDK Version Number + * + * @return current version number of the SDK + */ + static getSDKVersion(): string; + + /** + * Retrieve the current app ID + * + * @return The current app ID + */ + static getAppID(): string; + + /** + * Retrieve the current app key + * + * @return The current app key + */ + static getAppKey(): string; + + /** + * Set the access token lifetime in seconds. + * + * If you don't call this method or call it with 0, token won't be expired. + * Call this method if you like the access token to be expired + * after a certain period. Once called, token retrieved + * by each future authentication will have the specified lifetime. + * Note that, it will not update the lifetime of token received prior + * calling this method. Once expired, you have to login again to renew the token. + * + * @param expiresIn The life time of access token in seconds. + * + * @throws If specified expiresIn is negative. + * @throws If Kii has not been initialized + * + * @example + * Kii.setAccessTokenExpiration(3600); + */ + static setAccessTokenExpiration(expiresIn: number): void; + + /** + * Returns access token lifetime in seconds. + * + * If access token lifetime has not set explicitly by {@link Kii.setAccessTokenExpiration(expiresIn)}, returns 0. + * + * @return access token lifetime in seconds. + * + * @throws If Kii has not been initialized + */ + static getAccessTokenExpiration(): number; + + /** + * Initialize the Kii SDK with a specific URL + * + * Should be the first Kii SDK action your application makes. + * + * @param appID The application ID found in your Kii developer console + * @param appKey The application key found in your Kii developer console + * @param site Can be one of the constants KiiSite.US, KiiSite.JP, KiiSite.CN or KiiSite.SG depending on your location. + * @param analyticsOption An object used for initializing KiiAnalytics, If not provided or invalid object provided, KiiAnalytics won't be initialized. If provided, it can be empty object or with analyticsOption.deviceId.
If provided, but deviceId is not provided, SDK generates a new deviceId and use it when upload events. It can be retrieved by {@link KiiAnalytics.getDeviceId()}. It is recommended to retrieve the deviceId and store it to identify the device properly. + * + * @example + * // Disable KiiAnalytics + * Kii.initializeWithSite("my-app-id", "my-app-key", KiiSite.JP); + * + * // Enable KiiAnalytics with deviceId + * var analyticsOption = { deviceId: "my-device-id" }; + * Kii.initializeWithSite("my-app-id", "my-app-key", KiiSite.JP, analyticsOption); + * + * // Enable KiiAnalytics without deviceId + * Kii.initializeWithSite("my-app-id", "my-app-key", KiiSite.JP, {}); + */ + static initializeWithSite(appID: string, appKey: string, site: KiiSite, analyticsOption?: any): void; + + /** + * Initialize the Kii SDK + * + * Should be the first Kii SDK action your application makes. + * Meanwhile, Kii Analytics is initialized. + * + * @param appID The application ID found in your Kii developer console + * @param appKey The application key found in your Kii developer console + * @param analyticsOption An object used for initializing KiiAnalytics, If not provided or invalid object provided, KiiAnalytics won't be initialized. If provided, it can be empty object or with analyticsOption.deviceId.
If provided, but deviceId is not provided, SDK generates a new deviceId and use it when upload events. It can be retrieved by {@link KiiAnalytics.getDeviceId()}. It is recommended to retrieve the deviceId and store it to identify the device properly. + * + * @example + * // Disable KiiAnalytics + * Kii.initialize("my-app-id", "my-app-key"); + * + * // Enable KiiAnalytics with deviceId + * var analyticsOption = { deviceId: "my-device-id" }; + * Kii.initialize("my-app-id", "my-app-key", analyticsOption); + * + * // Enable KiiAnalytics without deviceId + * Kii.initialize("my-app-id", "my-app-key", {}); + */ + static initialize(appID: string, appKey: string, analyticsOption?: any): void; + + /** + * Creates a reference to a bucket for this app + * + *

The bucket will be created/accessed within this app's scope + * + * @param bucketName The name of the bucket the app should create/access + * + * @return A working KiiBucket object + * + * @example + * var bucket = Kii.bucketWithName("myBucket"); + */ + static bucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to a encrypted bucket for this app + * + *

The bucket will be created/accessed within this app's scope + * + * @param bucketName The name of the bucket the app should create/access + * + * @return A working KiiEncryptedBucket object + * + * @example + * var bucket = Kii.encryptedBucketWithName("myBucket"); + */ + static encryptedBucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to a group with the given name + * + * @param groupName An application-specific group name + * + * @return A new KiiGroup reference + * + * @example + * var group = new Kii.groupWithName("myGroup"); + */ + static groupWithName(groupName: string): KiiGroup; + + /** + * Creates a reference to a group with the given name and a list of default members + * + * @param groupName An application-specific group name + * @param members An array of KiiUser objects to add to the group + * + * @return A new KiiGroup reference + * + * @example + * var group = new KiiGroup.groupWithName("myGroup", members); + */ + static groupWithNameAndMembers(groupName: string, members: KiiUser[]): KiiGroup; + + /** + * Authenticate as app admin. + *

+ * This api call must not placed on code which can be accessed by browser. + * This api is intended to be used by server side code like Node.js. + * If you use this api in code accessible by browser, your application id and application secret could be stolen. + * Attacker will be act as appadmin and all the data in your application will be suffered. + * + * + * @param clientId assigned to your application. + * @param clientSecret assigned to your application. + * @param callbacks The callback methods called when authentication succeeded/failed. + * + * @return return promise object. + *

    + *
  • fulfill callback function: function(adminContext). adminContext is a KiiAppAdminContext instance.
  • + *
  • reject callback function: function(error). error is an Error instance. + *
      + *
    • error.message
    • + *
    + *
  • + *
+ * + * @example + * // example to use callbacks directly + * Kii.authenticateAsAppAdmin("your client id", "your client secret", { + * success: function(adminContext) { + * // adminContext : KiiAppAdminContext instance + * // Operate entities with adminContext. + * }, + * failure: function(error, statusCode) { + * // Authentication failed. + * } + * ); + * + * // example to use Promise + * Kii.authenticateAsAppAdmin("your client id", "your client secret").then( + * function(adminContext) { // fulfill callback function + * // adminContext : KiiAppAdminContext instance + * // Operate entities with adminContext. + * + * }, + * function(error) { // reject callback function + * // Authentication failed. + * var errorString = error.message; + * } + * ); + */ + static authenticateAsAppAdmin(clientId: string, clientSecret: string, callbacks?: { success(adminContext: KiiAppAdminContext): any; failure(error: string, statusCode: number): any; }): Promise; + + /** + * Instantiate KiiServerCodeEntry with specified entry name. + * + * @param entryName Name of the entry. + * + * @return KiiServerCodeEntry instance. + * + * @throws Thrown when entryName is invalid in the following cases: + *
  • not type of string
  • + *
  • empty string
  • + *
  • invalid string. Valid entryName pattern is "[a-zA-Z][_a-zA-Z0-9]*$".
  • + * + * @example + * var entry = Kii.serverCodeEntry("main"); + */ + static serverCodeEntry(entryName: string): KiiServerCodeEntry; + + /** + * Instantiate serverCodeEntryWithVersion with specified entry name and version. + * + * @param entryName Name of the entry. + * @param version Version of the entry. + * + * @return KiiServerCodeEntry instance. + * + * @throws Thrown in the following cases:
    + *
  • entryName or version is not type of string
  • + *
  • entryName or version is empty string
  • + *
  • entryName is invalid string. Valid entryName pattern is "[a-zA-Z][_a-zA-Z0-9]*$".
  • + * + * @example + * var entry = Kii.serverCodeEntryWithVersion("main", "gulsdf6ful8jvf8uq6fe7vjy6"); + */ + static serverCodeEntryWithVersion(entryName: string, version: string): KiiServerCodeEntry; + + /** + * Instantiate topic belongs to application. + * + * @param topicName name of the topic. Must be a not empty string. + * + * @return topic instance. + */ + static topicWithName(topicName: string): KiiTopic; + + /** + * Gets a list of topics in app scope + * + * @param callbacks An object with callback methods defined + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success or fullfill callback of promise. If empty string or no string object is provided, this API regards no paginationKey specified. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is array of KiiTopic instances.
      • + *
      • params[1] is string of nextPaginationKey.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * Kii.listTopics({ + * success: function(topicList, nextPaginationKey) { + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * Kii.listTopics({ + * success: function(topicList, nextPaginationKey) {...}, + * failure: function(anErrorString) {...} + * }, nextPaginationKey); + * } + * }, + * failure: function(anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use promise + * Kii.listTopics().then( + * function(params) { + * var topicList = params[0]; + * var nextPaginationKey = params[1]; + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * Kii.listTopics(null, nextPaginationKey).then( + * function(params) {...}, + * function(error) {...} + * ); + * } + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + static listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + } + + /** + * Represents a KiiACL object + */ + export class KiiACL { + /** + * Get the list of active ACLs associated with this object from the server + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is the KiiACL instance which this method was called on.
      • + *
      • params[1] is array of KiiACLEntry instances.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiACL instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var acl = . . .; // a KiiACL object + * acl.listACLEntries({ + * success: function(theACL, theEntries) { + * // do something + * }, + * + * failure: function(theACL, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var acl = . . .; // a KiiACL object + * acl.listACLEntries().then( + * function(params) { // fulfill callback function + * var theACL = params[0]; + * var theEntries = params[1]; + * // do something + * }, + * function(error) { // reject callback function + * var theACL = error.target; + * var anErrorString = error.message; + * // do something with the error response + * }); + */ + listACLEntries(callbacks?: { success(theACL: KiiACL, theEntries: KiiACLEntry[]): any; failure(theACL: KiiACL, anErrorString: string): any; }): Promise<[KiiACL, KiiACLEntry[]]>; + + /** + * Add a KiiACLEntry to the local object, if not already present. This does not explicitly grant any permissions, which should be done through the KiiACLEntry itself. This method simply adds the entry to the local ACL object so it can be saved to the server. + * + * @param entry The KiiACLEntry to add + * + * @throws If specified entry is not an instance of KiiACLEntry. + * + * @example + * var aclEntry = . . .; // a KiiACLEntry object + * var acl = . . .; // a KiiACL object + * acl.putACLEntry(aclEntry); + */ + putACLEntry(entry: KiiACLEntry): void; + + /** + * Remove a KiiACLEntry to the local object. This does not explicitly revoke any permissions, which should be done through the KiiACLEntry itself. This method simply removes the entry from the local ACL object and will not be saved to the server. + * + * @param entry The KiiACLEntry to remove + * + * @throws If specified entry is not an instance of KiiACLEntry. + * + * @example + * var aclEntry = . . .; // a KiiACLEntry object + * var acl = . . .; // a KiiACL object + * acl.removeACLEntry(aclEntry); + */ + removeACLEntry(entry: KiiACLEntry): void; + + /** + * Save the list of ACLEntry objects associated with this ACL object to the server + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theSavedACL). theSavedACL is KiiACL instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiACL instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var acl = . . .; // a KiiACL object + * acl.save({ + * success: function(theSavedACL) { + * // do something with the saved acl + * }, + * + * failure: function(theACL, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var acl = . . .; // a KiiACL object + * acl.save().then( + * function(theSavedACL) { // fulfill callback function + * // do something with the saved acl + * }, + * function(error) { // reject callback function + * var theACL = error.target; + * var anErrorString = error.message; + * // do something with the error response + * }); + */ + save(callbacks?: { success(theSavedACL: KiiACL): any; failure(theACL: KiiACL, anErrorString: string): any; }): Promise; + } + + /** + * Represents a KiiACLEntry object + */ + export class KiiACLEntry { + /** + * The action that is being permitted/restricted. Possible values: + *

    + * KiiACLAction.KiiACLBucketActionCreateObjects,
    + * KiiACLAction.KiiACLBucketActionQueryObjects,
    + * KiiACLAction.KiiACLBucketActionDropBucket,
    + * KiiACLAction.KiiACLObjectActionRead,
    + * KiiACLAction.KiiACLObjectActionWrite,
    + * KiiACLAction.KiiACLSubscribeToTopic,
    + * KiiACLAction.KiiACLSendMessageToTopic + * + * @param value The action being permitted/restricted + * + * @throws If the value is not one of the permitted values + */ + setAction(value: KiiACLAction): void; + + /** + * Get the action that is being permitted/restricted in this entry + * + * @return + */ + getAction(): KiiACLAction; + + /** + * Set the subject to which the action/grant is being applied + * + * @param subject instance. + * + * @throws If the value is not one of the permitted values + */ + setSubject(subject: KiiACLSubject): void; + + /** + * Get the subject that is being permitted/restricted in this entry + * + * @return + */ + getSubject(): T; + + /** + * Set whether or not the action is being permitted to the subject + * + * @param value true if the action is permitted, false otherwise + * + * @throws If the value is not a boolean type + */ + setGrant(value: boolean): void; + + /** + * Get whether or not the action is being permitted to the subject + * + * @return + */ + getGrant(): boolean; + + /** + * Create a KiiACLEntry object with a subject and action + * + * The entry will not be applied on the server until the KiiACL object is + * explicitly saved. This method simply returns a working KiiACLEntry with + * a specified subject and action. + * + * @param Subject to which the action/grant is being applied + * @param action One of the specified KiiACLAction values the + * permissions is being applied to + * + * @return A KiiACLEntry object with the specified attributes + * + * @throws If specified subject is invalid. + * @throws If the specified action is invalid. + */ + static entryWithSubject(Subject: KiiACLSubject, action: KiiACLAction): KiiACLEntry; + } + + /** + * The main SDK class + */ + export class KiiAnalytics { + /** + * Retrieve the current app ID + * + * @return The current app ID + */ + static getAppID(): string; + + /** + * Retrieve the current app key + * + * @return The current app key + */ + static getAppKey(): string; + + /** + * Get the deviceId. If deviceId has not specified while initialization, it returns SDK generated deviceId.It is recommended to retrieve the deviceId and store it to identify the device properly. + * + * @return deviceId. + */ + static getDeviceId(): string; + + /** + * Is the SDK printing logs to the console? + * + * @return True if printing logs, false otherwise + */ + static isLogging(): boolean; + + /** + * Set the logging status of the SDK + * + * Helpful for development - we strongly advice you turn off logging for any production code. + * + * @param True if logs should be printed, false otherwise + * + * @example + * KiiAnalytics.setLogging(true); + */ + static setLogging(True: boolean): void; + + /** + * + * + * @deprecated Use {@link Kii.initializeWithSite} instead. Initialize the Kii SDK with a specific URL + * + * Should be the first Kii SDK action your application makes + * + * @param appID The application ID found in your Kii developer console + * @param appKey The application key found in your Kii developer console + * @param site Can be one of the constants KiiAnalyticsSite.US, KiiAnalyticsSite.JP, KiiAnalyticsSite.CN, KiiAnalyticsSite.CN3 or KiiAnalyticsSite.SG depending on your location. + * @param deviceid If deviceId is not provided, SDK generates a new deviceId and use it when upload events.deviceId can be retrieved by {@link KiiAnalytics.getDeviceId()}.It is recommended to retrieve the deviceId and store it to identify the device properly. + * + * @example + * // initialize without deviceId + * Kii.initializeWithSite("my-app-id", "my-app-key", KiiAnalyticsSite.JP); + * // initialize with deviceId + * Kii.initializeWithSite("my-app-id", "my-app-key", KiiAnalyticsSite.JP, "my-device-id"); + */ + static initializeWithSite(appID: string, appKey: string, site: KiiAnalyticsSite, deviceid: string): void; + + /** + * + * + * @deprecated Use {@link Kii.initialize} instead. Initialize the KiiAnalytics SDK + * + * Should be the first KiiAnalytics SDK action your application makes + * + * @param appID The application ID found in your Kii developer console + * @param appKey The application key found in your Kii developer console + * @param deviceid If deviceId is not provided, SDK generates a new deviceId and use it when upload events. deviceId can be retrieved by {@link KiiAnalytics.getDeviceId()}.It is recommended to retrieve the deviceId and store it to identify the device properly. + * + * @example + * // initialize without deviceId + * Kii.initializeWithSite("my-app-id", "my-app-key", KiiAnalyticsSite.JP); + * // initialize with deviceId + * Kii.initializeWithSite("my-app-id", "my-app-key", KiiAnalyticsSite.JP, "my-device-id"); + */ + static initialize(appID: string, appKey: string, deviceid: string): void; + + /** + * Utilize the KiiAnalytics logger to track SDK-specific actions + * + * Helpful for development - we strongly advice you turn off logging for any production code. + * + * @param message The message to print to console.log in your browser + * + * @example + * KiiAnalytics.logger("My message"); + */ + static logger(message: string): void; + + /** + * Log a single event to be uploaded to KiiAnalytics + * + * Use this method if you'd like to track an event by name only. If you'd like to track other attributes/dimensions, please use KiiAnalytics.trackEventWithExtras(eventName, parameters) + * + * @param eventName A string representing the event name for later tracking + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(). No parameters.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + */ + static trackEvent(eventName: string): Promise; + + /** + * Log a single event to be uploaded to KiiAnalytics + * + * Use this method if you'd like to track an event by name and add extra information to the event. + * + * @param eventName A string representing the event name for later tracking + * @param extras A dictionary of JSON-encodable key/value pairs to be attached to the event. + * Key must follow the pattern "^[a-zA-Z][a-zA-Z0-9_]{0,63}$".Supported value type is string, number, boolean and array. + * Empty string or empty array will be considered as invalid.Type of array elements must be string, number or boolean. + * If any key/value pair is invalid, it will be ignored and not sent to the KiiCloud. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(). No parameters.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + */ + static trackEventWithExtras(eventName: string, extras: any): Promise; + + /** + * Log a single event to be uploaded to KiiAnalytics + * + * Use this method if you'd like to track an event asynchronously by name and add extra information to the event. + * + * @param eventName A string representing the event name for later tracking + * @param extras A dictionary of JSON-encodable key/value pairs to be attached to the event. + * Key must follow the pattern "^[a-zA-Z][a-zA-Z0-9_]{0,63}$".Supported value type is string, number, boolean and array. + * Empty string or empty array will be considered as invalid.Type of array elements must be string, number or boolean. + * If any key/value pair is invalid, it will be ignored and not sent to the KiiCloud. + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(). No parameters.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + */ + static trackEventWithExtrasAndCallbacks(eventName: string, extras: any, callbacks?: { success(): any; failure(error: Error): any; }): Promise; + + /** + * + * + * @deprecated Set a custom API endpoint URL + * + * @param url A string containing the desired endpoint + */ + static setBaseURL(url: string): void; + + /** + * + * + * @deprecated Use {@link Kii.getSDKVersion} instead. Kii Analytics SDK Version Number + * + * @return current version number of the SDK + */ + static getSDKVersion(): string; + } + + /** + * Represent an anonymous user for setting the ACL of an object. This will include anyone using the application but have not signed up or authenticated as registered user. + * + * When retrieving ACL from an object, test for this class to determine the subject type. + */ + export class KiiAnonymousUser { + /** + * Returns the ID of Anonymous user. + */ + getID(): string; + } + + /** + * Represent any authenticated user for setting the ACL of an object. This will include anyone using the application who has registered and authenticated in the current session. + * + * When retrieving ACL from an object, test for this class to determine the subject type. Example: + */ + export class KiiAnyAuthenticatedUser { + /** + * Returns the ID of AuthenticatedUser user. + */ + getID(): string; + } + + /** + * represents the app admin context + *

    + * This class must not referred from code accessible from browser. + * This class is intended to be used by server side code like Node.js. + * If you use this class in code accessible by browser, your application client id and client secret could be stolen. + * Attacker will be act as application admin and all the data in your application will be suffered. + * + * Application administrator context. Entities obtained from this class will be manipulated by application admin. + */ + export class KiiAppAdminContext { + /** + * Creates a reference to a bucket operated by app admin. + *

    The bucket will be created/accessed within this app's scope + * + * @param bucketName The name of the bucket the app should create/access + * + * @return A working KiiBucket object + * + * @example + * Kii.authenticateAsAppAdmin("client-id", "client-secret", { + * success: function(adminContext) { + * var bucket = adminContext.bucketWithName("myBucket"); + * // KiiBucket operation by app admin is available now. + * }, + * failure: function(errorString, errorCode) { + * // auth failed. + * } + * }); + */ + bucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to a encrypted bucket operated by app admin. + *

    The bucket will be created/accessed within this app's scope + * + * @param bucketName The name of the bucket the app should create/access + * + * @return A working KiiBucket object + * + * @example + * Kii.authenticateAsAppAdmin("client-id", "client-secret", { + * success: function(adminContext) { + * var bucket = adminContext.encryptedBucketWithName("myBucket"); + * // KiiBucket operation by app admin is available now. + * }, + * failure: function(errorString, errorCode) { + * // auth failed. + * } + * }); + */ + encryptedBucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to a group operated by app admin. + *

    + * Note: + * Returned instance from this API can not operate existing KiiGroup.
    + * If you want to operate existing KiiGroup, please use {@link KiiAppAdminContext#groupWithURI} or {@link KiiAppAdminContext#groupWithID}. + * + * @param group name. + * + * @return A working KiiGroup object + * + * @example + * Kii.authenticateAsAppAdmin("client-id", "client-secret", { + * success: function(adminContext) { + * var group = adminContext.groupWithName("newGroup"); + * // KiiGroup operation by app admin is available now. + * }, + * failure: function(errorString, errorCode) { + * // auth failed. + * } + * }); + */ + groupWithName(group: string): KiiGroup; + + /** + * Creates a reference to a user operated by app admin. + * + * @param user id. + * + * @return A working KiiUser object + * + * @example + * Kii.authenticateAsAppAdmin("client-id", "client-secret", { + * success: function(adminContext) { + * var user = adminContext.userWithID("userid"); + * // KiiUser operation by app admin is available now. + * }, + * failure: function(errorString, errorCode) { + * // auth failed. + * } + * }); + */ + userWithID(user: string): KiiUser; + + /** + * Creates a reference to an object operated by app admin using object`s URI. + * + * @param object URI. + * + * @return A working KiiObject instance + * + * @throws If the URI is null, empty or does not have correct format. + */ + objectWithURI(object: string): KiiObject; + + /** + * Creates a reference to a group operated by app admin using group's ID. + *

    + * Note: + * Returned instance from this API can operate existing KiiGroup.
    + * If you want to create a new KiiGroup, please use {@link KiiAppAdminContext#groupWithName}. + * + * @param group ID. + * + * @return A working KiiGroup object + * + * @throws Thrown if passed groupID is null or empty. + * + * @example + * Kii.authenticateAsAppAdmin("client-id", "client-secret", { + * success: function(adminContext) { + * var groupID = "0123456789abcdefghijklmno"; + * var group = adminContext.groupWithID(groupID); + * // KiiGroup operation by app admin is available now. + * }, + * failure: function(errorString, errorCode) { + * // auth failed. + * } + * }); + */ + groupWithID(group: string): KiiGroup; + + /** + * Creates a reference to a group operated by app admin using group's URI. + *

    + * Note: + * Returned instance from this API can operate existing KiiGroup.
    + * If you want to create a new KiiGroup, please use {@link KiiAppAdminContext#groupWithName}. + * + * @param group URI. + * + * @return A working KiiGroup object + * + * @throws Thrown if the URI is null, empty or does not have correct format. + * + * @example + * Kii.authenticateAsAppAdmin("client-id", "client-secret", { + * success: function(adminContext) { + * var groupUri = ...; // KiiGroup's URI + * var group = adminContext.groupWithURI(groupUri); + * // KiiGroup operation by app admin is available now. + * }, + * failure: function(errorString, errorCode) { + * // auth failed. + * } + * }); + */ + groupWithURI(group: string): KiiGroup; + + /** + * Find registered KiiUser with the email.
    + * If there are no user registers with the specified email or if there are but not verified email yet, + * callbacks.failure or reject callback of promise will be called.
    + * If the email is null or empty, callbacks.failure or reject callback of promise will be callded. + *

    + * Note: + *
      + *
    • If "Expose Full User Data To Others" is enabled in the application console, the response will contain full of the user data.
    • + *
    • Otherwise, the response will only contain "userID", "loginName" and "displayName" field values if exist.
    • + *
    + * + * @param email The email to find KiiUser who owns it.
    + * Don't add prefix of "EMAIL:" described in REST API documentation. SDK will take care of it. + * @param callbacks An object with callback methods defined. + * This argument is mandatory and can't be omitted. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is a KiiAppAdminContext instance which this method was called on.
      • + *
      • params[1] is a found KiiUser instance.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiAppAdminContext instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * Kii.authenticateAsAppAdmin("client-id", "client-secret", { + * success: function(adminContext) { + * adminContext.findUserByEmail("user_to_find@example.com", { + * success: function(adminContext, theMatchedUser) { + * // Do something with the found user + * }, + * failure: function(adminContext, anErrorString) { + * // Do something with the error response + * } + * }); + * }, + * failure: function(errorString, errorCode) { + * // Auth failed. + * } + * }); + * + * // example to use Promise + * Kii.authenticateAsAppAdmin("client-id", "client-secret").then( + * function(adminContext) { + * adminContext.findUserByEmail("user_to_find@example.com").then( + * function(params) { // fullfill callback function + * var adminContext = params[0]; + * var theMatchedUser = params[1]; + * // Do something with the found user + * }, + * function(error) { // reject callback function + * var adminContext = error.target; + * var anErrorString = error.message; + * // Do something with the error response + * } + * ); + * }, + * function(error) { + * // Auth failed. + * } + * ); + */ + findUserByEmail(email: string, callbacks?: { success(adminContext: KiiAppAdminContext, theMatchedUser: KiiUser): any; failure(adminContext: KiiAppAdminContext, anErrorString: string): any; }): Promise<[KiiAppAdminContext, KiiUser]>; + + /** + * Find registered KiiUser with the phone.
    + * If there are no user registers with the specified phone or if there are but not verified phone yet, + * callbacks.failure or reject callback of promise will be called.
    + * If the phone is null or empty, callbacks.failure or reject callback of promise will be called. + *

    + * Note: + *
      + *
    • If "Expose Full User Data To Others" is enabled in the application console, the response will contain full of the user data.
    • + *
    • Otherwise, the response will only contain "userID", "loginName" and "displayName" field values if exist.
    • + *
    + * + * @param phone The phone number to find KiiUser who owns it.
    + * Don't add prefix of "PHONE:" described in REST API documentation. SDK will take care of it. + * @param callbacks An object with callback methods defined. + * This argument is mandatory and can't be omitted. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is a KiiAppAdminContext instance which this method was called on.
      • + *
      • params[1] is a found KiiUser instance.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiAppAdminContext instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * Kii.authenticateAsAppAdmin("client-id", "client-secret", { + * success: function(adminContext) { + * adminContext.findUserByPhone("phone_number_to_find", { + * success: function(adminContext, theMatchedUser) { + * // Do something with the found user + * }, + * failure: function(adminContext, anErrorString) { + * // Do something with the error response + * } + * }); + * }, + * failure: function(errorString, errorCode) { + * // Auth failed. + * } + * }); + * + * // example to use Promise + * Kii.authenticateAsAppAdmin("client-id", "client-secret").then( + * function(adminContext) { + * adminContext.findUserByPhone("phone_number_to_find").then( + * function(params) { // fullfill callback function + * var adminContext = params[0]; + * var theMatchedUser = params[1]; + * // Do something with the found user + * }, + * function(error) { // reject callback function + * var adminContext = error.target; + * var anErrorString = error.message; + * // Do something with the error response + * } + * ); + * }, + * function(error) { + * // Auth failed. + * } + * ); + */ + findUserByPhone(phone: string, callbacks?: { success(adminContext: KiiAppAdminContext, theMatchedUser: KiiUser): any; failure(adminContext: KiiAppAdminContext, anErrorString: string): any; }): Promise<[KiiAppAdminContext, KiiUser]>; + + /** + * Find registered KiiUser with the user name.
    + * If there are no user registers with the specified user name, callbacks.failure or reject callback of promise will be called.
    + * If the user name is null or empty, callbacks.failure or reject callback of promise will be called. + *

    + * Note: + *
      + *
    • If "Expose Full User Data To Others" is enabled in the application console, the response will contain full of the user data.
    • + *
    • Otherwise, the response will only contain "userID", "loginName" and "displayName" field values if exist.
    • + *
    + * + * @param username The user name to find KiiUser who owns it.
    + * Don't add prefix of "LOGIN_NAME:" described in REST API documentation. SDK will take care of it. + * @param callbacks An object with callback methods defined. + * This argument is mandatory and can't be omitted. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is a KiiAppAdminContext instance which this method was called on.
      • + *
      • params[1] is a found KiiUser instance.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiAppAdminContext instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * Kii.authenticateAsAppAdmin("client-id", "client-secret", { + * success: function(adminContext) { + * adminContext.findUserByUsername("user_name_to_find", { + * success: function(adminContext, theMatchedUser) { + * // Do something with the found user + * }, + * failure: function(adminContext, anErrorString) { + * // Do something with the error response + * } + * }); + * }, + * failure: function(errorString, errorCode) { + * // Auth failed. + * } + * }); + * // example to use Promise + * Kii.authenticateAsAppAdmin("client-id", "client-secret").then( + * function(adminContext) { + * adminContext.findUserByUsername("user_name_to_find").then( + * function(params) { // fullfill callback function + * var adminContext = params[0]; + * var theMatchedUser = params[1]; + * // Do something with the found user + * }, + * function(error) { // reject callback function + * var adminContext = error.target; + * var anErrorString = error.message; + * // Do something with the error response + * } + * ); + * }, + * function(error) { + * // Auth failed. + * } + * ); + */ + findUserByUsername(username: string, callbacks?: { success(adminContext: KiiAppAdminContext, theMatchedUser: KiiUser): any; failure(adminContext: KiiAppAdminContext, anErrorString: string): any; }): Promise<[KiiAppAdminContext, KiiUser]>; + + /** + * Register thing by app admin. + * Method interface is same as {@link KiiThing#register()}. + * Please refer to KiiThing document for details. + * + * @param fields of the thing to be registered. Please refer to {@link KiiThing#register()} for the details of fields. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(thing). thing is KiiThing instance with adminToken.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // Assume you already have adminContext instance. + * adminContext.registerThing( + * { + * _vendorThingID: "thing-XXXX-YYYY-ZZZZZ", + * _password: "thing-password", + * _thingType: "thermometer", + * yourCustomObj: // Arbitrary key can be used. + * { // Object, Array, Number, String can be used. Should be compatible with JSON. + * yourCustomKey1: "value", + * yourCustomKey2: 100 + * } + * }, + * { + * success: function(thing) { + * // Register Thing succeeded. + * // Operation using thing instance in the parameter + * // is authored by app admin. + * }, + * failure: function(error) { + * // Handle error. + * } + * } + * ); + * + * // example to use Promise + * // Assume you already have adminContext instance. + * adminContext.registerThing( + * { + * _vendorThingID: "thing-XXXX-YYYY-ZZZZZ", + * _password: "thing-password", + * _thingType: "thermometer", + * yourCustomObj: // Arbitrary key can be used. + * { // Object, Array, Number, String can be used. Should be compatible with JSON. + * yourCustomKey1: "value", + * yourCustomKey2: 100 + * } + * } + * ).then( + * function(thing) { + * // Register Thing succeeded. + * // Operation using thing instance in the parameter + * // is authored by app admin. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + registerThing(fields: KiiThingFields, callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + + /** + * Creates a reference to a thing operated by app admin. + * + * @param thing id. + * + * @return A working KiiThing object + * + * @example + * // Assume you already have adminContext instance. + * adminContext.thingWithID(thingID); + */ + thingWithID(thing: string): KiiThing; + + /** + * Register user/group as owner of specified thing by app admin. + * + * @param thingID The ID of thing + * @param owner to be registered as owner. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is an Array instance. + *
        + *
      • params[0] is a KiiUser/KiiGroup instance.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume thing/group is already registered. + * var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy"); + * // example to use Promise + * // Assume you already have adminContext instance. + * adminContext.registerOwnerWithThingID("th.xxxx-yyyy-zzzz", group, { + * success: function(group) { + * // Register owner succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume thing/group is already registered. + * var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy"); + * // example to use Promise + * // Assume you already have adminContext instance. + * adminContext.registerOwnerWithThingID("th.xxxx-yyyy-zzzz", group).then( + * function(params) { + * // Register owner succeeded. + * var group = params[0]; + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + registerOwnerWithThingID(thingID: string, owner: T, callbacks?: { success(group: T): any; failure(error: Error): any; }): Promise; + + /** + * Register user/group as owner of specified thing by app admin. + * + * @param vendorThingID The vendor thing ID of thing + * @param owner to be registered as owner. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is an Array instance. + *
        + *
      • params[0] is a KiiUser/KiiGroup instance.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume thing/group is already registered. + * var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy"); + * // example to use Promise + * // Assume you already have adminContext instance. + * adminContext.registerOwnerWithVendorThingID("xxxx-yyyy-zzzz", group, { + * success: function(group) { + * // Register owner succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume thing/group is already registered. + * var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy"); + * // example to use Promise + * // Assume you already have adminContext instance. + * adminContext.registerOwnerWithVendorThingID("xxxx-yyyy-zzzz", group).then( + * function(group) { + * // Register owner succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + registerOwnerWithVendorThingID(vendorThingID: string, owner: T, callbacks?: { success(group: T): any; failure(error: Error): any; }): Promise; + + /** + * Load thing with vendor thing ID by app admin. + * Method interface is same as {@link KiiThing#loadWithVendorThingID()}. + * Please refer to KiiThing document for details. + * + * @param vendorThingID registered vendor thing id. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(thing). thing is KiiThing instance with adminToken.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // Assume you already have adminContext instance. + * adminContext.loadThingWithVendorThingID("thing-xxxx-yyyy",{ + * success: function(thing) { + * // Load succeeded. + * // Operation using thing instance in the parameter + * // is authored by app admin. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // Assume you already have adminContext instance. + * adminContext.loadThingWithVendorThingID("thing-xxxx-yyyy").then( + * function(thing) { + * // Load succeeded. + * // Operation using thing instance in the parameter + * // is authored by app admin. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + loadThingWithVendorThingID(vendorThingID: string, callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + + /** + * Load thing with thing ID by app admin. + * Method interface is same as {@link KiiThing#loadWithThingID()}. + * Please refer to KiiThing document for details. + * + * @param thingID registered thing id. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(thing). thing is KiiThing instance with adminToken.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // Assume you already have adminContext instance. + * adminContext.loadThingWithThingID("thing-xxxx-yyyy",{ + * success: function(thing) { + * // Load succeeded. + * // Operation using thing instance in the parameter + * // is authored by app admin. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // Assume you already have adminContext instance. + * adminContext.loadThingWithThingID("thing-xxxx-yyyy").then( + * function(thing) { + * // Load succeeded. + * // Operation using thing instance in the parameter + * // is authored by app admin. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + loadThingWithThingID(thingID: string, callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + + /** + * Creates a reference to a topic operated by app admin + * + * @param topicName name of the topic. Must be a not empty string. + * + * @return topic instance. + */ + topicWithName(topicName: string): KiiTopic; + + /** + * Gets a list of topics in app scope + * + * @param callbacks An object with callback methods defined + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is array of KiiTopic instances.
      • + *
      • params[1] is string of nextPaginationKey.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiAppAdminContext instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // Assume you already have adminContext instance. + * adminContext.listTopics({ + * success: function(topicList, nextPaginationKey) { + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * Kii.listTopics({ + * success: function(topicList, nextPaginationKey) {...}, + * failure: function(anErrorString) {...} + * }, nextPaginationKey); + * } + * }, + * failure: function(anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * // Assume you already have adminContext instance. + * adminContext.listTopics().then( + * function(params) { + * var topicList = params[0]; + * var nextPaginationKey = params[1]; + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * adminContext.listTopics(null, nextPaginationKey).then( + * function(params) {...}, + * function(error) {...} + * ); + * } + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + } + + /** + * Represents a KiiBucket object + */ + export class KiiBucket { + /** + * The name of this bucket + * + * @return + */ + getBucketName(): string; + + /** + * Create a KiiObject within the current bucket + * + *

    The object will not be created on the server until the KiiObject is explicitly saved. This method simply returns an empty working KiiObject. + * + * @return An empty KiiObject with no specific type + * + * @example + * var bucket = . . .; // a KiiBucket + * var object = bucket.createObject(); + */ + createObject(): KiiObject; + + /** + * Create a KiiObject within the current bucket, with type + * + *

    The object will not be created on the server until the KiiObject is explicitly saved. This method simply returns an empty working KiiObject with a specified type. The type allows for better indexing and improved query results. It is recommended to use this method - but for lazy creation, the createObject method is also available. + * + * @param type A string representing the desired object type + * + * @return An empty KiiObject with specified type + * + * @example + * var bucket = . . .; // a KiiBucket + * var object = bucket.createObjectWithType("scores"); + */ + createObjectWithType(type: string): KiiObject; + + /** + * Create a KiiObject within the current bucket, specifying its ID. + * + *

    If the object has not exist on KiiCloud, {@link KiiObject#saveAllFields(callback)} + * will create new Object which has ID specified in the argument. + * If the object exist in KiiCloud, references the existing object which has + * specified ID. use {@link KiiObject#refresh(callback)} to retrieve the contents of + * KiiObject. + * + * @param objectID ID of the obeject you want to instantiate. + * + * @return KiiObject instance. + * + * @throws objectID is not acceptable. + * Refer to {@link KiiObject.isValidObjectID(string)} for details of acceptable string. + * + * @example + * var bucket = . . .; // KiiBucket + * var object = bucket.createObjectWithID('__OBJECT_ID_'); + */ + createObjectWithID(objectID: string): KiiObject; + + /** + * Get the ACL handle for this bucket + * + *

    Any KiiACLEntry objects added or revoked from this ACL object will be appended to/removed from the server on ACL save. + * + * @return A KiiACL object associated with this KiiObject + * + * @example + * var bucket = . . .; // a KiiBucket + * var acl = bucket.acl(); + */ + acl(): KiiACL; + + /** + * Perform a query on the given bucket + * + *

    The query will be executed against the server, returning a result set. + * + * @param query An object with callback methods defined + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is a performed KiiQuery instance.
      • + *
      • params[1] is resultSet Array instance. Could be KiiObject, KiiGroup, KiiUser, etc.
      • + *
      • params[2] is a KiiQuery instance for next query. If there are no more results to be retrieved, it will be null.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiBucket instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var bucket = . . .; // a KiiBucket + * var queryObject = . . .; // a KiiQuery + * + * // define the callbacks (stored in a variable for reusability) + * var queryCallbacks = { + * success: function(queryPerformed, resultSet, nextQuery) { + * // do something with the results + * for(var i=0; i<resultSet.length; i++) { + * // do something with the object + * // resultSet[i]; // could be KiiObject, KiiGroup, KiiUser, etc + * } + * + * // if there are more results to be retrieved + * if(nextQuery != null) { + * + * // get them and repeat recursively until no results remain + * bucket.executeQuery(nextQuery, queryCallbacks); + * } + * }, + * + * failure: function(bucket, anErrorString) { + * // do something with the error response + * } + * }; + * bucket.executeQuery(queryObject, queryCallbacks); + * + * // example to use Promise + * var bucket = . . .; // a KiiBucket + * var queryObject = . . .; // a KiiQuery + * bucket.executeQuery(queryObject).then( + * function(params) { + * var queryPerformed = params[0]; + * var resultSet = params[1]; + * var nextQuery = params[2]; + * // do something with the results + * for(var i=0; i<resultSet.length; i++) { + * // do something with the object + * // resultSet[i]; // could be KiiObject, KiiGroup, KiiUser, etc + * } + * + * // if there are more results to be retrieved + * if(nextQuery != null) { + * + * // get them and repeat recursively until no results remain + * bucket.executeQuery(nextQuery).then( + * function(params) { + * // next query success + * }, + * function(error) { + * // next query failed, please handle the error + * } + * ); + * } + * + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + executeQuery(query: KiiQuery, callbacks?: { success(queryPerformed: KiiQuery, resultSet: T[], nextQuery: KiiQuery): any; failure(bucket: KiiBucket, anErrorString: string): any; }): Promise<[KiiQuery, T[], KiiQuery]>; + + /** + * Execute count aggregation of specified query on current bucket. + * Query that passed as nextQuery in success callback of {@link #executeQuery}, is not + * supported, callbacks.failure will be fired in this case. + * + * @param query to be executed. If null, the operation will be same as {@link #count}. + * @param callbacks An object with callback methods defined. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is a KiiBucket instance which this method was called on.
      • + *
      • params[1] is a KiiQuery instance.
      • + *
      • params[2] is an integer count result.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiBucket instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var bucket = . . .; // a KiiBucket + * var queryObject = . . .; // a KiiQuery + * + * // define the callbacks + * var callbacks = { + * success: function(bucket, query, count) { + * // do something with the results + * }, + * + * failure: function(bucket, errorString) { + * // error happened. + * } + * }; + * + * bucket.countWithQuery(queryObject, callbacks); + * + * // example to use Promise + * var bucket = . . .; // a KiiBucket + * var queryObject = . . .; // a KiiQuery + * + * bucket.countWithQuery(queryObject, callbacks).then( + * function(params) { + * var bucket = params[0]; + * var query = params[1]; + * var count = params[2]; + * // do something with the results + * }, + * function(error) { + * var bucket = error.target; + * var errorString = error.message; + * // error happened. + * } + * ); + */ + countWithQuery(query: KiiQuery, callbacks?: { success(bucket: KiiBucket, query: KiiQuery, count: number): any; failure(bucket: KiiBucket, errorString: string): any; }): Promise<[KiiBucket, KiiQuery, number]>; + + /** + * Execute count aggregation of all clause query on current bucket. + * + * @param callbacks An object with callback methods defined. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is a KiiBucket instance which this method was called on.
      • + *
      • params[1] is a KiiQuery instance.
      • + *
      • params[2] is an integer count result.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiBucket instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var bucket = . . .; // a KiiBucket + * // define the callbacks + * var callbacks = { + * success: function(bucket, query, count) { + * // do something with the results + * }, + * + * failure: function(bucket, errorString) { + * // error happened. + * } + * }; + * + * bucket.count(callbacks); + * + * // example to use Promise + * var bucket = . . .; // a KiiBucket + * var queryObject = . . .; // a KiiQuery + * + * bucket.count().then( + * function(params) { + * var bucket = params[0]; + * var count = params[2]; + * // do something with the results + * }, + * function(error) { + * var bucket = error.target; + * var errorString = error.message; + * // error happened. + * } + * ); + */ + count(callbacks?: { success(bucket: KiiBucket, query: KiiQuery, count: number): any; failure(bucket: KiiBucket, errorString: string): any; }): Promise<[KiiBucket, KiiQuery, number]>; + + /** + * Delete the given bucket from the server + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(deletedBucket). deletedBucket is KiiBucket instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiBucket instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var bucket = . . .; // a KiiBucket + * bucket['delete']({ + * success: function(deletedBucket) { + * // do something with the result + * }, + * + * failure: function(bucketToDelete, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var bucket = . . .; // a KiiBucket + * bucket['delete']({ + * success: function(deletedBucket) { + * // do something with the result + * }, + * + * failure: function(bucketToDelete, anErrorString) { + * // do something with the error response + * } + * }).then( + * function(deletedBucket) { + * // do something with the result + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + delete(callbacks?: { success(deletedBucket: KiiBucket): any; failure(bucketToDelete: KiiBucket, anErrorString: string): any; }): Promise; + } + + /** + * Represents a KiiClause expression object + */ + export class KiiClause { + /** + * Create a KiiClause with the AND operator concatenating multiple KiiClause objects + * + * @param A variable-length list of KiiClause objects to concatenate + * + * @example + * KiiClause clause = KiiClause.and(clause1, clause2, clause3, . . .) + */ + static and(...A: KiiClause[]): KiiClause; + + /** + * Create a KiiClause with the OR operator concatenating multiple KiiClause objects + * + * @param A variable-length list of KiiClause objects to concatenate + * + * @example + * KiiClause clause = KiiClause.or(clause1, clause2, clause3, . . .) + */ + static or(...A: KiiClause[]): KiiClause; + + /** + * Create an expression of the form (key == value) + * + * @param key The key to compare + * @param value the value to compare + */ + static equals(key: string, value: any): KiiClause; + + /** + * Create an expression of the form (key != value) + * + * @param key The key to compare + * @param value the value to compare + */ + static notEquals(key: string, value: any): KiiClause; + + /** + * Create an expression of the form (key > value) + * + * @param key The key to compare + * @param value the value to compare + */ + static greaterThan(key: string, value: any): KiiClause; + + /** + * Create an expression of the form (key >= value) + * + * @param key The key to compare + * @param value the value to compare + */ + static greaterThanOrEqual(key: string, value: any): KiiClause; + + /** + * Create an expression of the form (key < value) + * + * @param key The key to compare + * @param value the value to compare + */ + static lessThan(key: string, value: any): KiiClause; + + /** + * Create an expression of the form (key <= value) + * + * @param key The key to compare + * @param value the value to compare + */ + static lessThanOrEqual(key: string, value: any): KiiClause; + + /** + * Create an expression of the form (key in values) + * + * @param key The key to compare + * @param values to compare + */ + static inClause(key: string, values: any[]): KiiClause; + + /** + * Create an expression of the form (key STARTS WITH value) + * + * @param key The key to compare + * @param value the value to compare + */ + static startsWith(key: string, value: any): KiiClause; + + /** + * Create a clause of geo distance. This clause inquires objects in the specified circle. + * + * @param key Name of the key to inquire, which holds geo point. + * @param center Geo point which specify center of the circle. + * @param radius Radius of the circle. unit is meter. value should be in range of ]0, 20000000] + * @param putDistanceInto Used for retrieve distance from the center from the query result.Must match the pattern "^[a-zA-Z_][a-zA-Z0-9_]*$". + * If the specified value is null, query result will not contain the distance. + * Note: You can get the results in ascending order of distances from center. To do so, build the orderBy field by + * "_calculated.{specified value of putDistanceInto}" and pass it in {@link KiiQuery#sortByAsc}. Note that, descending order + * of distances is not supported. The unit of distance is meter. + * + * @return KiiClaluse reference. + * + * @throws
  • Specified key is not a string or an empty string.
  • + *
  • center is not an object of KiiGeoPoint.
  • + *
  • putDistanceInto is not a string or an empty string.
  • + * + * @example + * var putDistanceInto = "distanceFromCurrentLoc"; + * var currentLoc = ..; // current location + * var clause = KiiClause.geoDistance("location", currentLoc, 4000, putDistanceInto); + * var query = KiiQuery.queryWithClause(clause); + * // Sort by distances by ascending order.(Optional, use only if you intend to retrieve the distances in a ascending order). + * var orderByKey = "_calculated." + putDistanceInto; + * query.sortByAsc(orderByKey); + * // Define the callbacks + * var bucket = Kii.bucketWithName("MyBucket"); + * var queryCallback = { + * success: function(queryPerformed, resultSet, nextQuery) { + * // check the first object from resultSet. + * var object = resultSet[0]; + * var point = object.get("location"); + * var distanceToMyLocation = object.get("_calculated")[putDistanceInto]; + * }, + * failure: function(queryPerformed, anErrorString) { + * // do something with the error response + * } + * }; + * bucket.executeQuery(query, queryCallback); + */ + static geoDistance(key: string, center: KiiGeoPoint, radius: number, putDistanceInto: string): KiiClause; + + /** + * Create a clause of geo box. This clause inquires objects in the specified rectangle. + * Rectangle would be placed parallel to the equator with specified coordinates of the corner. + * + * @param key Key to inquire which holds geo point. + * @param northEast North-Eest corner of the rectangle. + * @param southWest South-Wast corner of the rectangle. + * + * @return KiiClause reference. + * + * @throws
  • Specified key is not a string or is an empty string.
  • + *
  • northEast or southWest is not a reference of KiiGeoPoint.
  • + */ + static geoBox(key: string, northEast: KiiGeoPoint, southWest: KiiGeoPoint): KiiClause; + } + + /** + * Represents Geo Point. + */ + export class KiiGeoPoint { + /** + * Return the latitide of this point. + */ + getLatitude(): number; + + /** + * Return the longitude of this point. + */ + getLongitude(): number; + + /** + * Create a geo point with the given latitude and longitude. + * + * @param latitude Latitude of the point in degrees. Valid if the value is greater than -90 degrees and less than +90 degrees. + * @param longitude Longitude of the point in degrees. Valid if the value is greater than -180 degrees and less than +180 degrees. + * + * @return A new reference of KiiGeoPoint. + * + * @throws Specified latitude or longitude is invalid. + * + * @example + * var point = KiiGeoPoint.geoPoint(35.07, 139.02); + */ + static geoPoint(latitude: number, longitude: number): KiiGeoPoint; + } + + /** + * Represents a KiiGroup object + */ + export class KiiGroup { + /** + * + * + * @deprecated Use {@link KiiGroup.getId} instead. + * Get the UUID of the given group, assigned by the server + * + * @return + */ + getUUID(): string; + + /** + * Get the ID of the current KiiGroup instance. + * + * @return Id of the group or null if the group has not saved to cloud. + */ + getID(): string; + + /** + * The name of this group + * + * @return + */ + getName(): string; + + /** + * Returns the owner of this group if this group holds the information of owner. + * + * Group will holds the information of owner when "saving group on cloud" or "retrieving group info/owner from cloud". + * The cache will not be shared among the different instances of KiiGroup. + *
      + *
    • This API will not access to server. + * To update the group owner information on cloud, please call {@link KiiGroup#refresh} or {@link KiiGroup#getOwner}. + *
    • + *
    • This API does not return all the properties of the owner. + * To get all owner properties, {@link KiiUser#refresh} is necessary.
    • + *
    + * + * @return KiiUser who owns this group, undefined if this group doesn't hold the information of owner yet. + * + * @see KiiGroup#getOwner + */ + getCachedOwner(): KiiUser; + + /** + * Get a specifically formatted string referencing the group + * + *

    The group must exist in the cloud (have a valid UUID). + * + * @return A URI string based on the current group. null if a URI couldn't be generated. + * + * @example + * var group = . . .; // a KiiGroup + * var uri = group.objectURI(); + */ + objectURI(): string; + + /** + * Creates a reference to a bucket for this group + * + *

    The bucket will be created/accessed within this group's scope + * + * @param bucketName The name of the bucket the user should create/access + * + * @return A working KiiBucket object + * + * @example + * var group = . . .; // a KiiGroup + * var bucket = group.bucketWithName("myBucket"); + */ + bucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to a encrypted bucket for this group + * + *

    The bucket will be created/accessed within this group's scope + * + * @param bucketName The name of the bucket the user should create/access + * + * @return A working KiiEncryptedBucket object + * + * @example + * var group = . . .; // a KiiGroup + * var bucket = group.encryptedBucketWithName("myBucket"); + */ + encryptedBucketWithName(bucketName: string): KiiBucket; + + /** + * Adds a user to the given group + * + *

    This method will NOT access the server immediately. You must call save to add the user on the server. This allows multiple users to be added/removed before calling save. + * + * @param member The user to be added to the group + * + * @example + * var user = . . .; // a KiiUser + * var group = . . .; // a KiiGroup + * group.addUser(user); + * group.save(callbacks); + */ + addUser(member: KiiUser): void; + + /** + * Removes a user from the given group + * + *

    This method will NOT access the server immediately. You must call save to remove the user on the server. This allows multiple users to be added/removed before calling save. + * + * @param member The user to be added to the group + * + * @example + * var user = . . .; // a KiiUser + * var group = . . .; // a KiiGroup + * group.removeUser(user); + * group.save(callbacks); + */ + removeUser(member: KiiUser): void; + + /** + * Gets a list of all current members of a group + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is a KiiGroup instance which this method was called on.
      • + *
      • params[1] is array of memeber KiiUser instances.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiACL instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var group = . . .; // a KiiGroup + * group.getMemberList({ + * success: function(theGroup, memberList) { + * // do something with the result + * for(var i=0; i<memberList.length; i++){ + * var u = memberList[i]; // a KiiUser within the group + * } + * }, + * + * failure: function(theGroup, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var group = . . .; // a KiiGroup + * group.getMemberList().then( + * function(params) { + * var theGroup = params[0]; + * var memberlist = params[1]; + * // do something with the result + * for(var i=0; i<memberList.length; i++){ + * var u = memberList[i]; // a KiiUser within the group + * } + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + getMemberList(callbacks?: { success(theGroup: KiiGroup, memberList: KiiUser[]): any; failure(theGroup: KiiGroup, anErrorString: string): any; }): Promise<[KiiGroup, KiiUser[]]>; + + /** + * Updates the group name on the server + * + * @param newName A String of the desired group name + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theRenamedGroup). theRenamedGroup is KiiGroup instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiGroup instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var group = . . .; // a KiiGroup + * group.changeGroupName("myNewName", { + * success: function(theRenamedGroup) { + * // do something with the group + * }, + * + * failure: function(theGroup, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var group = . . .; // a KiiGroup + * group.changeGroupName("myNewName").then( + * function(theRenamedGroup) { + * // do something with the group + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + changeGroupName(newName: string, callbacks?: { success(theRenamedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string): any; }): Promise; + + /** + * Saves the latest group values to the server + * + *

    If the group does not yet exist, it will be created. If the group already exists, the members that have changed will be updated accordingly. If the group already exists and there is no updates of members, it will allways succeed but does not execute update. To change the name of group, use {@link #changeGroupName}. + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theSavedGroup). theSavedGroup is KiiGroup instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiGroup instance which this method was called on.
      • + *
      • error.message
      • + *
      • error.addMembersArray is array of KiiUser to be added as memebers of this group.
      • + *
      • error.removeMembersArray is array of KiiUser to be removed from the memebers list of this group.
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var group = . . .; // a KiiGroup + * group.save({ + * success: function(theSavedGroup) { + * // do something with the saved group + * }, + * + * failure: function(theGroup, anErrorString, addMembersArray, removeMembersArray) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var group = . . .; // a KiiGroup + * group.save({ + * success: function(theSavedGroup) { + * // do something with the saved group + * }, + * + * failure: function(theGroup, anErrorString, addMembersArray, removeMembersArray) { + * // do something with the error response + * } + * }).then( + * function(theSavedGroup) { + * // do something with the saved group + * }, + * function(error) { + * var theGroup = error.target; + * var anErrorString = error.message; + * var addMembersArray = error.addMembersArray; + * var removeMembersArray = error.removeMembersArray; + * // do something with the error response + * }); + */ + save(callbacks?: { success(theSavedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string, addMembersArray: KiiUser[], removeMembersArray: KiiUser[]): any; }): Promise; + + /** + * Updates the local group's data with the group data on the server + * + *

    The group must exist on the server. Local data will be overwritten. + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theRefreshedGroup). theRefreshedGroup is KiiGroup instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiGroup instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var group = . . .; // a KiiGroup + * group.refresh({ + * success: function(theRefreshedGroup) { + * // do something with the refreshed group + * }, + * + * failure: function(theGroup, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var group = . . .; // a KiiGroup + * group.refresh().then( + * function(theRefreshedGroup) { + * // do something with the refreshed group + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + refresh(callbacks?: { success(theRefreshedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string): any; }): Promise; + + /** + * Delete the group from the server + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theDeletedGroup). theDeletedGroup is KiiGroup instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiGroup instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var group = . . .; // a KiiGroup + * group['delete']({ + * success: function(theDeletedGroup) { + * // do something + * }, + * + * failure: function(theGroup, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var group = . . .; // a KiiGroup + * group['delete']({ + * success: function(theDeletedGroup) { + * }, + * + * failure: function(theGroup, anErrorString) { + * } + * }).then( + * function(theDeletedGroup) { + * // do something + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + delete(callbacks?: { success(theDeletedGroup: KiiGroup): any; failure(theGroup: KiiGroup, anErrorString: string): any; }): Promise; + + /** + * Gets the owner of the associated group + * + * This API does not return all the properties of the owner. + * To get all owner properties, {@link KiiUser#refresh} is necessary. + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is the KiiGroup instance which this method was called on.
      • + *
      • params[1] is an group owner KiiUser instances.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiGroup instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var group = . . .; // a KiiGroup + * group.getOwner({ + * success: function(theGroup, theOwner) { + * // do something + * }, + * failure: function(theGroup, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var group = . . .; // a KiiGroup + * group.getOwner().then( + * function(params) { + * // do something + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + getOwner(callbacks?: { success(theGroup: KiiGroup, theOwner: KiiUser): any; failure(theGroup: KiiGroup, anErrorString: string): any; }): Promise<[KiiGroup, KiiUser]>; + + /** + * Creates a reference to a group with the given name + *

    + * Note: + * Returned instance from this API can not operate existing KiiGroup.
    + * If you want to operate existing KiiGroup, please use {@link KiiGroup.groupWithURI}. + * + * @param groupName An application-specific group name + * + * @return A new KiiGroup reference + * + * @example + * var group = new KiiGroup.groupWithName("myGroup"); + */ + static groupWithName(groupName: string): KiiGroup; + + /** + * Creates a reference to a group with the given name and a list of default members + *

    + * Note: + * Returned instance from this API can not operate existing KiiGroup.
    + * If you want to operate existing KiiGroup, please use {@link KiiGroup.groupWithURI}. + * + * @param groupName An application-specific group name + * @param members An array of KiiUser objects to add to the group + * + * @return A new KiiGroup reference + * + * @example + * var group = new KiiGroup.groupWithName("myGroup", members); + */ + static groupWithNameAndMembers(groupName: string, members: KiiUser[]): KiiGroup; + + /** + * Instantiate KiiGroup that refers to existing group which has specified ID. + * You have to specify the ID of existing KiiGroup. Unlike KiiObject, + * you can not assign ID in the client side.
    + * NOTE: This API does not access to the server. + * After instantiation, call {@link KiiGroup#refresh} to fetch the properties. + * + * @param groupId ID of the KiiGroup to instantiate. + * + * @return instance of KiiGroup. + * + * @throws when passed groupID is empty or null. + * + * @example + * var group = new KiiUser.groupWithID("__GROUP_ID__"); + */ + static groupWithID(groupId: string): KiiGroup; + + /** + * Generate a new KiiGroup based on a given URI + *

    + * Note: + * Returned instance from this API can operate existing KiiGroup.
    + * If you want to create a new KiiGroup, please use {@link KiiGroup.groupWithName}. + * + * @param uri The URI of the group to be represented + * + * @return A new KiiGroup with its parameters filled in from the URI + * + * @throws If the URI given is invalid + * + * @example + * var group = new KiiGroup.groupWithURI("kiicloud://myuri"); + */ + static groupWithURI(uri: string): KiiGroup; + + /** + * Instantiate topic belongs to this group. + * + * @param topicName name of the topic. Must be a not empty string. + * + * @return topic instance. + */ + topicWithName(topicName: string): KiiTopic; + + /** + * Gets a list of topics in this group scope + * + * @param callbacks An object with callback methods defined + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is array of KiiTopic instances.
      • + *
      • params[1] is string of nextPaginationKey.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiGroup instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var group = . . .; // a KiiGroup + * group.listTopics({ + * success: function(topicList, nextPaginationKey) { + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * group.listTopics({ + * success: function(topicList, nextPaginationKey) {...}, + * failure: function(anErrorString) {...} + * }, nextPaginationKey); + * } + * }, + * failure: function(anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use promise + * var group = . . .; // a KiiGroup + * group.listTopics().then( + * function(params) { + * var topicList = params[0]; + * var nextPaginationKey = params[1]; + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * group.listTopics(null, nextPaginationKey).then( + * function(params) {...}, + * function(error) {...} + * ); + * } + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + } + + /** + * Represents a KiiObject object + */ + export class KiiObject { + /** + * Get the UUID of the given object, assigned by the server + * + * @return + */ + getUUID(): string; + + /** + * Get the server's creation date of this object + * + * @return + */ + getCreated(): number; + + /** + * Get the modified date of the given object, assigned by the server + * + * @return + */ + getModified(): string; + + /** + * Get the application-defined type name of the object + * + * @return + */ + getObjectType(): string; + + /** + * Get the body content-type. + * It will be updated after the success of {@link KiiObject#uploadBody} and {@link KiiObject#downloadBody} + * returns null when this object doesn't have body content-type information. + * + * @return content-type of object body + */ + getBodyContentType(): string; + + /** + * Sets a key/value pair to a KiiObject + * + *

    If the key already exists, its value will be written over. If the object is of invalid type, it will return false and a KiiError will be thrown (quietly). Accepted types are any JSON-encodable objects. + *
    NOTE: Before involving floating point value, please consider using integer instead. For example, use percentage, permil, ppm, etc.
    + * The reason is: + *
  • Will dramatically improve the performance of bucket query.
  • + *
  • Bucket query does not support the mixed result of integer and floating point. + * ex.) If you use same key for integer and floating point and inquire object with the integer value, objects which has floating point value with the key would not be evaluated in the query. (and vice versa)
  • + * + * @param key The key to set. The key must not be a system key (created, metadata, modified, type, uuid) or begin with an underscore (_) + * @param value The value to be set. Object must be of a JSON-encodable type (Ex: dictionary, array, string, number, etc) + * + * @example + * var obj = . . .; // a KiiObject + * obj.set("score", 4298); + */ + set(key: string, value: any): void; + + /** + * Gets the value associated with the given key + * + * @param key The key to retrieve + * + * @return The object associated with the key. null if none exists + * + * @example + * var obj = . . .; // a KiiObject + * var score = obj.get("score"); + */ + get(key: string): T; + + /** + * Set Geo point to this object with the specified key. + * + * @param key The key to set. + * @param KiiGeoPoint to be tied to the specified key. + * + * @throws Specified kiiGeoPint is not an instance of KiiGeoPoint. + */ + setGeoPoint(key: string, KiiGeoPoint: KiiGeoPoint): void; + + /** + * Gets the geo point associated with the given key. + * + * @param key The key of the geo point to retrieve. + * + * @return KiiGeoPoint tied to the key. null if null exists. + */ + getGeoPoint(key: string): KiiGeoPoint; + + /** + * Get the ACL handle for this file + * + *

    Any KiiACLEntry objects added or revoked from this ACL object will be appended to/removed from the server on ACL save. + * + * @return A KiiACL object associated with this KiiObject + * + * @example + * var obj = . . .; // a KiiObject + * var acl = obj.objectACL(); + */ + objectACL(): KiiACL; + + /** + * Get a specifically formatted string referencing the object + * + *

    The object must exist in the cloud (have a valid UUID). + * + * @return A URI string based on the current object. null if a URI couldn't be generated. + * + * @example + * var obj = . . .; // a KiiObject + * var uri = obj.objectURI(); + */ + objectURI(): string; + + /** + * Create or update the KiiObject on KiiCloud. + *

    When call this method for the object that has not saved on cloud, will send all fields. + * Call this method for the object that has saved on cloud, Update all field of this object. + * + * @param callbacks An object with callback methods defined + * sucess: function called when save succeeded.
    + * failure: function called when save failed. + * @param overwrite optional, true by default. + *
      + *
    • If overwrite is true: + *
        + *
      • If a KiiObject with the same ID exists in cloud, the local copy will overwrite the remote copy, even if the remote copy is newer.
      • + *
      + *
    • Otherwise: + *
        + *
      • If a KiiObject with the same ID exists in cloud and the remote copy is newer, save will fail.
      • + *
      + *
    + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theSavedObject). theSavedObject is KiiObject instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiObject instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var obj = . . .; // a KiiObject + * obj.saveAllFields({ + * success: function(theSavedObject) { + * // do something with the saved object + * }, + * + * failure: function(theObject, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var obj = . . .; // a KiiObject + * obj.saveAllFields().then( + * function(theSavedObject) { + * // do something with the saved object + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + saveAllFields(callbacks?: { success(theSavedObject: KiiObject): any; failure(theObject: KiiObject, anErrorString: string): any; }, overwrite?: boolean): Promise; + + /** + * Create or update the KiiObject on KiiCloud. + *

    When call this method for the object that has not saved on cloud, will send all fields. + * Call this method for the object that has saved on cloud, Update only updated fields. + * Do not send fields that has not updated locally. To send all fields regardless of updates, call {@link KiiObject#saveAllFields}. + * + * @param callbacks An object with callback methods defined + * sucess: function called when save succeeded.
    + * failure: function called when save failed. + * @param overwrite optional, true by default. + *
      + *
    • If overwrite is true: + *
        + *
      • If a KiiObject with the same ID exists in cloud, the local copy will overwrite the remote copy, even if the remote copy is newer.
      • + *
      + *
    • Otherwise: + *
        + *
      • If a KiiObject with the same ID exists in cloud and the remote copy is newer, save will fail.
      • + *
      + *
    + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theSavedObject). theSavedObject is KiiObject instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiObject instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var obj = . . .; // a KiiObject + * obj.save({ + * success: function(theSavedObject) { + * // do something with the saved object + * }, + * + * failure: function(theObject, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var obj = . . .; // a KiiObject + * obj.save().then( + * function(theSavedObject) { + * // do something with the saved object + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + save(callbacks?: { success(theSavedObject: KiiObject): any; failure(theObject: KiiObject, anErrorString: string): any; }, overwrite?: boolean): Promise; + + /** + * Updates the local object's data with the user data on the server + * + *

    The object must exist on the server. Local data will be overwritten. + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theRefreshedObject). theRefreshedObject is KiiObject instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiObject instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var obj = . . .; // a KiiObject + * obj.refresh({ + * success: function(theRefreshedObject) { + * // do something with the refreshed object + * }, + * + * failure: function(theObject, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var obj = . . .; // a KiiObject + * obj.refresh().then( + * function(theRefreshedObject) { + * // do something with the refreshed object + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + refresh(callbacks?: { success(theRefreshedObject: KiiObject): any; failure(theObject: KiiObject, anErrorString: string): any; }): Promise; + + /** + * Delete the object from the server + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theDeletedObject). theDeletedObject is KiiObject instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiObject instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var obj = . . .; // a KiiObject + * obj['delete']({ + * success: function(theDeletedObject) { + * // do something + * }, + * + * failure: function(theObject, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var obj = . . .; // a KiiObject + * obj['delete']().then( + * function(theDeletedObject) { + * // do something + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + delete(callbacks?: { success(theDeletedObject: KiiObject): any; failure(theObject: KiiObject, anErrorString: string): any; }): Promise; + + /** + * Generate a new KiiObject based on a given URI + * + * @param uri The URI of the object to be represented + * + * @return A new KiiObject with its parameters filled in from the URI + * + * @throws If the URI is not in the proper format + * + * @example + * var group = new KiiObject.objectWithURI("kiicloud://myuri"); + */ + static objectWithURI(uri: string): KiiObject; + + /** + * Move KiiObject body from an object to another object. + *
    + * This moving can be allowed under same application, across different scopes + * and source/target KiiObject have a read and write permission (READ_EXISTING_OBJECT and WRITE_EXISTING_OBJECT). + *

    If target KiiObject has a body, it will be overwritten. + * + * @param targetObjectUri A KiiObject URI which KiiObject body is moved to. + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is the source KiiObject instance which this method was called on.
      • + *
      • params[1] is the target targetObjectUri String.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the source KiiObject instance which this method was called on.
      • + *
      • error.targetObjectUri is the targetObjectUri String.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var sourceObject = ...; // Source KiiObject + * var targetObject = ...; // Target KiiObject + * var targetObjectUri = targetObject.objectURI(); + * sourceObject.moveBody(targetObjectUri, { + * success: function(theSrcObject, theTgtObjectUri) { + * // Do something with the objects + * }, + * + * failure: function(theSrcObject, theTgtObjectUri, anErrorString) { + * // Do something with the error response + * } + * }); + * + * // example to use Promise + * var sourceObject = ...; // Source KiiObject + * var targetObject = ...; // Target KiiObject + * var targetObjectUri = targetObject.objectURI(); + * sourceObject.moveBody(targetObjectUri).then( + * function(params) { + * var theSrcObject = params[0]; + * var theTgtObjectUri = params[1]; + * // Do something with the objects + * }, + * function(error) { + * // Do something with the error response + * } + * ); + */ + moveBody(targetObjectUri: string, callbacks?: { success(theSrcObject: KiiObject, theTgtObjectUri: string): any; failure(theSrcObject: KiiObject, theTgtObjectUri: string, anErrorString: string): any; }): Promise<[KiiObject, string]>; + + /** + * Upload body data of this object.
    + * If the KiiObject has not saved on the cloud or deleted, + * request will be failed. + *
    NOTE: this requires XMLHttpRequest Level 2, FileReader and Blob supports. Do not use it in server code.
    + * + * @param srcDataBlob data to be uploaded. + * type is used to determin content-type managed in Kii Cloud. + * If type was not specified in the Blob, + * 'application/octet-stream' will be used. + * @param callbacks progress: function called on XMLHttpRequest 'progress' event listener.
    + * sucess: function called when upload succeeded.
    + * failure: function called when upload failed. + * + * @return return promise object. + *
    NOTE: Promise will not handle progress event. Please pass callbacks with progress function to handle progress. + *
      + *
    • fulfill callback function: function(theObject). theObject is a KiiObject instance which this method was called on.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiObject instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var myObject = Kii.bucketWithName('myBucket').createObject(); + * myObject.save({ + * success: function(obj) { + * var srcData = new Blob(['Hello Blob'], {type: 'text/plain'}); + * obj.uploadBody(srcData, { + * progress: function (oEvent) { + * if (oEvent.lengthComputable) { + * var percentComplete = oEvent.loaded / oEvent.total; + * //getting upload progress. You can update progress bar on this function. + * } + * }, + * success: function(obj) { + * // Upload succeeded. + * }, + * failure: function(obj, anErrorString) { + * // Handle error. + * } + * }); + * }, + * failure: function(obj, error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * var myObject = Kii.bucketWithName('myBucket').createObject(); + * myObject.save().then( + * function(obj) { + * var srcData = new Blob(['Hello Blob'], {type: 'text/plain'}); + * obj.uploadBody(srcData, { + * progress: function (oEvent) { + * if (oEvent.lengthComputable) { + * var percentComplete = oEvent.loaded / oEvent.total; + * //getting upload progress. You can update progress bar on this function. + * } + * } + * }).then( + * function(obj) { // fullfill callback function + * // Upload succeeded. + * }, + * function(error) { // reject callback function + * // Handle error. + * } + * ); + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + uploadBody(srcDataBlob: Blob, callbacks?: { success(obj: KiiObject): any; failure(obj: KiiObject, anErrorString: string): any; }): Promise; + + /** + * Download body data of this object.
    + * If the KiiObject has not saved on the cloud or deleted + * or exist but does not have body object, request will be failed. + *
    NOTE: this requires XMLHttpRequest Level 2, FileReader and Blob supports. Do not use it in server code.
    + * + * @param callbacks progress: function called on XMLHttpRequest 'progress' event listener.
    + * sucess: function called when download succeeded.
    + * failure: function called when download failed. + * + * @return return promise object. + *
    NOTE: Promise will not handle progress event. Please pass callbacks with progress function to handle progress. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is a KiiObject instance which this method was called on.
      • + *
      • params[1] is the returned body blob object.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance.
    • + *
        + *
      • error.target is the KiiObject instance which this method was called on.
      • + *
      • error.message
      • + *
      + * + *
    + * + * @example + * // example to use callbacks directly + * var myObject = KiiObject.objectWithURI('put existing object uri here'); + * myObject.downloadBody({ + * progress: function (oEvent) { + * if (oEvent.lengthComputable) { + * var percentComplete = oEvent.loaded / oEvent.total; + * //getting download progress. You can update progress bar on this function. + * + * } + * }, + * success: function(obj, bodyBlob) { + * // Obtaind body contents as bodyBlob. + * // content-type managed in Kii Cloud can be obtained from type attr. + * // It is same as obj.getBodyContentType(); + * var contentType = bodyBlob.type; + * }, + * failure: function(obj, anErrorString) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * var myObject = KiiObject.objectWithURI('put existing object uri here'); + * myObject.downloadBody({ + * progress: function (oEvent) { + * if (oEvent.lengthComputable) { + * var percentComplete = oEvent.loaded / oEvent.total; + * //getting download progress. You can update progress bar on this function. + * + * } + * } + * ).then( + * function(params) { + * // Obtaind body contents as bodyBlob. + * // content-type managed in Kii Cloud can be obtained from type attr. + * // It is same as obj.getBodyContentType(); + * var obj = param[0]; + * var bodyBlob = params[1]; + * var contentType = bodyBlob.type; + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + downloadBody(callbacks?: { success(obj: KiiObject, bodyBlob: Blob): any; failure(obj: KiiObject, anErrorString: string): any; }): Promise<[KiiObject, Blob]>; + + /** + * Publish object body.
    + * Publish object body and obtain public URL links to the body.
    + * It doesn't expires.
    + * If the KiiObject has not saved on the cloud or deleted + * or exist but does not have body object, request will be failed. + * + * @param callbacks sucess: function called when publish succeeded.
    + * failure: function called when publish failed. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is the KiiObject instance which this method was called on.
      • + *
      • params[1] is the published url string.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiObject instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var myObject = KiiObject.objectWithURI('put existing object uri here'); + * myObject.publishBody({ + * success: function(obj, publishedUrl) { + * // ex.) You can show publishedUrl in the view. + * }, + * failure: function(obj, anErrorString) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * var myObject = KiiObject.objectWithURI('put existing object uri here'); + * myObject.publishBody().then( + * function(params) { + * // ex.) You can show publishedUrl in the view. + * var obj = params[0]; + * var publishedUrl = params[1]; + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + publishBody(callbacks?: { success(obj: KiiObject, publishedUrl: string): any; failure(obj: KiiObject, anErrorString: string): any; }): Promise<[KiiObject, string]>; + + /** + * Publish object body with expiration date.
    + * Publish object body and obtain public URL links to the body.
    + * Expires at specified date
    + * If the KiiObject has not saved on the cloud or deleted + * or exist but does not have body object, request will be failed. + * + * @param expiresAt expiration date. should specify future date. + * @param callbacks sucess: function called when publish succeeded.
    + * failure: function called when publish failed. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is the KiiObject instance which this method was called on.
      • + *
      • params[1] is the published url string.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiObject instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var myObject = KiiObject.objectWithURI('put existing object uri here'); + * var expiresAt = new Date(2014, 11, 24); + * myObject.publishBodyExpiresAt(expiresAt, { + * success: function(obj, publishedUrl) { + * // ex.) You can show publishedUrl in the view. + * }, + * failure: function(obj, anErrorString) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * var myObject = KiiObject.objectWithURI('put existing object uri here'); + * var expiresAt = new Date(2014, 11, 24); + * myObject.publishBodyExpiresAt(expiresAt).then( + * function(params) { + * // ex.) You can show publishedUrl in the view. + * var obj = params[0]; + * var publishedUrl = params[1]; + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + publishBodyExpiresAt(expiresAt: Date, callbacks?: { success(obj: KiiObject, publishedUrl: string): any; failure(obj: KiiObject, anErrorString: string): any; }): Promise<[KiiObject, string]>; + + /** + * Publish object body with expiration duration.
    + * Publish object body and obtain public URL links to the body.
    + * Expires in specified duration
    + * If the KiiObject has not saved on the cloud or deleted + * or exist but does not have body object, request will be failed. + * + * @param expiresIn duration in seconds. greater than 0. + * @param callbacks sucess: function called when publish succeeded.
    + * failure: function called when publish failed. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is the KiiObject instance which this method was called on.
      • + *
      • params[1] is the published url string.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiObject instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var myObject = KiiObject.objectWithURI('put existing object uri here'); + * var expiresIn = 60 * 60; // Expires in 1 hour. + * myObject.publishBodyExpiresIn(expiresIn, { + * success: function(obj, publishedUrl) { + * // ex.) You can show publishedUrl in the view. + * }, + * failure: function(obj, anErrorString) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * var myObject = KiiObject.objectWithURI('put existing object uri here'); + * var expiresIn = 60 * 60; // Expires in 1 hour. + * myObject.publishBodyExpiresIn(expiresIn).then( + * function(params) { + * // ex.) You can show publishedUrl in the view. + * var obj = params[0]; + * var publishedUrl = params[1]; + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + publishBodyExpiresIn(expiresIn: number, callbacks?: { success(obj: KiiObject, publishedUrl: string): any; failure(obj: KiiObject, anErrorString: string): any; }): Promise<[KiiObject, string]>; + + /** + * Delete the object body from the server.
    + * If the KiiObject has not saved on the cloud or deleted + * or exist but does not have body object, request will be failed.
    + * If succeeded, The object body content type will be nullified. + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theDeletedObject). theDeletedObject is the KiiObject instance which this method was called on.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiObject instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var obj = . . .; // a KiiObject + * obj.deleteBody({ + * success: function(theDeletedObject) { + * // do something + * }, + * + * failure: function(obj, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var obj = . . .; // a KiiObject + * obj.deleteBody().then( + * function(theDeletedObject) { + * // do something + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + deleteBody(callbacks?: { success(theDeletedObject: KiiObject): any; failure(obj: KiiObject, anErrorString: string): any; }): Promise; + + /** + * Check if given ID is valid for object ID. + * Valid pattern: ^[a-zA-Z0-9-_\\.]{2,100}$ + * + * @param objectID to be checked. + * + * @return true if given ID is valid, false otherwise. + */ + static isValidObjectID(objectID: string): boolean; + } + + /** + * Builder of push message + */ + export class KiiPushMessageBuilder { + /** + * instantiate builder with push message data. + * By default all push channels (gcm, apns, jpush, mqtt) is enabled. + * All other properties configured by method of this class won't be set and default + * value would be applied.
    + * Details of properties of message and its default value, please refer to + * http://documentation.kii.com/rest/#notification_management-leverage__push_to_users__notification-group_scope-send_messages-send_a_push_message_to_the_current_topic + * + * @param data sent to all push channels (gcm, apns, jpush, mqtt). + */ + constructor(data: any); + + /** + * build push message. + * + * @return push message object. Can be used in {@link KiiTopic#sendMessage()} + */ + build(): any; + + /** + * Indicate whether send this message to development environment. + * If this method is not called, true will be applied as default. + * + * @param flag indicate whether send this message to development env. + * + * @return builder instance. + */ + setSendToDevelopment(flag: boolean): KiiPushMessageBuilder; + + /** + * Indicate whether send this message to production environment. + * If this method is not called, true will be applied as default. + * + * @param flag indicate whether send this message to production env. + * + * @return builder instance. + */ + setSendToProduction(flag: boolean): KiiPushMessageBuilder; + + /** + * Enable/ Disable message distribution via GCM. + * If this method is not called, true will be applied as default. + * + * @param enable flag indicate whether distribute this message to GCM subscribers. + * + * @return builder instance. + */ + enableGcm(enable: boolean): KiiPushMessageBuilder; + + /** + * Enable/ Disable message distribution via APNS. + * If this method is not called, true will be applied as default. + * + * @param enable flag indicate whether distribute this message to APNS subscribers. + * + * @return builder instance. + */ + enableApns(enable: boolean): KiiPushMessageBuilder; + + /** + * Enable/ Disable message distribution via JPush. + * If this method is not called, true will be applied as default. + * + * @param enable flag indicate whether distribute this message to JPush subscribers. + * + * @return builder instance. + */ + enableJpush(enable: boolean): KiiPushMessageBuilder; + + /** + * Enable/ Disable message distribution via MQTT. + * If this method is not called, true will be applied as default. + * + * @param enable flag indicate whether distribute this message to MQTT subscribers. + * + * @return builder instance. + */ + enableMqtt(enable: boolean): KiiPushMessageBuilder; + + /** + * Set specific data for GCM subscribers. + * If this method is not called, no specific data is not applied + * and data passed to the constructor would be sent to subscribers. + * + * @param data specific data applied to only GCM subscribers. + * Contents should be JSON Object with only one-level of nesting, + * and only strings in values + * + * @return builder instance. + */ + gcmData(data: { [key: string]: string }): KiiPushMessageBuilder; + + /** + * Set collapse_key for GCM subscribers. + * If this method is not called, no collapse_key is applied. + * For details please refer to GCM document of collapse_key. + * + * @param collapseKey + * + * @return builder instance. + */ + gcmCollapseKey(collapseKey: string): KiiPushMessageBuilder; + + /** + * Set delay_while_idle for GCM subscribers. + * If this method is not called, no delay_while_idle is applied. + * For details please refer to GCM document of delay_while_idle. + * + * @param delayWhileIdle + * + * @return builder instance. + */ + gcmDelayWhileIdle(delayWhileIdle: boolean): KiiPushMessageBuilder; + + /** + * Set time_to_live for GCM subscribers. + * If this method is not called, no time_to_live is applied. + * For details please refer to GCM document of time_to_live. + * + * @param timeToLive + * + * @return builder instance. + */ + gcmTimeToLive(timeToLive: number): KiiPushMessageBuilder; + + /** + * Set restricted_package_name for GCM subscribers. + * If this method is not called, no restricted_package_name is applied. + * For details please refer to GCM document of restricted_package_name. + * + * @param restrictedPackageName + * + * @return builder instance. + */ + gcmRestrictedPackageName(restrictedPackageName: string): KiiPushMessageBuilder; + + /** + * Set specific data for APNS subscribers. + * If this method is not called, no specific data is not applied + * and data passed to the constructor would be sent to subscribers. + * + * @param data specific data applied to only APNS subscribers. + * Contents should be JSON Object with only one-level of nesting, + * and only strings, integers, booleans or doubles in the values. + * + * @return builder instance. + */ + apnsData(data: { [key: string]: string | number | boolean }): KiiPushMessageBuilder; + + /** + * Set alert for APNS subscribers. + * If this method is not called, no alert is applied. + * For details please refer to APNS document of alert. + * + * @param alert alert object + * + * @return builder instance. + */ + apnsAlert(alert: string | APNSAlert): KiiPushMessageBuilder; + + /** + * Set sound for APNS subscribers. + * If this method is not called, no sound is applied. + * For details please refer to APNS document of sound. + * + * @param sound + * + * @return builder instance. + */ + apnsSound(sound: string): KiiPushMessageBuilder; + + /** + * Set badge for APNS subscribers. + * If this method is not called, no badge is applied. + * For details please refer to APNS document of badge. + * + * @param badge + * + * @return builder instance. + */ + apnsBadge(badge: number): KiiPushMessageBuilder; + + /** + * Set content-available for APNS subscribers. + * If this method is not called, no content-available is applied. + * + * @param contentAvailable If 0 or this method is not invoked, + * content-available payload is not delivered. + * Otherwise, content-available=1 payload is delivered. + * + * @return builder instance. + */ + apnsContentAvailable(contentAvailable: number): KiiPushMessageBuilder; + + /** + * Set category for APNS subscribers. + * If this method is not called, no category is applied. + * For details please refer to APNS document of category. + * + * @param category + * + * @return builder instance. + */ + apnsCategory(category: string): KiiPushMessageBuilder; + + /** + * Set specific data for JPush subscribers. + * If this method is not called, no specific data is not applied + * and data passed to the constructor would be sent to subscribers. + * + * @param data specific data applied to only JPush subscribers. + * Contents should be JSON Object with only one-level of nesting, + * and only strings, integers, booleans or doubles in the values. + * + * @return builder instance. + */ + jpushData(data: { [name: string]: string | number | boolean }): KiiPushMessageBuilder; + + /** + * Set specific data for MQTT subscribers. + * If this method is not called, no specific data is not applied + * and data passed to the constructor would be sent to subscribers. + * + * @param data specific data applied to only MQTT subscribers. + * Contents should be JSON Object with only one-level of nesting, + * and only strings in the values. + * + * @return builder instance. + */ + mqttData(data: { [key: string]: string }): KiiPushMessageBuilder; + } + + /** + * Represents a KiiPushSubscription. + */ + export class KiiPushSubscription { + /** + * Subscribe to bucket or topic. + * + * @param target to be subscribed. KiiBucket or KiiTopic instance. + * @param callbacks object contains callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is an Array instance. + *
        + *
      • params[0] is a KiiPushSubscription instance.
      • + *
      • params[1] is the KiiTopic instance to subscribe.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiPushSubscription instance.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var topic = Kii.topicWithName("myAppTopic"); + * var user = KiiUser.getCurrentUser(); + * user.pushSubscription().subscribe(topic, { + * success: function(subscription, topic) { + * // Succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * var topic = Kii.topicWithName("myAppTopic"); + * var user = KiiUser.getCurrentUser(); + * user.pushSubscription().subscribe(topic).then( + * function(params) { + * var subscription = params[0]; + * var topic = params[1]; + * // Succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + subscribe(target: T, callbacks?: { success(subscription: KiiPushSubscription, topic: T): any; failure(error: Error): any; }): Promise<[KiiPushSubscription, T]>; + + /** + * Unsubscribe to bucket or topic. + * + * @param target to be unsubscribed. KiiBucket or KiiTopic instance. + * @param callbacks object contains callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is an Array instance. + *
        + *
      • params[0] is a KiiPushSubscription instance.
      • + *
      • params[1] is the KiiTopic instance to unsubscribe.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiPushSubscription instance.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var topic = Kii.topicWithName("myAppTopic"); + * var user = KiiUser.getCurrentUser(); + * user.pushSubscription().unsubscribe(topic, { + * success: function(subscription, topic) { + * // Succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * var topic = Kii.topicWithName("myAppTopic"); + * var user = KiiUser.getCurrentUser(); + * user.pushSubscription().unsubscribe(topic).then( + * function(params) { + * var subscription = params[0]; + * var topic = params[1]; + * // Succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + unsubscribe(target: T, callbacks?: { success(subscription: KiiPushSubscription, topic: T): any; failure(error: Error): any; }): Promise<[KiiPushSubscription, T]>; + + /** + * Check subscription of bucket, topic. + * + * @param target to check subscription. KiiBucket or KiiTopic instance. + * @param callbacks object contains callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is an Array instance. + *
        + *
      • params[0] is a KiiPushSubscription instance.
      • + *
      • params[1] is the KiiTopic instance to subscribe.
      • + *
      • params[2] is Boolean value. true if subscirbed, otherwise false.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiPushSubscription instance.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var topic = Kii.topicWithName("myAppTopic"); + * var user = KiiUser.getCurrentUser(); + * user.pushSubscription().isSubscribed(topic, { + * success: function(subscription, topic, isSubscribed) { + * // Succeeded. + * if (isSubscribed) { + * // The topic is subscribed by current user. + * } else { + * // The topic is not subscribed by current user. + * } + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * var topic = Kii.topicWithName("myAppTopic"); + * var user = KiiUser.getCurrentUser(); + * user.pushSubscription().isSubscribed(topic).then( + * function(params) { + * // Succeeded. + * var subscription = params[0]; + * var topic = params[1]; + * var isSubscribed = params[2]; + * if (isSubscribed) { + * // The topic is subscribed by current user. + * } else { + * // The topic is not subscribed by current user. + * } + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + isSubscribed(target: T, callbacks?: { success(subscription: KiiPushSubscription, topic: T, isSubscribed: boolean): any; failure(error: Error): any; }): Promise<[KiiPushSubscription, T, boolean]>; + } + + /** + * Represents a KiiQuery object + */ + export class KiiQuery { + /** + * Get the limit of the current query + * + * @return + */ + getLimit(): number; + + /** + * Set the limit of the given query + * + * @param value The desired limit. Must be an integer > 0 + * + * @throws InvalidLimitException + */ + setLimit(value: number): void; + + /** + * Create a KiiQuery object based on a KiiClause + *

    + * By passing null as the ‘clause’ parameter, all objects can be retrieved. + * + * @param clause The KiiClause to be executed with the query + */ + static queryWithClause(clause: KiiClause): KiiQuery; + + /** + * Set the query to sort by a field in descending order + * + * If a sort has already been set, it will be overwritten. + * + * @param field The key that should be used to sort + */ + sortByDesc(field: string): void; + + /** + * Set the query to sort by a field in ascending order + * + * If a sort has already been set, it will be overwritten. + * + * @param field The key that should be used to sort + */ + sortByAsc(field: string): void; + } + + /** + * Represents a server side code entry in KiiCloud. + */ + export class KiiServerCodeEntry { + /** + * Execute this server code entry.
    + * If argument is an empty object or not type of Object, callbacks.failure or reject callback of promise will be called.
    + * + * @param argument pass to the entry of script in the cloud. + * If null is specified, no argument pass to the script. + * @param callbacks called on completion of execution. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is the KiiServerCodeEntry instance which this method was called on.
      • + *
      • params[1] is the passed argument object.
      • + *
      • params[2] is a KiiServerCodeExecResult instance.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiServerCodeEntry instance which this method was called on.
      • + *
      • error.message
      • + *
      • error.argument is passed argument object.
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // Instantiate with the endpoint. + * var entry = Kii.serverCodeEntry("main"); + * + * // Set the custom parameters. + * var arg = {"username":"name_of_my_friend", "password":"password_for_my_friend"}; + * + * // Example of executing the Server Code + * entry.execute(arg, { + * + * success: function(entry, argument, execResult) { + * // do something now that the user is logged in + * }, + * + * failure: function(entry, argument, execResult, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * // Instantiate with the endpoint. + * var entry = Kii.serverCodeEntry("main"); + * + * // Set the custom parameters. + * var arg = {"username":"name_of_my_friend", "password":"password_for_my_friend"}; + * + * // Example of executing the Server Code + * entry.execute(arg).then( + * function(params) { + * var entry = params[0]; + * var argument = params[1]; + * var execResult = params[2]; + * // do something + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + execute(argument: T, callbacks?: { success(entry: KiiServerCodeEntry, argument: T, execResult: KiiServerCodeExecResult): any; failure(entry: KiiServerCodeEntry, argument: T, execResult: KiiServerCodeExecResult, anErrorString: string): any; }): Promise<[KiiServerCodeEntry, T, KiiServerCodeExecResult]>; + + /** + * Get the entryName of this server code entry. + * + * @return entryName. + */ + getEntryName(): string; + } + + /** + * Represents a server side code execution result in KiiCloud. + */ + export class KiiServerCodeExecResult { + /** + * Get calculated number of executed steps. + * + * @return calculated number of executed steps + */ + getExecutedSteps(): number; + + /** + * Get Object returned by server code entry. + * + * @return returned by server code entry. + */ + getReturnedValue(): any; + } + + /** + * Represents a KiiSocialConnect object + */ + export class KiiSocialConnect { + /** + * + * + * @deprecated You don't have to call this method. + * Set up a reference to one of the supported KiiSocialNetworks. + * + * Set up the network. Need to be called before accessing other methods. + *
    Facebook + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    ArgumentValue TypeValueNote
    networkNameNumberKiiSocialNetworkName.FACEBOOKSpecify Facebook
    apiKeyStringnullFacebook does not requires this argument.
    apiSecretStringnullFacebook does not requires this argument.
    extrasObjectnullFacebook does not requires this argument.
    + * + *
    Twitter + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    ArgumentValue TypeValueNote
    networkNameNumberKiiSocialNetworkName.TWITTERSpecify Twitter
    apiKeyStringnullTwitter does not requires this argument.
    apiSecretStringnullTwitter does not requires this argument.
    extrasObjectnullTwitter does not requires this argument.
    + *
    QQ + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    ArgumentValue TypeValueNote
    networkNameNumberKiiSocialNetworkName.QQSpecify QQ
    apiKeyStringnullQQ does not requires this argument.
    apiSecretStringnullQQ does not requires this argument.
    extrasObjectnullQQ does not requires this argument.
    + * + * @param networkName One of the supported KiiSocialNetworkName values + * @param apiKey The SDK key assigned by the social network provider. For details refer to the table above. + * @param apiSecret The SDK secret assigned by the social network provider. For details refer to the table above. + * @param extras Extra options that should be passed to the SNS. For details refer to the table above. + * + * @throws For details refer to the table above + */ + static setupNetwork(networkName: KiiSocialNetworkName, apiKey: string, apiSecret: string, extras: any): void; + + /** + * Log a user into the social network provided + * + * This will initiate the login process for the given network. If user has already linked with the specified social network, + * sign-in with the social network. Otherwise, this will sign-up and create new user authenticated by the specified social network. + * If sign-up successful, the user is cached inside SDK as current user,and accessible via {@link KiiUser.getCurrentUser()}. + * User token and token expiration is also cached and can be get by {@link KiiUser#getAccessTokenObject()}. + * Access token won't be expired unless you set it explicitly by {@link Kii.setAccessTokenExpiration()}. + * The network must already be set up via setupNetwork
    + * If the opitons is invalid, callbacks.failure or reject callback of promise will be called.
    + * + * @param networkName One of the supported KiiSocialNetworkName values + * @param options A dictionary of key/values to pass to KiiSocialConnect + * + *
    Facebook + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    KeyValue typeValueNote
    access_tokenStringAccess token of Facebook.This is mandatory.
    + * + *
    Twitter + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    KeyValue typeValueNote
    oauth_tokenStringOAuth access token of twitter.This is mandatory.
    oauth_token_secretStringOAuth access token secret of twitter.This is mandatory.
    + * + *
    Google + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    KeyValue typeValueNote
    access_tokenStringAccess token of Google.This is mandatory.
    + * + *
    Renren + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    KeyValue typeValueNote
    access_tokenStringAccess token of Renren.This is mandatory.
    + * + *
    QQ + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    KeyValue typeValueNote
    access_tokenStringAccess token of QQ.This is mandatory.
    openIDStringOpenID of QQ.This is mandatory.
    + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is a logged in KiiUser instance.
      • + *
      • params[1] is the KiiSocialNetworkName used to login.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      • error.network is the KiiSocialNetworkName used to login.
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // Example of using no option + * KiiSocialConnect.logIn(KiiSocialNetworkName.FACEBOOK, null, { + * + * success: function(user, network) { + * // do something now that the user is logged in + * }, + * + * failure: function(user, network, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * KiiSocialConnect.logIn(KiiSocialNetworkName.FACEBOOK, null).then( + * function(params) { + * // do something now that the user is logged in + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + static logIn(networkName: KiiSocialNetworkName, options: KiiSocialConnectOptions, callbacks?: { success(user: KiiUser, network: KiiSocialNetworkName): any; failure(user: KiiUser, network: KiiSocialNetworkName, anErrorString: string): any; }): Promise<[KiiUser, KiiSocialNetworkName]>; + + /** + * Link the currently logged in user with a social network + * + * This will initiate the login process for the given network, which for SSO-enabled services like Facebook, will send the user to the Facebook site for authentication. There must be a currently authenticated KiiUser. Otherwise, you can use the logIn: method to create and log in a KiiUser using a network. The network must already be set up via setupNetwork
    + * If there is not logged-in user to link with, callbacks.failure or reject callback of promise will be called.
    + * If the opitons is invalid, callbacks.failure or reject callback of promise will be called.
    + * + * @param networkName One of the supported KiiSocialNetworkName values + * @param options A dictionary of key/values to pass to KiiSocialConnect + *
    Facebook + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    KeyValue typeValueNote
    access_tokenStringAccess token of Facebook.This is mandatory.
    + * + *
    Twitter + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    KeyValue typeValueNote
    oauth_tokenStringOAuth access token of twitter.This is mandatory.
    oauth_token_secretStringOAuth access token secret of twitter.This is mandatory.
    + * + *
    Google + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    KeyValue typeValueNote
    access_tokenStringAccess token of Google.This is mandatory.
    + * + *
    Renren + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    KeyValue typeValueNote
    access_tokenStringAccess token of Renren.This is mandatory.
    + * + *
    QQ + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    KeyValue typeValueNote
    access_tokenStringAccess token of QQ.This is mandatory.
    openIDStringOpenID of QQ.This is mandatory.
    + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is a linked KiiUser instance.
      • + *
      • params[1] is the KiiSocialNetworkName used to link.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is current logged-in KiiUser instance. If there is not logged-in user, it will be null.
      • + *
      • error.message
      • + *
      • error.network is the KiiSocialNetworkName used to link.
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // Example of using no option + * KiiSocialConnect.linkCurrentUserWithNetwork(KiiSocialNetworkName.FACEBOOK, null, { + * + * success: function(user, network) { + * // do something now that the user is linked + * }, + * + * failure: function(user, network, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * // Example of using no option + * KiiSocialConnect.linkCurrentUserWithNetwork(KiiSocialNetworkName.FACEBOOK, null).then( + * function(params) { + * // do something now that the user is linked + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + static linkCurrentUserWithNetwork(networkName: KiiSocialNetworkName, options: KiiSocialConnectOptions, callbacks?: { success(user: KiiUser, network: KiiSocialNetworkName): any; failure(user: KiiUser, network: KiiSocialNetworkName, anErrorString: string): any; }): Promise<[KiiUser, KiiSocialNetworkName]>; + + /** + * Unlink the currently logged in user with a social network + * + * The network must already be set up via setupNetwork + * + * @param networkName One of the supported KiiSocialNetworkName values + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is a unlinked KiiUser instance.
      • + *
      • params[1] is the KiiSocialNetworkName used to unlink.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is current logged-in KiiUser instance. If there is not logged-in user, it will be null.
      • + *
      • error.message
      • + *
      • error.network is the KiiSocialNetworkName used to unlink.
      • + *
      + *
    • + *
    + * + * @example + * + * // example to use callbacks directly + * KiiSocialConnect.unLinkCurrentUserFromNetwork(KiiSocialNetworkName.FACEBOOK, { + * + * success: function(user, network) { + * // do something now that the user is unlinked + * }, + * + * failure: function(user, network, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * KiiSocialConnect.unLinkCurrentUserFromNetwork(KiiSocialNetworkName.FACEBOOK).then( + * function(params) { + * // do something now that the user is unlinked + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + static unLinkCurrentUserFromNetwork(networkName: KiiSocialNetworkName, callbacks?: { success(user: KiiUser, network: KiiSocialNetworkName): any; failure(user: KiiUser, network: KiiSocialNetworkName, anErrorString: string): any; }): Promise<[KiiUser, KiiSocialNetworkName]>; + + /** + * Retrieve the current user's access token from a social network + * The network must be set up and linked to the current user. It is recommended you save this to preferences for multi-session use. + * + * @deprecated Use {@link KiiSocialConnect.getAccessTokenObjectForNetwork} instead. + * + * @param networkName One of the supported KiiSocialNetworkName values + * + * @return The current access token, null if unavailable + */ + static getAccessTokenForNetwork(networkName: KiiSocialNetworkName): string; + + /** + * Retrieve the current user's access token expiration date from a social network + * + * The network must be set up and linked to the current user. It is recommended you save this to preferences for multi-session use. + * + * @deprecated Use {@link KiiSocialConnect.getAccessTokenObjectForNetwork} instead. + * + * @param networkName One of the supported KiiSocialNetworkName values + * + * @return The current access token expiration date, null if unavailable + */ + static getAccessTokenExpirationForNetwork(networkName: KiiSocialNetworkName): string; + + /** + * Retrieve the current user's access token object from a social network + * + * The network must be set up and linked to the current user. + * It is recommended you save this to preferences for multi-session use.

    + * Following parameters can be assigned to object.

    + * Facebook + *
  • access_token
  • + *
  • expires_in
  • + *
  • kii_new_user
  • + *
    + * Twitter + *
  • oauth_token
  • + *
  • oauth_token_secret
  • + *
  • kii_new_user
  • + *
    + * Google + *
  • access_token
  • + *
  • kii_new_user
  • + *
    + * RenRen + *
  • access_token
  • + *
  • kii_new_user
  • + *
    + * QQ + *
  • access_token
  • + *
  • openID
  • + *
  • kii_new_user
  • + * + * @param networkName One of the supported KiiSocialNetworkName values + * + * @return tokenObject The current access token object, null if unavailable. + */ + static getAccessTokenObjectForNetwork(networkName: KiiSocialNetworkName): any; + } + + /** + * Represents a Thing object + */ + export class KiiThing { + /** + * of this thing. + * For details refer to {@link KiiThing.register} + */ + fields: KiiThingFields; + + /** + * Get thing ID. + * + * @return thing id + */ + getThingID(): string; + + /** + * Get vendor thing ID. + * + * @return vendor thing id + */ + getVendorThingID(): string; + + /** + * Get access token of this thing. + * + * @return access token of this thing. + */ + getAccessToken(): string; + + /** + * Get created time of this thing. + * + * @return created time of this thing. + */ + getCreated(): Date; + + /** + * Get disabled status of this thing. + * + * @return true if thing is disabled, false otherwise. + */ + getDisabled(): boolean; + + /** + * Register thing in KiiCloud.
    + * This API doesnt require users login Anonymous user can register thing. + *
    + * Propertis started with '_' in the fields is reserved by Kii Cloud.
    + * Those properties are indexed in Kii Cloud storage.
    + * Properties not started with '_' is custom properties defined by developer.
    + * Custom properties are not indexed in KiiCloud storage.
    + * Following properties are readonly and ignored on creation/{@link #update} of thing.
    + * '_thingID', '_created', '_accessToken'
    + * Following properties are readonly after creation and will be ignored on {@link #update} of thing.
    + * '_vendorThingID', '_password'
    + * + * @param fields of the thing to be registered. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(thing). thing is a KiiThing instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiThing instance.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * KiiThing.register( + * { + * _vendorThingID: "thing-XXXX-YYYY-ZZZZZ", + * _password: "thing-password", + * _thingType: "thermometer", + * yourCustomObj: // Arbitrary key can be used. + * { // Object, Array, Number, String can be used. Should be compatible with JSON. + * yourCustomKey1: "value", + * yourCustomKey2: 100 + * } + * }, + * { + * success: function(thing) { + * // Register Thing succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * } + * ); + * + * // example to use Promise + * KiiThing.register( + * { + * _vendorThingID: "thing-XXXX-YYYY-ZZZZZ", + * _password: "thing-password", + * _thingType: "thermometer", + * yourCustomObj: // Arbitrary key can be used. + * { // Object, Array, Number, String can be used. Should be compatible with JSON. + * yourCustomKey1: "value", + * yourCustomKey2: 100 + * } + * } + * ).then( + * function(thing) { + * // Register Thing succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + static register(fields: KiiThingFields, callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + + /** + * Retrieve the latest thing information from KiiCloud. + *
    This API is authorized by owner of thing. + *
    Need user login who owns this thing before execute this API. + *
    To let users to own thing, please call {@link KiiThing#registerOwner} + *
    Note: if you obtain thing instance from {@link KiiAppAdminContext}, + * API is authorized by app admin.
    + * + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(thing). thing is KiiThing instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiThing instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume thing is already registered. + * thing.refresh({ + * success: function(thing) { + * // Refresh succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume thing is already registered. + * thing.refresh().then( + * function(thing) { + * // Refresh succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + refresh(callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + + /** + * Update registered thing information in Kii Cloud + *
    This API is authorized by owner of thing. + *
    Need user login who owns this thing before execute this API. + *
    To let users to own thing, please call {@link KiiThing#registerOwner} + *
    Note: if you obtain thing instance from {@link KiiAppAdminContext}, + * API is authorized by app admin.
    + * + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(thing). thing is a KiiThing instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiThing instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @see KiiThing.register + * + * @example + * // example to use callbacks directly + * // assume thing is already registered. + * thing.fields._stringField1 = "new string value"; + * thing.fields.customObject = { + * "customField1" : "abcd", + * "customField2" : 123 + * }; + * thing.update({ + * success: function(thing) { + * // Update succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume thing is already registered. + * thing.fields._stringField1 = "new string value"; + * thing.fields.customObject = { + * "customField1" : "abcd", + * "customField2" : 123 + * }; + * thing.update().then( + * function(thing) { + * // Update succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + update(callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + + /** + * Delete registered thing in Kii Cloud. + *
    This API is authorized by owner of thing. + *
    Need user login who owns this thing before execute this API. + *
    To let users to own thing, please call {@link KiiThing#registerOwner} + *
    Note: if you obtain thing instance from {@link KiiAppAdminContext}, + * API is authorized by app admin.
    + * + * It will delete bucket, topic which belongs to this thing, + * entity belongs to the bucket/topic and all ownership information of thing. + * This operation can not be reverted. Please carefully use this. + * + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(thing). thing is a KiiThing instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiThing instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume thing is already registered. + * thing.deleteThing({ + * success: function(thing) { + * // Delete succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume thing is already registered. + * thing.deleteThing().then( + * function(thing) { + * // Delete succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + deleteThing(callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + + /** + * Check if user/ group is owner of the thing. + *
    This API is authorized by owner of thing. + *
    Need user login before execute this API. + *
    To let users to own Thing, please call {@link KiiThing#registerOwner} + *
    Note: if you obtain thing instance from {@link KiiAppAdminContext}, + * API is authorized by app admin.
    + * + * @param owner whether the instance is owner of thing or not. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is an Array instance. + *
        + *
      • params[0] is the KiiThing instance which this method was called on.
      • + *
      • params[1] is a KiiUser/KiiGroup instance.
      • + *
      • params[2] is Boolean value, true is the user/group is owner of the thing, otherwise false.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiThing instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume thing/user is already registered. + * var user = KiiUser.userWithURI("kiicloud://users/xxxyyyy"); + * thing.isOwner(user, { + * success: function(thing, user, isOwner) { + * if (isOwner) { + * // user is owner of the thing. + * } else { + * // user is not owner of the thing. + * } + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume thing/user is already registered. + * var user = KiiUser.userWithURI("kiicloud://users/xxxyyyy"); + * thing.isOwner(user).then( + * function(params) { + * var thing = params[0]; + * var user = params[1]; + * var isOwner = params[2]; + * if (isOwner) { + * // user is owner of the thing. + * } else { + * // user is not owner of the thing. + * } + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + isOwner(owner: T, callbacks?: { success(thing: KiiThing, user: T, isOwner: boolean): any; failure(error: Error): any; }): Promise<[KiiThing, T, boolean]>; + + /** + * Register user/group as owner of this thing. + *
    Need user login before execute this API. + *
    Note: if you obtain thing instance from {@link KiiAppAdminContext}, + * API is authorized by app admin.
    + * + * @param owner to be registered as owner. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is an Array instance. + *
        + *
      • params[0] is the KiiThing instance which this method was called on.
      • + *
      • params[1] is a KiiUser/KiiGroup instance.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiThing instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume thing/group is already registered. + * var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy"); + * thing.registerOwner(group, { + * success: function(thing, group) { + * // Register owner succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume thing/group is already registered. + * var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy"); + * thing.registerOwner(group).then( + * function(params) { + * // Register owner succeeded. + * var thing = params[0]; + * var group = params[1]; + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + registerOwner(owner: T, callbacks?: { success(thing: KiiThing, group: T): any; failure(error: Error): any; }): Promise<[KiiThing, T]>; + + /** + * Register user/group as owner of specified thing. + *
    Need user login before execute this API. + *
    Note: if you obtain thing instance from {@link KiiAppAdminContext}, + * API is authorized by app admin.
    + * + * @param thingID The ID of thing + * @param owner to be registered as owner. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is an Array instance. + *
        + *
      • params[0] is a KiiUser/KiiGroup instance.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume thing/group is already registered. + * var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy"); + * KiiThing.registerOwnerWithThingID("th.xxxx-yyyy-zzzz", group, { + * success: function(group) { + * // Register owner succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume thing/group is already registered. + * var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy"); + * KiiThing.registerOwnerWithThingID("th.xxxx-yyyy-zzzz", group).then( + * function(params) { + * // Register owner succeeded. + * var group = params[0]; + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + static registerOwnerWithThingID(thingID: string, owner: T, callbacks?: { success(group: T): any; failure(error: Error): any; }): Promise; + + /** + * Register user/group as owner of specified thing. + *
    Need user login before execute this API. + *
    Note: if you obtain thing instance from {@link KiiAppAdminContext}, + * API is authorized by app admin.
    + * + * @param vendorThingID The vendor thing ID of thing + * @param owner to be registered as owner. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is an Array instance. + *
        + *
      • params[0] is a KiiUser/KiiGroup instance.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume thing/group is already registered. + * var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy"); + * KiiThing.registerOwnerWithVendorThingID("xxxx-yyyy-zzzz", group, { + * success: function(group) { + * // Register owner succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume thing/group is already registered. + * var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy"); + * KiiThing.registerOwnerWithVendorThingID("xxxx-yyyy-zzzz", group).then( + * function(group) { + * // Register owner succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + static registerOwnerWithVendorThingID(vendorThingID: string, owner: T, callbacks?: { success(group: T): any; failure(error: Error): any; }): Promise; + + /** + * Remove ownership of thing from specified user/group. + *
    This API is authorized by owner of thing. + *
    Need user login who owns this thing before execute this API. + *
    Note: if you obtain thing instance from {@link KiiAppAdminContext}, + * API is authorized by app admin.
    + * + * @param owner to be unregistered. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is an Array instance. + *
        + *
      • params[0] is the KiiThing instance which this method was called on.
      • + *
      • params[1] is a KiiUser/KiiGroup instance which had ownership of the thing removed.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiThing instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume thing/group is already registered. + * var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy"); + * thing.unregisterOwner(group, { + * success: function(thing, group) { + * // Unregister owner succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume thing/group is already registered. + * var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy"); + * thing.unregisterOwner(group).then( + * function(params) { + * // Unregister owner succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + unregisterOwner(owner: T, callbacks?: { success(thing: KiiThing, group: T): any; failure(error: Error): any; }): Promise<[KiiThing, T]>; + + /** + * Disable the thing. + *
    This API is authorized by owner of thing. + *
    Need user login who owns this thing before execute this API. + *
    To let users to own Thing, please call {@link KiiThing#registerOwner} + *
    Note: if you obtain thing instance from {@link KiiAppAdminContext}, + * API is authorized by app admin.
    + * + * After succeeded, access token published for thing is disabled. + * In a result, only the app administrator and owners of thing can access the thing. + * Used when user lost the thing and avoid using by unknown users. + * It doesn't throw error when the thing is already disabled. + * + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(thing). thing is a KiiThing instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiThing instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume thing is already registered. + * thing.disable({ + * success: function(thing) { + * // Disable succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume thing is already registered. + * thing.disable().then( + * function(thing) { + * // Disable succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + disable(callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + + /** + * Enable the thing. + *
    This API is authorized by owner of thing. + *
    Need user login who owns this thing before execute this API. + *
    To let users to own Thing, please call {@link KiiThing#registerOwner} + *
    Note: if you obtain thing instance from {@link KiiAppAdminContext}, + * API is authorized by app admin.
    + * + * After succeeded, If thing is registered with "persistentToken" option, + * token should be recovered (Access token which is used before disabling can be available). + * Otherwise, it does not recovered. + * It doesn't throw error when the thing is already enabled. + * + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(thing). thing is a KiiThing instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiThing instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume thing is already registered. + * thing.enable({ + * success: function(thing) { + * // Enable succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume thing is already registered. + * thing.enable().then( + * function(thing) { + * // Disable succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + enable(callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + + /** + * Load thing with given vendor thing id. + *
    This API is authorized by owner of thing. + *
    Need user login who owns this thing before execute this API. + *
    To let users to own Thing, please call {@link KiiThing#registerOwner} + *
    Note: if you obtain thing instance from {@link KiiAppAdminContext}, + * API is authorized by app admin.
    + * + * @param vendorThingID registered vendor thing id. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(thing). thing is a KiiThing instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * KiiThing.loadWithVendorThingID("thing-xxxx-yyyy",{ + * success: function(thing) { + * // Load succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * KiiThing.loadWithVendorThingID("thing-xxxx-yyyy").then( + * function(thing) { + * // Load succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + static loadWithVendorThingID(vendorThingID: string, callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + + /** + * Load thing with thing id given by Kii Cloud. + *
    This API is authorized by owner of thing. + *
    Need user login who owns this thing before execute this API. + *
    To let users to own Thing, please call {@link KiiThing#registerOwner} + *
    Note: if you obtain thing instance from {@link KiiAppAdminContext}, + * API is authorized by app admin.
    + * + * thing id can be obtained by {@link thingID} + * + * @param thingID registered thing id. + * @param callbacks object holds callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(thing). thing is a KiiThing instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * KiiThing.loadWithThingID("thing-xxxx-yyyy",{ + * success: function(thing) { + * // Load succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * KiiThing.loadWithVendorThingID("thing-xxxx-yyyy").then( + * function(thing) { + * // Load succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + static loadWithThingID(thingID: string, callbacks?: { success(thing: KiiThing): any; failure(error: Error): any; }): Promise; + + /** + * Instantiate bucket belongs to this thing. + * + * @param bucketName name of the bucket. + * + * @return bucket instance. + */ + bucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to a encrypted bucket for this thing + * + *

    The bucket will be created/accessed within this thing's scope + * + * @param bucketName The name of the bucket the user should create/access + * + * @return A working KiiEncryptedBucket object + * + * @example + * var thing = . . .; // a KiiThing + * var bucket = thing.encryptedBucketWithName("myBucket"); + */ + encryptedBucketWithName(bucketName: string): KiiBucket; + + /** + * Instantiate topic belongs to this thing. + * + * @param topicName name of the topic. Must be a not empty string. + * + * @return topic instance. + */ + topicWithName(topicName: string): KiiTopic; + + /** + * Gets a list of topics in this thing scope + * + * @param callbacks An object with callback methods defined + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is array of KiiTopic instances.
      • + *
      • params[1] is string of nextPaginationKey.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiThing instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var thing = . . .; // a KiiThing + * thing.listTopics({ + * success: function(topicList, nextPaginationKey) { + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * thing.listTopics({ + * success: function(topicList, nextPaginationKey) {...}, + * failure: function(anErrorString) {...} + * }, nextPaginationKey); + * } + * }, + * failure: function(anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use promise + * var thing = . . .; // a KiiThing + * thing.listTopics().then( + * function(params) { + * var topicList = params[0]; + * var nextPaginationKey = params[1]; + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * thing.listTopics(null, nextPaginationKey).then( + * function(params) {...}, + * function(error) {...} + * ); + * } + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + + /** + * Instantiate push subscription for this thing. + * + * @return push subscription object. + */ + pushSubscription(): KiiPushSubscription; + } + + /** + * Represents a Topic object. + */ + export class KiiTopic { + /** + * get name of this topic + * + * @return name of this topic. + */ + getName(): string; + + /** + * Checks whether the topic already exists or not. + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(existed). true if the topic exists.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiTopic instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume topic is already instantiated. + * topic.exists({ + * success: function(existed) { + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume topic is already instantiated. + * topic.exists().then( + * function(existed){ + * }, + * function(error){ + * // Handle error. + * }); + */ + exists(callbacks?: { success(existed: boolean): any; failure(error: Error): any; }): Promise; + + /** + * Save this topic on Kii Cloud. + * Note that only app admin can save application scope topic. + * + * @param callbacks callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theSavedTopic). theSavedTopic is a KiiTopic instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiTopic instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume topic is already instantiated. + * topic.save({ + * success: function(topic) { + * // Save topic succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume topic is already instantiated. + * topic.save().then( + * function(topic) { + * // Save topic succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + save(callbacks?: { success(topic: KiiTopic): any; failure(error: Error): any; }): Promise; + + /** + * Send message to the topic. + * + * @param message to be sent. + * @param callbacks callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is an Array instance. + *
        + *
      • params[0] is the KiiTopic instance which this method was called on.
      • + *
      • params[1] is the message object to send.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiTopic instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume topic is already instantiated. + * var contents = { + * message : "hello push!" + * }; + * var message = new KiiPushMessageBuilder(contents).build(); + * topic.sendMessage(message, { + * success: function(topic, message) { + * // Send message succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume topic is already instantiated. + * var contents = { + * message : "hello push!" + * }; + * var message = new KiiPushMessageBuilder(contents).build(); + * topic.sendMessage(message).then( + * function(params) { + * // Send message succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + sendMessage(message: T, callbacks?: { success(topic: KiiTopic, message: T): any; failure(error: Error): any; }): Promise<[KiiTopic, T]>; + + /** + * Delete the topic. + * + * @param callbacks callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theDeletedTopic). theDeletedTopic is a KiiTopic instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiTopic instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // assume topic is already instantiated. + * topic.deleteTopic({ + * success: function(topic) { + * // Delete topic succeeded. + * }, + * failure: function(error) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * // assume topic is already instantiated. + * topic.deleteTopic().then( + * function(topic) { + * // Delete topic succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + deleteTopic(callbacks?: { success(topic: KiiTopic): any; failure(error: Error): any; }): Promise; + + /** + * Get ACL object of this topic. + * Access to topic can be configured by adding/removing KiiACLEntry + * to/from obtained acl object. + * + * @return acl object of this topic. + */ + acl(): KiiACL; + } + + /** + * Represents a KiiUser object + */ + export class KiiUser { + /** + * + * + * @deprecated Use {@link KiiUser.getId} instead. + * Get the UUID of the given user, assigned by the server + * + * @return + */ + getUUID(): string; + + /** + * Get the ID of the current KiiUser instance. + * + * @return Id of the user or null if the user has not saved to cloud. + */ + getID(): string; + + /** + * Get the username of the given user + * + * @return + */ + getUsername(): string; + + /** + * Return true if the user is disabled, false when enabled and undefined + * when user is not refreshed. + * Call {@link KiiUser#refresh()} prior calling this method to get + * correct status. + */ + disabled(): void; + + /** + * Get the display name associated with this user + * + * @return + */ + getDisplayName(): string; + + /** + * Set the display name associated with this user. Cannot be used for logging a user in; is non-unique + * + * @param value Must be between 1-50 alphanumeric characters. + * + * @throws If the displayName is not a valid format + */ + setDisplayName(value: string): void; + + /** + * Get whether or not the user is pseudo user. + * If this method is not called for current login user, calling + * {@link KiiUser#refresh()} method is necessary to get a correct value. + * + * @return whether this user is pseudo user or not. + */ + isPseudoUser(): boolean; + + /** + * Get the email address associated with this user + * + * @return + */ + getEmailAddress(): string; + + /** + * Get the phone number associated with this user + * + * @return + */ + getPhoneNumber(): string; + + /** + * Get the country code associated with this user + * + * @return + */ + getCountry(): string; + + /** + * Set the country code associated with this user + * + * @param value The country code to set. Must be 2 alphabetic characters. Ex: US, JP, CN + * + * @throws If the country code is not a valid format + */ + setCountry(value: string): void; + + /** + * Get the server's creation date of this user + * + * @return + */ + getCreated(): string; + + /** + * + * + * @deprecated Get the modified date of the given user, assigned by the server + * + * @return + */ + getModified(): string; + + /** + * Get the status of the user's email verification. This field is assigned by the server + * + * @return true if the user's email address has been verified by the user, false otherwise. + * Could be undefined if haven't obtained value from server or not allowed to see the value. + * Should be used by current login user to check the email verification status. + */ + getEmailVerified(): boolean; + + /** + * Get the status of the user's phone number verification. This field is assigned by the server + * + * @return true if the user's email address has been verified by the user, false otherwise + * Could be undefined if haven't obtained value from server or not allowed to see the value. + * Should be used by current login user to check the phone verification status. + */ + getPhoneVerified(): boolean; + + /** + * Get the social accounts that is linked to this user. + * Refresh the user by {@link KiiUser#refresh()} prior call the method. + * Otherwise, it returns empty object. + * + * @return Social network name as key and account info as value. + */ + getLinkedSocialAccounts(): { [name: string]: KiiSocialAccountInfo }; + + /** + * Get the access token for the user - only available if the user is currently logged in + * + * @return + */ + getAccessToken(): string; + + /** + * Return the access token and token expire time in a object. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    KeyTypeValue
    "access_token"Stringrequired for accessing KiiCloud
    "expires_at"DateAccess token expiration time, null if the user is not login user.
    + * + * @return Access token and token expires in a object. + */ + getAccessTokenObject(): { access_token: string, expires_at: Date }; + + /** + * Get a specifically formatted string referencing the user + * + *

    The user must exist in the cloud (have a valid UUID). + * + * @return A URI string based on the given user. null if a URI couldn't be generated. + * + * @example + * var user = . . .; // a KiiUser + * var uri = user.objectURI(); + */ + objectURI(): string; + + /** + * Sets a key/value pair to a KiiUser + * + *

    If the key already exists, its value will be written over. If the object is of invalid type, it will return false and a KiiError will be thrown (quietly). Accepted types are any JSON-encodable objects. + * + * @param key The key to set. The key must not be a system key (created, metadata, modified, type, uuid) or begin with an underscore (_) + * @param value The value to be set. Object must be of a JSON-encodable type (Ex: dictionary, array, string, number, etc) + * + * @example + * var user = . . .; // a KiiUser + * user.set("score", 4298); + */ + set(key: string, value: any): void; + + /** + * Gets the value associated with the given key + * + * @param key The key to retrieve + * + * @return The object associated with the key. null if none exists + * + * @example + * var user = . . .; // a KiiUser + * var score = user.get("score"); + */ + get(key: string): T; + + /** + * The currently authenticated user + * + * @return + * + * @example + * var user = KiiUser.getCurrentUser(); + */ + static getCurrentUser(): KiiUser; + + /** + * Create a user object to prepare for registration with credentials pre-filled + * + *

    Creates an pre-filled user object for manipulation. This user will not be authenticated until one of the authentication methods are called on it. It can be treated as any other KiiObject before it is authenticated. + * + * @param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_', dashes '-' and periods '.' + * @param password The user's password. Must be between 4-50 characters, made up of ascii characters excludes control characters. + * + * @return a working KiiUser object + * + * @throws If the username is not in the proper format + * @throws If the password is not in the proper format + * + * @example + * var user = KiiUser.userWithUsername("myusername", "mypassword"); + */ + static userWithUsername(username: string, password: string): KiiUser; + + /** + * Create a user object to prepare for registration with credentials pre-filled + * + *

    Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered. + * + * @param phoneNumber The user's phone number + * @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,& + * + * @return a working KiiUser object + * + * @throws If the password is not in the proper format + * @throws If the phone number is not in the proper format + * + * @example + * var user = KiiUser.userWithPhoneNumber("+874012345678", "mypassword"); + */ + static userWithPhoneNumber(phoneNumber: string, password: string): KiiUser; + + /** + * Create a user object to prepare for registration with credentials pre-filled + * + *

    Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered. + * + * @param phoneNumber The user's phone number + * @param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_', dashes '-' and periods '.' + * @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,& + * + * @return a working KiiUser object + * + * @throws If the username is not in the proper format + * @throws If the password is not in the proper format + * @throws If the phone number is not in the proper format + * + * @example + * var user = KiiUser.userWithPhoneNumberAndUsername("+874012345678", "johndoe", "mypassword"); + */ + static userWithPhoneNumberAndUsername(phoneNumber: string, username: string, password: string): KiiUser; + + /** + * Create a user object to prepare for registration with credentials pre-filled + * + *

    Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered. + * + * @param emailAddress The user's email address + * @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,& + * + * @return a working KiiUser object + * + * @throws If the password is not in the proper format + * @throws If the email address is not in the proper format + * + * @example + * var user = KiiUser.userWithEmailAddress("johndoe@example.com", "mypassword"); + */ + static userWithEmailAddress(emailAddress: string, password: string): KiiUser; + + /** + * Create a user object to prepare for registration with credentials pre-filled + * + *

    Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered. + * + * @param emailAddress The user's email address + * @param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_', dashes '-' and periods '.' + * @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,& + * + * @return a working KiiUser object + * + * @throws If the username is not in the proper format + * @throws If the password is not in the proper format + * @throws If the phone number is not in the proper format + * + * @example + * var user = KiiUser.userWithEmailAddressAndUsername("johndoe@example.com", "johndoe", "mypassword"); + */ + static userWithEmailAddressAndUsername(emailAddress: string, username: string, password: string): KiiUser; + + /** + * Create a user object to prepare for registration with credentials pre-filled + * + *

    Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered. + * + * @param emailAddress The user's email address + * @param phoneNumber The user's phone number + * @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,& + * + * @return a working KiiUser object + * + * @throws If the phone number is not in the proper format + * @throws If the password is not in the proper format + * @throws If the phone number is not in the proper format + * + * @example + * var user = KiiUser.userWithEmailAddressAndPhoneNumber("johndoe@example.com", "+874012345678", "mypassword"); + */ + static userWithEmailAddressAndPhoneNumber(emailAddress: string, phoneNumber: string, password: string): KiiUser; + + /** + * Create a user object to prepare for registration with credentials pre-filled + * + *

    Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered. + * + * @param emailAddress The user's email address + * @param phoneNumber The user's phone number + * @param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_', dashes '-' and periods '.' + * @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,& + * + * @return a working KiiUser object + * + * @throws If the phone number is not in the proper format + * @throws If the phone number is not in the proper format + * @throws If the username is not in the proper format + * @throws If the password is not in the proper format + * + * @example + * var user = KiiUser.userWithCredentials("johndoe@example.com", "+874012345678", "johndoe", "mypassword"); + */ + static userWithCredentials(emailAddress: string, phoneNumber: string, username: string, password: string): KiiUser; + + /** + * Instantiate KiiUser that refers to existing user which has specified ID. + * You have to specify the ID of existing KiiUser. Unlike KiiObject, + * you can not assign ID in the client side.
    + * NOTE: This API does not access to the server. + * After instantiation, call {@link KiiUser#refresh} to fetch the properties. + * + * @param userID ID of the KiiUser to instantiate. + * + * @return instance of KiiUser. + * + * @throws when passed userID is empty or null. + * + * @example + * var user = new KiiUser.userWithID("__USER_ID__"); + */ + static userWithID(userID: string): KiiUser; + + /** + * Generate a new KiiUser based on a given URI + * + * @param uri The URI of the object to be represented + * + * @return A new KiiUser with its parameters filled in from the URI + * + * @throws If the URI is not in the proper format + * + * @example + * var user = new KiiUser.userWithURI("kiicloud://myuri"); + */ + static userWithURI(uri: string): KiiUser; + + /** + * Creates a reference to a bucket for this user + * + *

    The bucket will be created/accessed within this user's scope + * + * @param bucketName The name of the bucket the user should create/access + * + * @return A working KiiBucket object + * + * @example + * var user = . . .; // a KiiUser + * var bucket = user.bucketWithName("myBucket"); + */ + bucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to a encrypted bucket for this user + * + *

    The bucket will be created/accessed within this user's scope + * + * @param bucketName The name of the bucket the user should create/access + * + * @return A working KiiEncryptedBucket object + * + * @example + * var user = . . .; // a KiiUser + * var bucket = user.encryptedBucketWithName("myBucket"); + */ + encryptedBucketWithName(bucketName: string): KiiBucket; + + /** + * Authenticates a user with the server. + * If authentication successful, the user is cached inside SDK as current user,and accessible via + * {@link KiiUser.getCurrentUser()}. + * User token and token expiration is also cached and can be get by {@link KiiUser#getAccessTokenObject()}. + * Access token won't be expired unless you set it explicitly by {@link Kii.setAccessTokenExpiration()}.
    + * If password or userIdentifier is invalid, callbacks.failure or reject callback of promise will be called.
    + * + * @param userIdentifier The username, validated email address, or validated phone number of the user to authenticate + * @param password The password of the user to authenticate + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theAuthenticatedUser). theAuthenticatedUser is KiiUser instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiUser instance.If given password or userIdentifier is invalid, it will be null.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * KiiUser.authenticate("myusername", "mypassword", { + * success: function(theAuthenticatedUser) { + * // do something with the authenticated user + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * KiiUser.authenticate("myusername", "mypassword").then( + * function(theAuthenticatedUser) { + * // do something with the authenticated user + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + static authenticate(userIdentifier: string, password: string, callbacks?: { success(theAuthenticatedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + + /** + * Asynchronously authenticates a user with the server using specified access token. + * This method is non-blocking.

    + * Specified expiresAt won't be used by SDK. IF login successful, + * we set this property so that you can get it later along with token + * by {@link KiiUser#getAccessTokenObject()}.
    + * Also, if successful, the user is cached inside SDK as current user + * and accessible via {@link KiiUser.getCurrentUser()}.
    + * + * Note that, if not specified, token expiration time is not cached + * and set to value equivalant to 275760 years.
    + * + * If the specified token is expired, authenticataiton will be failed. + * Authenticate the user again to renew the token.
    + * + * If expiresAt is invalid, callbacks.failure or reject callback of promise will be called.
    + * + * @param accessToken A valid access token associated with the desired user + * @param callbacks An object with callback methods defined + * @param expiresAt Access token expire time that has received by {@link KiiUser#getAccessTokenObject()}. This param is optional and can be omitted. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theAuthenticatedUser). theAuthenticatedUser is KiiUser instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiUser instance.If expiresAt is invalid, it will be null.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // Assume you stored the object get from KiiUser#getAccessTokenObject() + * // and now accessing by 'tokenObject' var. + * var token = tokenObject["access_token"]; + * var expiresAt = tokenObject["expires_at"]; + * expireDate.setHours(expireDate.getHours() + 24); + * KiiUser.authenticateWithToken(token, { + * success: function(theAuthenticatedUser) { + * // do something with the authenticated user + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }, expiresAt); + * + * // example to use Promise + * // Assume you stored the object get from KiiUser#getAccessTokenObject() + * // and now accessing by 'tokenObject' var. + * var token = tokenObject["access_token"]; + * var expiresAt = tokenObject["expires_at"]; + * expireDate.setHours(expireDate.getHours() + 24); + * KiiUser.authenticateWithToken(token, null, expiresAt).then( + * function(theAuthenticatedUser) { + * // do something with the authenticated user + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + static authenticateWithToken(accessToken: string, callbacks?: { success(theAuthenticatedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }, expiresAt?: Date): Promise; + + /** + * Registers a user with the server + * + *

    The user object must have an associated email/password combination. + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theAuthenticatedUser). theAuthenticatedUser is KiiUser instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiUser instance.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = KiiUser.userWithUsername("myusername", "mypassword"); + * user.register({ + * success: function(theAuthenticatedUser) { + * // do something with the authenticated user + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var user = KiiUser.userWithUsername("myusername", "mypassword"); + * user.register().then( + * function(params) { + * // do something with the authenticated user + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + register(callbacks?: { success(theAuthenticatedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + + /** + * Registers a user as pseudo user with the server + * + * @param callbacks An object with callback methods defined. + * This argument is mandatory and can't be ommited. + * @param userFields Custom Fields to add to the user. This is optional and can be omitted. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theAuthenticatedUser). theAuthenticatedUser is KiiUser instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var userFields = {"displayName":"yourName", "country":"JP", "age":30}; + * KiiUser.registerAsPseudoUser({ + * success: function(theAuthenticatedUser) { + * // do something with the authenticated user + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }, userFields); + * + * // example to use Promise + * var userFields = {"displayName":"yourName", "country":"JP", "age":30}; + * KiiUser.registerAsPseudoUser(null, userFields).then( + * function(theAuthenticatedUser) { + * // do something with the authenticated user + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + static registerAsPseudoUser(callbacks?: { success(theAuthenticatedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }, userFields?: any): Promise; + + /** + * Sets credentials data and custom fields to pseudo user. + * + *

    This method is exclusive to pseudo user. + *
    password is mandatory and needs to provide at least one of login name, email address or phone number. + * + * @param identityData + * @param password The user's password. Valid pattern is ^[\x20-\x7E]{4,50}$. + * @param callbacks An object with callback methods defined. + * This argument is mandatory and can't be ommited. + * @param userFields Custom Fields to add to the user. This is optional and can be omitted. + * @param removeFields An array of field names to remove from the user custom fields. Default fields are not removed from server. + * This is optional and can be omitted. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(user). user is KiiUser instance which this method was called on.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var identityData = { "username": "__USER_NAME_" }; + * var userFields = { "displayName":"__DISPLAY_NAME","score":12344300 }; + * var removeFields = ["age"]; + * user.putIdentity( + * identityData, + * "__PASSWORD__", + * { + * success: function(user) { + * // do something with the updated user. + * }, + * failure: function(user, errorString) { + * // check error response. + * } + * }, + * userFields, + * removeFields + * ); + * + * // example to use Promise + * var identityData = { "username": "__USER_NAME_" }; + * var userFields = { "displayName":"__DISPLAY_NAME","score":12344300 }; + * var removeFields = ["age"]; + * user.putIdentity( + * identityData, + * "__PASSWORD__", + * null, + * userFields, + * removeFields + * ).then( + * function(user) { + * // do something with the updated user. + * }, + * function(error) { + * // check error response. + * } + * ); + */ + putIdentity(identityData: identityData, password: string, callbacks?: { success(user: KiiUser): any; failure(user: KiiUser, errorString: string): any; }, userFields?: any, removeFields?: string[]): Promise; + + /** + * Update user attributes. + * + * + *

    If you want to update identity data of pseudo user, you must use KiiUser.putIdentity instead. + * + * @param identityData + * @param callbacks An object with callback methods defined. + * This argument is mandatory and can't be ommited. + * @param userFields Custom Fields to add to the user. + * @param removeFields An array of field names to remove from the user custom fields. Default fields are not removed from server. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(user). user is KiiUser instance which this method was called on.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiUser instance.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var identityData = { "username": "__USER_NAME_" }; + * var userFields = { "displayName":"__DISPLAY_NAME","score":12344300 }; + * var removeFields = ["age"]; + * user.update( + * identityData, + * { + * success: function(user) { + * // do something with the updated user. + * }, + * failure: function(user, errorString) { + * // check error response. + * } + * }, + * userFields, + * removeFields + * ); + * + * // example to use Promise + * var identityData = { "username": "__USER_NAME_" }; + * var userFields = { "displayName":"__DISPLAY_NAME","score":12344300 }; + * var removeFields = ["age"]; + * user.update( + * identityData, + * null, + * userFields, + * removeFields + * ).then( + * function(user) { + * // do something with the updated user. + * }, + * function(error) { + * // check error response. + * } + * ); + */ + update(identityData: identityData, callbacks?: { success(user: KiiUser): any; failure(user: KiiUser, errorString: string): any; }, userFields?: any, removeFields?: string[]): Promise; + + /** + * Update a user's password on the server + * + *

    Update a user's password with the server. The fromPassword must be equal to the current password associated with the account in order to succeed. + * + * @param fromPassword The user's current password + * @param toPassword The user's desired password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,& + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theUser). theUser is KiiUser instance which this method was called on.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = Kii.currentUser(); + * user.updatePassword("oldpassword", "newpassword", { + * success: function(theUser) { + * // do something + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var user = Kii.currentUser(); + * user.updatePassword("oldpassword", "newpassword").then( + * function(theUser) { + * // do something + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + updatePassword(fromPassword: string, toPassword: string, callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + + /** + * Reset a user's password on the server + * + *

    Reset a user's password on the server. The user is determined by the specified userIdentifier - which is an email address that has already been associated with an account. Reset instructions will be sent to that identifier. + *

    Please Note: This will reset the user's access token, so if they are currently logged in - their session will no longer be valid. + * + * @param userIdentifier The user's email address + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(). No parameter used.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * KiiUser.resetPassword("johndoe@example.com", { + * success: function() { + * // do something + * }, + * + * failure: function(anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * KiiUser.resetPassword("johndoe@example.com").then( + * function() { + * // do something + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + static resetPassword(userIdentifier: string, callbacks?: { success(): any; failure(anErrorString: string): any; }): Promise; + + /** + * Reset the password of user
    + * Reset the password of user specified by given identifier.
    + * This api does not execute login after reset password. + * + * @param userIdentifier should be valid email address, + * global phone number or user identifier obtained by {@link #getID}. + * @param notificationMethod specify the destination of message include link + * of resetting password. must be "EMAIL" or "SMS". + * different type of identifier and destination can be used + * as long as user have verified email, phone. + * (ex. User registers both email and phone. Identifier is email and + * notificationMethod is SMS.) + * @param callbacks object includes callback functions. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(). No parameter used.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * KiiUser.resetPasswordWithNotificationMethod("+819001234567", "SMS", { + * success: function() { + * // Operation succeeded. + * }, + * failure: function(errString) { + * // Handle error. + * } + * }); + * + * // example to use Promise + * KiiUser.resetPasswordWithNotificationMethod("+819001234567", "SMS").then( + * function() { + * // Operation succeeded. + * }, + * function(error) { + * // Handle error. + * } + * ); + */ + static resetPasswordWithNotificationMethod(userIdentifier: string, notificationMethod: string, callbacks?: { success(): any; failure(errString: string): any; }): Promise; + + /** + * Verify the current user's phone number + *

    This method is used to verify the phone number of user currently + * logged in.
    + * Verification code is sent from Kii Cloud when new user is registered with + * phone number or user requested to change their phone number in the + * application which requires phone verification.
    + * (You can enable/disable phone verification through the console in + * developer.kii.com)
    + * After the verification succeeded, new phone number becomes users phone + * number and user is able to login with the phone number.
    + * To get the new phone number, please call {@link #refresh()} and call + * {@link #getPhoneNumber()}
    + * Before completion of {@link #refresh()}, {@link #getPhoneNumber()} returns + * cached phone number. It could be old phone number or undefined. + * + * @param verificationCode The code which verifies the currently logged in user + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theUser). theUser is KiiUser instance which this method was called on.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = Kii.currentUser(); + * user.verifyPhoneNumber("012345", { + * success: function(theUser) { + * // do something + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var user = Kii.currentUser(); + * user.verifyPhoneNumber("012345").then( + * function(theUser) { + * // do something + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + verifyPhoneNumber(verificationCode: string, callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + + /** + * Resend the email verification code to the user + * + *

    This method will re-send the email verification to the currently logged in user + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theUser). theUser is KiiUser instance which this method was called on.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = Kii.currentUser(); + * user.resendEmailVerification({ + * success: function(theUser) { + * // do something + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var user = Kii.currentUser(); + * user.resendEmailVerification().then( + * function(theUser) { + * // do something + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + resendEmailVerification(callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + + /** + * Resend the SMS verification code to the user + * + *

    This method will re-send the SMS verification to the currently logged in user + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theUser). theUser is KiiUser instance which this method was called on.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = Kii.currentUser(); + * user.resendPhoneNumberVerification({ + * success: function(theUser) { + * // do something + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var user = Kii.currentUser(); + * user.resendPhoneNumberVerification().then( + * function(theUser) { + * // do something + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + resendPhoneNumberVerification(callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + + /** + * Retrieve a list of groups which the user is a member of + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is the KiiUser instance which this method was called on.
      • + *
      • params[1] is array of KiiGroup instances.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = Kii.currentUser(); + * user.memberOfGroups({ + * success: function(theUser, groupList) { + * // do something with the results + * for(var i=0; i<groupList.length; i++) { + * var g = groupList[i]; // a KiiGroup object + * } + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var user = Kii.currentUser(); + * user.memberOfGroups().then( + * function(params) { + * // do something with the results + * var theUser = params[0]; + * var groupList = params[1]; + * for(var i=0; i<groupList.length; i++) { + * var g = groupList[i]; // a KiiGroup object + * } + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + memberOfGroups(callbacks?: { success(theUser: KiiUser, groupList: KiiGroup[]): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise<[KiiUser, KiiGroup[]]>; + + /** + * Retrieve the groups owned by this user. Group in the groupList + * does not contain all the property of group. To get all the + * property from cloud, a {@link KiiGroup#refresh(callback)} is necessary. + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is the KiiUser instance which this method was called on.
      • + *
      • params[1] is array of KiiGroup instances.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = Kii.currentUser(); + * user.ownerOfGroups({ + * success: function(theUser, groupList) { + * // do something with the results + * for(var i=0; i<groupList.length; i++) { + * var g = groupList[i]; // a KiiGroup object + * } + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var user = Kii.currentUser(); + * user.ownerOfGroups().then( + * function(params) { + * // do something with the results + * var theUser = params[0]; + * var groupList = params[1]; + * for(var i=0; i<groupList.length; i++) { + * var g = groupList[i]; // a KiiGroup object + * } + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + ownerOfGroups(callbacks?: { success(theUser: KiiUser, groupList: KiiGroup[]): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise<[KiiUser, KiiGroup[]]>; + + /** + * Updates the user's phone number on the server + * + * @param newPhoneNumber The new phone number to change to + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theUser). theUser is KiiUser instance which this method was called on.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = Kii.currentUser(); + * user.changePhone('+19415551234', { + * success: function(theUser) { + * // do something on success + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var user = Kii.currentUser(); + * user.changePhone('+19415551234').then( + * function(theUser) { + * // do something on success + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + changePhone(newPhoneNumber: string, callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + + /** + * Updates the user's email address on the server + * + * @param newEmail The new email address to change to + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theUser). theUser is KiiUser instance which this method was called on.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = Kii.currentUser(); + * user.changeEmail('mynewemail@kii.com', { + * success: function(theUser) { + * // do something on success + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var user = Kii.currentUser(); + * user.changeEmail('mynewemail@kii.com').then( + * function(theUser) { + * // do something on success + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + changeEmail(newEmail: string, callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + + /** + * Saves the latest user values to the server + * + *

    If the user does not yet exist, it will NOT be created. Otherwise, the fields that have changed will be updated accordingly. + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theSavedUser). theSavedUser is KiiUser instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = Kii.getCurrentUser(); // a KiiUser + * user.save({ + * success: function(theSavedUser) { + * // do something with the saved user + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var user = Kii.getCurrentUser(); // a KiiUser + * user.save().then( + * function(theSavedUser) { + * // do something with the saved user + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + save(callbacks?: { success(theSavedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + + /** + * Updates the local user's data with the user data on the server + * + *

    The user must exist on the server. Local data will be overwritten. + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theRefreshedUser). theRefreshedUser is KiiUser instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = Kii.getCurrentUser(); // a KiiUser + * user.refresh({ + * success: function(theRefreshedUser) { + * // do something with the refreshed user + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var user = Kii.getCurrentUser(); // a KiiUser + * user.refresh().then( + * function(theRefreshedUser) { + * // do something with the refreshed user + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + refresh(callbacks?: { success(theRefreshedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + + /** + * Delete the user from the server + * + * @param callbacks An object with callback methods defined + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theDeletedUser). theDeletedUser is KiiUser instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = Kii.getCurrentUser(); // a KiiUser + * user['delete']({ + * success: function(theDeletedUser) { + * // do something + * }, + * + * failure: function(theUser, anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * var user = Kii.getCurrentUser(); // a KiiUser + * user['delete']().then( + * function(theDeletedUser) { + * // do something + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + delete(callbacks?: { success(theDeletedUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; + + /** + * Logs the currently logged-in user out of the KiiSDK + * + * @example + * KiiUser.logOut(); + */ + static logOut(): void; + + /** + * Checks to see if there is a user authenticated with the SDK + * + * @example + * if(KiiUser.loggedIn()) { + * // do something + * } + */ + static loggedIn(): boolean; + + /** + * Find registered KiiUser with the email.
    + * If there are no user registers with the specified email or if there are but not verified email yet, + * callbacks.failure or reject callback of promise will be called.
    + *

    + * Note: + *
      + *
    • If "Expose Full User Data To Others" is enabled in the application console, the response will contain full of the user data.
    • + *
    • Otherwise, the response will only contain "userID", "loginName" and "displayName" field values if exist.
    • + *
    + * + * @param email The email to find KiiUser who owns it.
    + * Don't add prefix of "EMAIL:" described in REST API documentation. SDK will take care of it. + * @param callbacks An object with callback methods defined. + * This argument is mandatory and can't be ommited. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theMatchedUser). theMatchedUser is KiiUser instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * KiiUser.findUserByEmail("user_to_find@example.com", { + * success: function(theMatchedUser) { + * // Do something with the found user + * }, + * failure: function(anErrorString) { + * // Do something with the error response + * } + * }); + * + * // example to use Promise + * KiiUser.findUserByEmail("user_to_find@example.com").then( + * function(theMatchedUser) { + * // Do something with the matched user + * }, + * function(error) { + * // Do something with the error response + * } + * ); + */ + static findUserByEmail(email: string, callbacks?: { success(theMatchedUser: KiiUser): any; failure(anErrorString: string): any; }): Promise; + + /** + * Find registered KiiUser with the phone.
    + * If there are no user registers with the specified phone or if there are but not verified phone yet, + * callbacks.failure or reject callback of promise will be called. + *

    + * Note: + *
      + *
    • If "Expose Full User Data To Others" is enabled in the application console, the response will contain full of the user data.
    • + *
    • Otherwise, the response will only contain "userID", "loginName" and "displayName" field values if exist.
    • + *
    + * + * @param phone The phone number to find KiiUser who owns it.
    + * Don't add prefix of "PHONE:" described in REST API documentation. SDK will take care of it. + * @param callbacks An object with callback methods defined. + * This argument is mandatory and can't be ommited. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theMatchedUser). theMatchedUser is KiiUser instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * KiiUser.findUserByPhone("phone_number_to_find", { + * success: function(theMatchedUser) { + * // Do something with the found user + * }, + * failure: function(anErrorString) { + * // Do something with the error response + * } + * }); + * + * // example to use Promise + * KiiUser.findUserByPhone("phone_number_to_find").then( + * function(theMatchedUser) { + * // Do something with the matched user + * }, + * function(error) { + * // Do something with the error response + * } + * ); + */ + static findUserByPhone(phone: string, callbacks?: { success(theMatchedUser: KiiUser): any; failure(anErrorString: string): any; }): Promise; + + /** + * Find registered KiiUser with the user name.
    + * If there are no user registers with the specified user name, callbacks.failure or reject callback of promise will be called. + *

    + * Note: + *
      + *
    • If "Expose Full User Data To Others" is enabled in the application console, the response will contain full of the user data.
    • + *
    • Otherwise, the response will only contain "userID", "loginName" and "displayName" field values if exist.
    • + *
    + * + * @param username The user name to find KiiUser who owns it.
    + * Don't add prefix of "LOGIN_NAME:" described in REST API documentation. SDK will take care of it. + * @param callbacks An object with callback methods defined. + * This argument is mandatory and can't be ommited. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(theMatchedUser). theMatchedUser is KiiUser instance.
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * KiiUser.findUserByUsername("user_name_to_find", { + * success: function(theMatchedUser) { + * // Do something with the found user + * }, + * failure: function(anErrorString) { + * // Do something with the error response + * } + * }); + * + * // example to use Promise + * KiiUser.findUserByUsername("user_name_to_find").then( + * function(theMatchedUser) { + * // Do something with the matched user + * }, + * function(error) { + * // Do something with the error response + * } + * ); + */ + static findUserByUsername(username: string, callbacks?: { success(theMatchedUser: KiiUser): any; failure(anErrorString: string): any; }): Promise; + + /** + * Instantiate topic belongs to this user. + * + * @param topicName name of the topic. Must be a not empty string. + * + * @return topic instance. + */ + topicWithName(topicName: string): KiiTopic; + + /** + * Gets a list of topics in this user scope + * + * @param callbacks An object with callback methods defined + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is array of KiiTopic instances.
      • + *
      • params[1] is string of nextPaginationKey.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is the KiiUser instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * var user = . . .; // a KiiUser + * user.listTopics({ + * success: function(topicList, nextPaginationKey) { + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * user.listTopics({ + * success: function(topicList, nextPaginationKey) {...}, + * failure: function(anErrorString) {...} + * }, nextPaginationKey); + * } + * }, + * failure: function(anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use callbacks directly + * var user = . . .; // a KiiUser + * user.listTopics().then( + * function(params) { + * var topicList = params[0]; + * var nextPaginationKey = params[1]; + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * user.listTopics(null, nextPaginationKey).then( + * function(params) {...}, + * function(error) {...} + * ); + * } + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + + /** + * Instantiate push subscription for this user. + * + * @return push subscription object. + */ + pushSubscription(): KiiPushSubscription; + } +} + +import KiiACLAction = KiiCloud.KiiACLAction; +import KiiSite = KiiCloud.KiiSite; +import KiiAnalyticsSite = KiiCloud.KiiAnalyticsSite; +import KiiSocialNetworkName = KiiCloud.KiiSocialNetworkName; +import Kii = KiiCloud.Kii; +import KiiACL = KiiCloud.KiiACL; +import KiiACLEntry = KiiCloud.KiiACLEntry; +import KiiAnalytics = KiiCloud.KiiAnalytics; +import KiiAnonymousUser = KiiCloud.KiiAnonymousUser; +import KiiAnyAuthenticatedUser = KiiCloud.KiiAnyAuthenticatedUser; +import KiiAppAdminContext = KiiCloud.KiiAppAdminContext; +import KiiBucket = KiiCloud.KiiBucket; +import KiiClause = KiiCloud.KiiClause; +import KiiGeoPoint = KiiCloud.KiiGeoPoint; +import KiiGroup = KiiCloud.KiiGroup; +import KiiObject = KiiCloud.KiiObject; +import KiiPushMessageBuilder = KiiCloud.KiiPushMessageBuilder; +import KiiPushSubscription = KiiCloud.KiiPushSubscription; +import KiiQuery = KiiCloud.KiiQuery; +import KiiServerCodeEntry = KiiCloud.KiiServerCodeEntry; +import KiiServerCodeExecResult = KiiCloud.KiiServerCodeExecResult; +import KiiSocialConnect = KiiCloud.KiiSocialConnect; +import KiiThing = KiiCloud.KiiThing; +import KiiTopic = KiiCloud.KiiTopic; +import KiiUser = KiiCloud.KiiUser; From a3631563a87205e404e1dccb7b6aec14337793c3 Mon Sep 17 00:00:00 2001 From: bgrieder Date: Wed, 11 Nov 2015 06:42:07 +0100 Subject: [PATCH 80/86] added ActivityIndicatorsIOS --- react-native/react-native.d.ts | 63 +++++++++++++++++++++++++++------- 1 file changed, 50 insertions(+), 13 deletions(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index f3120c004..10cfb50c5 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -5,10 +5,10 @@ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // -// This work is based on an original work made by Bernd Paradies: https://github.com/bparadie -// // These definitions are meant to be used with the TSC compiler target set to ES6 // +// This work is based on an original work made by Bernd Paradies: https://github.com/bparadie +// // WARNING: this work is very much beta: // -it is still missing react-native definitions // -it re-exports the whole of react 0.14 which may not be what react-native actually does @@ -834,10 +834,42 @@ declare namespace ReactNative { /** - * @see + * @see https://facebook.github.io/react-native/docs/activityindicatorios.html#props */ - export interface ActivityIndicatorIOSProperties { - /// TODO + export interface ActivityIndicatorIOSProperties extends React.Props { + + /** + * Whether to show the indicator (true, the default) or hide it (false). + */ + animating?: boolean + + /** + * The foreground color of the spinner (default is gray). + */ + color?: string + + /** + * Whether the indicator should hide when not animating (true by default). + */ + hidesWhenStopped?: boolean + + /** + * Invoked on mount and layout changes with + */ + onLayout?: ( event: {nativeEvent: { layout: {x: number, y: number , width: number, height: number}}} ) => void + + /** + * Size of the indicator. + * Small has a height of 20, large has a height of 36. + * + * enum('small', 'large') + */ + size?: string + + style?: ViewStyle + } + + export interface ActivityIndicatorIOSStatic extends React.ComponentClass { } /** @@ -1470,7 +1502,7 @@ declare namespace ReactNative { /** * @see NavigatorNavigationBar.js */ - export interface NavigationBarProperties extends React.Props{ + export interface NavigationBarProperties extends React.Props { navigator?: Navigator routeMapper?: NavigationBarRouteMapper navState?: NavState @@ -1491,17 +1523,17 @@ declare namespace ReactNative { } export interface BreadcrumbNavigationBarRouteMapper { - rightContentForRoute: (route: Route, navigator: Navigator) => React.ReactElement - titleContentForRoute: (route: Route, navigator: Navigator) => React.ReactElement - iconForRoute: (route: Route, navigator: Navigator) => React.ReactElement + rightContentForRoute: ( route: Route, navigator: Navigator ) => React.ReactElement + titleContentForRoute: ( route: Route, navigator: Navigator ) => React.ReactElement + iconForRoute: ( route: Route, navigator: Navigator ) => React.ReactElement //in samples... - separatorForRoute: (route: Route, navigator: Navigator) => React.ReactElement + separatorForRoute: ( route: Route, navigator: Navigator ) => React.ReactElement } /** * @see NavigatorNavigationBar.js */ - export interface BreadcrumbNavigationBarProperties extends React.Props{ + export interface BreadcrumbNavigationBarProperties extends React.Props { navigator?: Navigator routeMapper?: BreadcrumbNavigationBarRouteMapper navState?: NavState @@ -2084,6 +2116,11 @@ declare namespace ReactNative { // exported singletons: // export var AppRegistry: AppRegistryStatic; + + + export var ActivityIndicatorIOS: ActivityIndicatorIOSStatic; + export type ActivityIndicatorIOS = ActivityIndicatorIOSStatic; + export var AsyncStorage: AsyncStorageStatic; export type AsyncStorage = AsyncStorageStatic; @@ -2141,7 +2178,7 @@ declare namespace ReactNative { export var AlertIOS: React.ComponentClass; export var SegmentedControlIOS: React.ComponentClass; export var SwitchIOS: React.ComponentClass; - export var ActivityIndicatorIOS: React.ComponentClass; + export var PixelRatio: PixelRatioStatic; export var DeviceEventEmitter: DeviceEventEmitterStatic; export var DeviceEventSubscription: DeviceEventSubscriptionStatic; @@ -2399,4 +2436,4 @@ declare module "Dimensions" { declare var global: ReactNative.GlobalStatic -declare function require(name: string): any +declare function require( name: string ): any From 91c74c1cf6a693c7688d8ce41ca602d03aa610ab Mon Sep 17 00:00:00 2001 From: bgrieder Date: Wed, 11 Nov 2015 07:44:36 +0100 Subject: [PATCH 81/86] Added DatePickerIOS + fixes to TextInput + TestModule (minimal) --- react/react-addons-tests.ts | 2875 ++++++++++++++++++++++++++++++----- 1 file changed, 2483 insertions(+), 392 deletions(-) diff --git a/react/react-addons-tests.ts b/react/react-addons-tests.ts index 4d8ed3212..668c7d7d2 100644 --- a/react/react-addons-tests.ts +++ b/react/react-addons-tests.ts @@ -1,415 +1,2506 @@ -/// -import React = require("react/addons"); - -import TestUtils = React.addons.TestUtils; - -interface Props extends React.Props { - hello: string; - world?: string; - foo: number; - bar: boolean; -} - -interface State { - inputValue?: string; - seconds?: number; -} - -interface Context { - someValue?: string; -} - -interface ChildContext { - someOtherValue: string; -} - -interface MyComponent extends React.Component { - reset(): void; -} - -var props: Props = { - key: 42, - ref: "myComponent42", - hello: "world", - foo: 42, - bar: true -}; - -var container: Element; +// Type definitions for react-native 0.14 +// Project: https://github.com/facebook/react-native +// Definitions by: Bruno Grieder +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // -// Top-Level API -// -------------------------------------------------------------------------- +// These definitions are meant to be used with the TSC compiler target set to ES6 +// +// This work is based on an original work made by Bernd Paradies: https://github.com/bparadie +// +// WARNING: this work is very much beta: +// -it is still missing react-native definitions +// -it re-exports the whole of react 0.14 which may not be what react-native actually does +// +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -var ClassicComponent: React.ClassicComponentClass = - React.createClass({ - getDefaultProps: () => { - return { - hello: undefined, - world: "peace", - foo: undefined, - bar: undefined - }; +/// + +import React = __React; + +declare namespace ReactNative { + + + /** + * Represents the completion of an asynchronous operation + * @see lib.es6.d.ts + */ + export interface Promise { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then( onfulfilled?: ( value: T ) => TResult | Promise, onrejected?: ( reason: any ) => TResult | Promise ): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch( onrejected?: ( reason: any ) => T | Promise ): Promise; + + + // not in lib.es6.d.ts but called by react-native + done(): void; + } + + export interface PromiseConstructor { + /** + * A reference to the prototype. + */ + prototype: Promise; + + /** + * Creates a new Promise. + * @param init A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new ( init: ( resolve: ( value?: T | Promise ) => void, reject: ( reason?: any ) => void ) => void ): Promise; + + ( init: ( resolve: ( value?: T | Promise ) => void, reject: ( reason?: any ) => void ) => void ): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all( values: (T | Promise)[] ): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of values. + * @returns A new Promise. + */ + all( values: Promise[] ): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race( values: (T | Promise)[] ): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject( reason: any ): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject( reason: any ): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve( value: T | Promise ): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; + } + + // @see lib.es6.d.ts + export var Promise: PromiseConstructor; + + // node_modules/react-tools/src/classic/class/ReactClass.js + export interface ReactClass { + // TODO: + } + + // see react-jsx.d.ts + export function createElement

    ( type: React.ReactType, + props?: P, + ...children: React.ReactNode[] ): React.ReactElement

    ; + + + export type Runnable = ( appParameters: any ) => void; + + export type AppConfig = { + appKey: string; + component: ReactClass; + run?: Runnable; + } + + // https://github.com/facebook/react-native/blob/master/Libraries/AppRegistry/AppRegistry.js + export class AppRegistry { + static registerConfig( config: AppConfig[] ): void; + + static registerComponent( appKey: string, getComponentFunc: () => React.ComponentClass ): string; + + static registerRunnable( appKey: string, func: Runnable ): string; + + static runApplication( appKey: string, appParameters: any ): void; + } + + /* + export interface ReactPropTypes extends React.ReactPropTypes + { + + } + + export interface PropTypes + { + [key:string]: React.Requireable; + } + */ + + /** + * Flex Prop Types + * @see https://facebook.github.io/react-native/docs/flexbox.html#proptypes + * @see LayoutPropTypes.js + */ + export interface FlexStyle { + + alignItems?: string; //enum('flex-start', 'flex-end', 'center', 'stretch') + alignSelf?: string// enum('auto', 'flex-start', 'flex-end', 'center', 'stretch') + borderBottomWidth?: number + borderLeftWidth?: number + borderRightWidth?: number + borderTopWidth?: number + borderWidth?: number + bottom?: number + flex?: number + flexDirection?: string // enum('row', 'column') + flexWrap?: string // enum('wrap', 'nowrap') + height?: number + justifyContent?: string // enum('flex-start', 'flex-end', 'center', 'space-between', 'space-around') + left?: number + margin?: number + marginBottom?: number + marginHorizontal?: number + marginLeft?: number + marginRight?: number + marginTop?: number + marginVertical?: number + padding?: number + paddingBottom?: number + paddingHorizontal?: number + paddingLeft?: number + paddingRight?: number + paddingTop?: number + paddingVertical?: number + position?: string // enum('absolute', 'relative') + right?: number + top?: number + width?: number + } + + + export interface TransformsStyle { + + transform?: [{perspective: number}, {rotate: string}, {rotateX: string}, {rotateY: string}, {rotateZ: string}, {scale: number}, {scaleX: number}, {scaleY: number}, {translateX: number}, {translateY: number}, {skewX: string}, {skewY: string}] + transformMatrix?: Array + rotation?: number + scaleX?: number + scaleY?: number + translateX?: number + translateY?: number + + } + + + export interface StyleSheetProperties { + // TODO: + } + + export interface LayoutRectangle { + x: number; + y: number; + width: number; + height: number; + } + + // @see TextProperties.onLayout + export interface LayoutChangeEvent { + nativeEvent: { + layout: LayoutRectangle + } + } + + // @see https://facebook.github.io/react-native/docs/text.html#style + export interface TextStyle extends FlexStyle { + color?: string; + containerBackgroundColor?: string; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; // 'normal' | 'italic'; + fontWeight?: string; // enum("normal", 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900') + letterSpacing?: number; + lineHeight?: number; + textAlign?: string; // enum("auto", 'left', 'right', 'center') + writingDirection?: string; //enum("auto", 'ltr', 'rtl') + } + + // https://facebook.github.io/react-native/docs/text.html#props + export interface TextProperties extends React.Props { + /** + * numberOfLines number + * + * Used to truncate the text with an elipsis after computing the text layout, including line wrapping, such that the total number of lines does not exceed this number. + */ + numberOfLines?: number; + + /** + * onLayout function + * + * Invoked on mount and layout changes with + * + * {nativeEvent: { layout: {x, y, width, height}}}. + */ + onLayout?: ( event: LayoutChangeEvent ) => void; + + /** + * onPress function + * + * This function is called on press. Text intrinsically supports press handling with a default highlight state (which can be disabled with suppressHighlighting). + */ + onPress?: () => void; + + /** + * @see https://facebook.github.io/react-native/docs/text.html#style + */ + style?: TextStyle; + } + + export interface TextStatic extends React.ComponentClass { + + } + + + /** + * IOS Specific properties for TextInput + * @see https://facebook.github.io/react-native/docs/textinput.html#props + */ + export interface TextInputIOSProperties { + + /** + * If true, the text field will blur when submitted. + * The default value is true. + */ + blurOnSubmit?: boolean + + /** + * enum('never', 'while-editing', 'unless-editing', 'always') + * When the clear button should appear on the right side of the text view + */ + clearButtonMode?: string + + /** + * If true, clears the text field automatically when editing begins + */ + clearTextOnFocus?: boolean + + /** + * If true, the keyboard disables the return key when there is no text and automatically enables it when there is text. + * The default value is false. + */ + enablesReturnKeyAutomatically?: boolean + + /** + * Callback that is called when a key is pressed. + * Pressed key value is passed as an argument to the callback handler. + * Fires before onChange callbacks. + */ + onKeyPress?: () => void + + /** + * enum('default', 'go', 'google', 'join', 'next', 'route', 'search', 'send', 'yahoo', 'done', 'emergency-call') + * Determines how the return key should look. + */ + returnKeyType?: string + + /** + * If true, all text will automatically be selected on focus + */ + selectTextOnFocus?: boolean + + /** + * //FIXME: require typing + * See DocumentSelectionState.js, some state that is responsible for maintaining selection information for a document + */ + selectionState?: any + + + } + + /** + * Android Specific properties for TextInput + * @see https://facebook.github.io/react-native/docs/textinput.html#props + */ + export interface TextInputAndroidProperties { + + /** + * Sets the number of lines for a TextInput. + * Use it with multiline set to true to be able to fill the lines. + */ + numberOfLines?: number + + /** + * enum('start', 'center', 'end') + * Set the position of the cursor from where editing will begin. + */ + textAlign?: string + + /** + * enum('top', 'center', 'bottom') + * Aligns text vertically within the TextInput. + */ + textAlignVertical?: string + + /** + * The color of the textInput underline. + */ + underlineColorAndroid?: string + } + + + /** + * @see https://facebook.github.io/react-native/docs/textinput.html#props + */ + export interface TextInputProperties extends TextInputIOSProperties, TextInputAndroidProperties, React.Props { + + /** + * Can tell TextInput to automatically capitalize certain characters. + * characters: all characters, + * words: first letter of each word + * sentences: first letter of each sentence (default) + * none: don't auto capitalize anything + * + * https://facebook.github.io/react-native/docs/textinput.html#autocapitalize + */ + autoCapitalize?: string + + /** + * If false, disables auto-correct. + * The default value is true. + */ + autoCorrect?: boolean + + /** + * If true, focuses the input on componentDidMount. + * The default value is false. + */ + autoFocus?: boolean + + /** + * Provides an initial value that will change when the user starts typing. + * Useful for simple use-cases where you don't want to deal with listening to events + * and updating the value prop to keep the controlled state in sync. + */ + defaultValue?: string + + /** + * If false, text is not editable. The default value is true. + */ + editable?: boolean + + /** + * enum("default", 'numeric', 'email-address', "ascii-capable", 'numbers-and-punctuation', 'url', 'number-pad', 'phone-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search') + * Determines which keyboard to open, e.g.numeric. + * The following values work across platforms: - default - numeric - email-address + */ + keyboardType?: string + + /** + * Limits the maximum number of characters that can be entered. + * Use this instead of implementing the logic in JS to avoid flicker. + */ + maxLength?: number + + /** + * If true, the text input can be multiple lines. The default value is false. + */ + multiline?: boolean + + /** + * Callback that is called when the text input is blurred + */ + onBlur?: () => void + + /** + * Callback that is called when the text input's text changes. + */ + onChange?: (event: {nativeEvent: {text: string}}) => void + + /** + * Callback that is called when the text input's text changes. + * Changed text is passed as an argument to the callback handler. + */ + onChangeText?: ( text: string ) => void + + /** + * Callback that is called when text input ends. + */ + onEndEditing?: (event: {nativeEvent: {text: string}}) => void + + /** + * Callback that is called when the text input is focused + */ + onFocus?: () => void + + /** + * Invoked on mount and layout changes with {x, y, width, height}. + */ + onLayout?: (event: {nativeEvent: {x: number, y: number, width: number, height: number}}) => void + + /** + * Callback that is called when the text input's submit button is pressed. + */ + onSubmitEditing?: (event: {nativeEvent: {text: string}}) => void + + /** + * The string that will be rendered before text input has been entered + */ + placeholder?: string + + /** + * The text color of the placeholder string + */ + placeholderTextColor?: string + + /** + * If true, the text input obscures the text entered so that sensitive text like passwords stay secure. + * The default value is false. + */ + secureTextEntry?: boolean + + /** + * Styles + */ + style?: TextStyle + + /** + * Used to locate this view in end-to-end tests + */ + testID?: string + + /** + * The value to show for the text input. TextInput is a controlled component, + * which means the native value will be forced to match this value prop if provided. + * For most uses this works great, but in some cases this may cause flickering - one common cause is preventing edits by keeping value the same. + * In addition to simply setting the same value, either set editable={false}, + * or set/update maxLength to prevent unwanted edits without flicker. + */ + value?: string + } + + export interface TextInputStatic extends React.ComponentClass { + + } + + export interface AccessibilityTraits { + // TODO + } + + // @see https://facebook.github.io/react-native/docs/view.html#style + export interface ViewStyle extends FlexStyle, TransformsStyle { + backgroundColor?: string; + borderBottomColor?: string; + borderBottomLeftRadius?: number; + borderBottomRightRadius?: number; + borderColor?: string; + borderLeftColor?: string; + borderRadius?: number; + borderRightColor?: string; + borderTopColor?: string; + borderTopLeftRadius?: number; + borderTopRightRadius?: number; + opacity?: number; + overflow?: string; // enum('visible', 'hidden') + shadowColor?: string; + shadowOffset?: {width: number, height: number}; + shadowOpacity?: number; + shadowRadius?: number; + } + + /** + * @see https://facebook.github.io/react-native/docs/view.html#props + */ + export interface ViewProperties extends React.Props { + /** + * accessibilityLabel string + * + * Overrides the text that's read by the screen reader when the user interacts with the element. By default, the label is constructed by traversing all the children and accumulating all the Text nodes separated by space. + * + */ + + accessibilityLabel?: string; + + + /** + * accessibilityTraits AccessibilityTraits, [AccessibilityTraits] + * Provides additional traits to screen reader. By default no traits are provided unless specified otherwise in element + */ + + accessibilityTraits?: AccessibilityTraits; + + /** + * accessible bool + * + * When true, indicates that the view is an accessibility element. By default, all the touchable elements are accessible. + */ + + accessible?: boolean; + + /** + * onAcccessibilityTap function + * When accessible is true, the system will try to invoke this function when the user performs accessibility tap gesture. + * + */ + + onAcccessibilityTap?: () => void; + + /** + * onLayout function + * + * Invoked on mount and layout changes with + * + * {nativeEvent: { layout: {x, y, width, height}}}. + */ + onLayout?: ( event: LayoutChangeEvent ) => void; + + /** + * onMagicTap function + * + * When accessible is true, the system will invoke this function when the user performs the magic tap gesture. + */ + + onMagicTap?: () => void; + + /** + * onMoveShouldSetResponder function + * + * For most touch interactions, you'll simply want to wrap your component in TouchableHighlight or TouchableOpacity. Check out Touchable.js, ScrollResponder.js and ResponderEventPlugin.js for more discussion. + */ + onMoveShouldSetResponder?: () => void; + + onResponderGrant?: () => void; + + onResponderMove?: () => void; + + onResponderReject?: () => void; + + onResponderRelease?: () => void; + + onResponderTerminate?: () => void; + + onResponderTerminationRequest?: () => void; + + onStartShouldSetResponder?: () => void; + + onStartShouldSetResponderCapture?: () => void; + + /** + * pointerEvents enum('box-none', 'none', 'box-only', 'auto') + * + * In the absence of auto property, none is much like CSS's none value. box-none is as if you had applied the CSS class: + * + * .box-none { + * pointer-events: none; + * } + * .box-none * { + * pointer-events: all; + * } + * + * box-only is the equivalent of + * + * .box-only { + * pointer-events: all; + * } + * .box-only * { + * pointer-events: none; + * } + * + * But since pointerEvents does not affect layout/appearance, and we are already deviating from the spec by adding additional modes, + * we opt to not include pointerEvents on style. On some platforms, we would need to implement it as a className anyways. Using style or not is an implementation detail of the platform. + */ + + pointerEvents?: string; + + /** + * removeClippedSubviews bool + * + * This is a special performance property exposed by RCTView and is useful for scrolling content when there are many subviews, + * most of which are offscreen. For this property to be effective, it must be applied to a view that contains many subviews that extend outside its bound. + * The subviews must also have overflow: hidden, as should the containing view (or one of its superviews). + */ + + removeClippedSubviews?: boolean + + /** + * renderToHardwareTextureAndroid bool + * + * Whether this view should render itself (and all of its children) into a single hardware texture on the GPU. + * + * On Android, this is useful for animations and interactions that only modify opacity, rotation, translation, and/or scale: + * in those cases, the view doesn't have to be redrawn and display lists don't need to be re-executed. The texture can just be + * re-used and re-composited with different parameters. The downside is that this can use up limited video memory, so this prop should be set back to false at the end of the interaction/animation. + */ + + renderToHardwareTextureAndroid?: boolean; + + style?: ViewStyle; + + /** + * testID string + * + * Used to locate this view in end-to-end tests. + */ + + testID?: string; + } + + export interface ViewStatic extends React.ComponentClass { + + } + + /** + * @see https://facebook.github.io/react-native/docs/activityindicatorios.html#props + */ + export interface AlertIOSProperties { + /** + * animating bool + * + * Whether to show the indicator (true, the default) or hide it (false). + */ + animating?: boolean; + + /** + * color string + * + * The foreground color of the spinner (default is gray). + */ + + color?: string; + + /** + * hidesWhenStopped bool + * + * Whether the indicator should hide when not animating (true by default). + */ + + hidesWhenStopped?: boolean; + + /** + * onLayout function + * + * Invoked on mount and layout changes with + * + * {nativeEvent: { layout: {x, y, width, height}}}. + */ + onLayout?: ( event: LayoutChangeEvent ) => void; + + /** + * size enum('small', 'large') + * + * Size of the indicator. Small has a height of 20, large has a height of 36. + */ + size: string; // enum('small', 'large') + } + + /** + * @see + */ + export interface SegmentedControlIOSProperties { + /// TODO + } + + /** + * @see + */ + export interface SwitchIOSProperties { + /// TODO + } + + + export interface NavigatorIOSProperties extends React.Props { + + /** + * NavigatorIOS uses "route" objects to identify child views, their props, and navigation bar configuration. + * "push" and all the other navigation operations expect routes to be like this + */ + initialRoute?: Route + + /** + * The default wrapper style for components in the navigator. + * A common use case is to set the backgroundColor for every page + */ + itemWrapperStyle?: ViewStyle + + /** + * A Boolean value that indicates whether the navigation bar is hidden + */ + navigationBarHidden?: boolean + + /** + * A Boolean value that indicates whether to hide the 1px hairline shadow + */ + shadowHidden?: boolean + + /** + * The color used for buttons in the navigation bar + */ + tintColor?: string + + /** + * The text color of the navigation bar title + */ + titleTextColor?: string + + /** + * A Boolean value that indicates whether the navigation bar is translucent + */ + translucent?: boolean + + /** + * NOT IN THE DOC BUT IN THE EXAMPLES + */ + style?: ViewStyle + } + + /** + * A navigator is an object of navigation functions that a view can call. + * It is passed as a prop to any component rendered by NavigatorIOS. + * + * Navigator functions are also available on the NavigatorIOS component: + * + * @see https://facebook.github.io/react-native/docs/navigatorios.html#navigator + */ + export interface NavigationIOS { + /** + * Navigate forward to a new route + */ + push: ( route: Route ) => void + + /** + * Go back one page + */ + pop: () => void + + /** + * Go back N pages at once. When N=1, behavior matches pop() + */ + popN: ( n: number ) => void + + /** + * Replace the route for the current page and immediately load the view for the new route + */ + replace: ( route: Route ) => void + + /** + * Replace the route/view for the previous page + */ + replacePrevious: ( route: Route ) => void + + /** + * Replaces the previous route/view and transitions back to it + */ + replacePreviousAndPop: ( route: Route ) => void + + /** + * Replaces the top item and popToTop + */ + resetTo: ( route: Route ) => void + + /** + * Go back to the item for a particular route object + */ + popToRoute( route: Route ): void + + /** + * Go back to the top item + */ + popToTop(): void + } + + export interface NavigatorIOSStatic extends NavigationIOS, React.ComponentClass { + } + + + /** + * @see https://facebook.github.io/react-native/docs/activityindicatorios.html#props + */ + export interface ActivityIndicatorIOSProperties extends React.Props { + + /** + * Whether to show the indicator (true, the default) or hide it (false). + */ + animating?: boolean + + /** + * The foreground color of the spinner (default is gray). + */ + color?: string + + /** + * Whether the indicator should hide when not animating (true by default). + */ + hidesWhenStopped?: boolean + + /** + * Invoked on mount and layout changes with + */ + onLayout?: ( event: {nativeEvent: { layout: {x: number, y: number , width: number, height: number}}} ) => void + + /** + * Size of the indicator. + * Small has a height of 20, large has a height of 36. + * + * enum('small', 'large') + */ + size?: string + + style?: ViewStyle + } + + export interface ActivityIndicatorIOSStatic extends React.ComponentClass { + } + + + export interface DatePickerIOSProperties extends React.Props { + + /** + * The currently selected date. + */ + date?: Date + + + /** + * Maximum date. + * Restricts the range of possible date/time values. + */ + maximumDate?: Date + + /** + * Maximum date. + * Restricts the range of possible date/time values. + */ + minimumDate?: Date + + /** + * enum(1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30) + * The interval at which minutes can be selected. + */ + minuteInterval?: number + + /** + * enum('date', 'time', 'datetime') + * The date picker mode. + */ + mode?: string + + /** + * Date change handler. + * This is called when the user changes the date or time in the UI. + * The first and only argument is a Date object representing the new date and time. + */ + onDateChange?: (newDate: Date) => void + + /** + * Timezone offset in minutes. + * By default, the date picker will use the device's timezone. With this parameter, it is possible to force a certain timezone offset. + * For instance, to show times in Pacific Standard Time, pass -7 * 60. + */ + timeZoneOffsetInMinutes?: number + + } + + export interface DatePickerIOSStatic extends React.ComponentClass { + } + + /** + * @see https://facebook.github.io/react-native/docs/sliderios.html + */ + export interface SliderIOSProperties extends React.Props { + /** + maximumTrackTintColor string + The color used for the track to the right of the button. Overrides the default blue gradient image. + */ + maximumTrackTintColor?: string; + + /** + maximumValue number + + Initial maximum value of the slider. Default value is 1. + */ + maximumValue?: number; + + /** + minimumTrackTintColor string + The color used for the track to the left of the button. Overrides the default blue gradient image. + */ + minimumTrackTintColor?: string; + + /** + minimumValue number + Initial minimum value of the slider. Default value is 0. + */ + minimumValue?: number; + + /** + onSlidingComplete function + Callback called when the user finishes changing the value (e.g. when the slider is released). + */ + onSlidingComplete?: () => void; + + /** + onValueChange function + Callback continuously called while the user is dragging the slider. + */ + onValueChange?: ( value: number ) => void; + + /** + value number + Initial value of the slider. The value should be between minimumValue and maximumValue, which default to 0 and 1 respectively. Default value is 0. + + This is not a controlled component, e.g. if you don't update the value, the component won't be reset to its inital value. + */ + value?: number; + } + + export interface SliderIOSStatic extends React.ComponentClass { + + } + + /** + * @see + */ + export interface CameraRollProperties { + /// TODO + } + + /** + * Image style + * @see https://facebook.github.io/react-native/docs/image.html#style + */ + export interface ImageStyle extends FlexStyle { + color?: string; + containerBackgroundColor?: string; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; // 'normal' | 'italic'; + fontWeight?: string; // enum("normal", 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900') + letterSpacing?: number; + lineHeight?: number; + textAlign?: string; // enum("auto", 'left', 'right', 'center') + writingDirection?: string; //enum("auto", 'ltr', 'rtl') + } + + /** + * @see https://facebook.github.io/react-native/docs/image.html + */ + export interface ImageProperties extends React.Props { + /** + * onLayout function + * + * Invoked on mount and layout changes with + * + * {nativeEvent: { layout: {x, y, width, height}}}. + */ + onLayout?: ( event: LayoutChangeEvent ) => void; + + + /** + * Determines how to resize the image when the frame doesn't match the raw image dimensions. + */ + resizeMode?: string; // enum('cover', 'contain', 'stretch') + + /** + * uri is a string representing the resource identifier for the image, + * which could be an http address, a local file path, + * or the name of a static image resource (which should be wrapped in the require('image!name') function). + */ + source: {uri: string} | string; + + /** + * + * Style + */ + style?: ImageStyle; + + /** + * A unique identifier for this element to be used in UI Automation testing scripts. + */ + testID?: string; + + /** + * The text that's read by the screen reader when the user interacts with the image. + */ + iosaccessibilityLabel?: string; + + /** + * When true, indicates the image is an accessibility element. + */ + iosaccessible?: boolean; + + /** + * When the image is resized, the corners of the size specified by capInsets will stay a fixed size, + * but the center content and borders of the image will be stretched. + * This is useful for creating resizable rounded buttons, shadows, and other resizable assets. + * More info on Apple documentation + */ + ioscapInsets?: {top: number, left: number, bottom: number, right: number} + + /** + * A static image to display while downloading the final image off the network. + */ + iosdefaultSource?: {uri: string} + + /** + * Invoked on load error with {nativeEvent: {error}} + */ + iosonError?: ( error: {nativeEvent: any} ) => void + + /** + * Invoked when load completes successfully + */ + iosonLoad?: () => void + + /** + * Invoked when load either succeeds or fails + */ + iosonLoadEnd?: () => void + + /** + * Invoked on load start + */ + iosonLoadStart?: () => void + + /** + * Invoked on download progress with {nativeEvent: {loaded, total}} + */ + iosonProgress?: ()=> void + } + + /** + * @see https://facebook.github.io/react-native/docs/listview.html#props + */ + export interface ListViewProperties extends ScrollViewProperties, React.Props { + + dataSource?: ListViewDataSource + + /** + * How many rows to render on initial component mount. Use this to make + * it so that the first screen worth of data apears at one time instead of + * over the course of multiple frames. + */ + initialListSize?: number + + /** + * (visibleRows, changedRows) => void + * + * Called when the set of visible rows changes. `visibleRows` maps + * { sectionID: { rowID: true }} for all the visible rows, and + * `changedRows` maps { sectionID: { rowID: true | false }} for the rows + * that have changed their visibility, with true indicating visible, and + * false indicating the view has moved out of view. + */ + onChangeVisibleRows?: ( visibleRows: Array<{[sectionId: string]: {[rowID: string]: boolean}}>, changedRows: Array<{[sectionId: string]: {[rowID: string]: boolean}}> ) => void + + /** + * Called when all rows have been rendered and the list has been scrolled + * to within onEndReachedThreshold of the bottom. The native scroll + * event is provided. + */ + onEndReached?: () => void + + /** + * Threshold in pixels for onEndReached. + */ + onEndReachedThreshold?: number + + /** + * Number of rows to render per event loop. + */ + pageSize?: number + + /** + * An experimental performance optimization for improving scroll perf of + * large lists, used in conjunction with overflow: 'hidden' on the row + * containers. Use at your own risk. + */ + removeClippedSubviews?: boolean + + /** + * () => renderable + * + * The header and footer are always rendered (if these props are provided) + * on every render pass. If they are expensive to re-render, wrap them + * in StaticContainer or other mechanism as appropriate. Footer is always + * at the bottom of the list, and header at the top, on every render pass. + */ + renderFooter?: () => React.ReactElement + + /** + * () => renderable + * + * The header and footer are always rendered (if these props are provided) + * on every render pass. If they are expensive to re-render, wrap them + * in StaticContainer or other mechanism as appropriate. Footer is always + * at the bottom of the list, and header at the top, on every render pass. + */ + renderHeader?: () => React.ReactElement + + /** + * (rowData, sectionID, rowID) => renderable + * Takes a data entry from the data source and its ids and should return + * a renderable component to be rendered as the row. By default the data + * is exactly what was put into the data source, but it's also possible to + * provide custom extractors. + */ + renderRow?: ( rowData: any, sectionID: string, rowID: string, highlightRow?: boolean ) => React.ReactElement + + + /** + * A function that returns the scrollable component in which the list rows are rendered. + * Defaults to returning a ScrollView with the given props. + */ + renderScrollComponent?: ( props: ScrollViewProperties ) => React.ReactElement + + /** + * (sectionData, sectionID) => renderable + * + * If provided, a sticky header is rendered for this section. The sticky + * behavior means that it will scroll with the content at the top of the + * section until it reaches the top of the screen, at which point it will + * stick to the top until it is pushed off the screen by the next section + * header. + */ + renderSectionHeader?: ( sectionData: any, sectionId: string ) => React.ReactElement + + + /** + * (sectionID, rowID, adjacentRowHighlighted) => renderable + * If provided, a renderable component to be rendered as the separator below each row + * but not the last row if there is a section header below. + * Take a sectionID and rowID of the row above and whether its adjacent row is highlighted. + */ + renderSeparator?: ( sectionID: string, rowID: string, adjacentRowHighlighted?: boolean ) => React.ReactElement + + /** + * How early to start rendering rows before they come on screen, in + * pixels. + */ + scrollRenderAheadDistance?: number + } + + export interface ListViewStatic extends React.ComponentClass { + DataSource: ListViewDataSource; + } + + + /** + * @see https://facebook.github.io/react-native/docs/touchablewithoutfeedback.html + */ + export interface TouchableWithoutFeedbackProperties { + /* + accessible bool + + Called when the touch is released, but not if cancelled (e.g. by a scroll that steals the responder lock). + */ + accessible?: boolean; + /* + delayLongPress number + + Delay in ms, from onPressIn, before onLongPress is called. + */ + delayLongPress?: number; + + /* + delayPressIn number + + Delay in ms, from the start of the touch, before onPressIn is called. + */ + delayPressIn?: number; + + /* + delayPressOut number + + Delay in ms, from the release of the touch, before onPressOut is called. + */ + delayPressOut?: number; + + /* + onLongPress function + */ + onLongPress?: () => void; + + /* + onPress function + */ + onPress?: () => void; + + /* + onPressIn function + */ + onPressIn?: () => void; + + /* + onPressOut function + */ + onPressOut?: () => void; + } + + + export interface TouchableWithoutFeedbackProps extends TouchableWithoutFeedbackProperties, React.Props { + + } + + export interface TouchableWithoutFeedbackStatic extends React.ComponentClass { + + } + + + /** + * @see https://facebook.github.io/react-native/docs/touchablehighlight.html#props + */ + export interface TouchableHighlightProperties extends TouchableWithoutFeedbackProperties, React.Props { + /** + * activeOpacity number + * + * Determines what the opacity of the wrapped view should be when touch is active. + */ + activeOpacity?: number + + /** + * onHideUnderlay function + * + * Called immediately after the underlay is hidden + */ + + onHideUnderlay?: () => void + + + /** + * onShowUnderlay function + * + * Called immediately after the underlay is shown + */ + onShowUnderlay?: () => void + + /** + * @see https://facebook.github.io/react-native/docs/view.html#style + */ + style?: ViewStyle + + + /** + * underlayColor string + * + * The color of the underlay that will show through when the touch is active. + */ + underlayColor?: string + + } + + export interface TouchableHighlightStatic extends React.ComponentClass { + } + + + /** + * @see https://facebook.github.io/react-native/docs/touchableopacity.html#props + */ + export interface TouchableOpacityProperties extends TouchableWithoutFeedbackProperties, React.Props { + /** + * activeOpacity number + * + * Determines what the opacity of the wrapped view should be when touch is active. + */ + activeOpacity?: number; + } + + export interface TouchableOpacityStatic extends React.ComponentClass { + } + + + export interface LeftToRightGesture { + + } + + export interface AnimationInterpolator { + + } + + // see /NavigatorSceneConfigs.js + export interface SceneConfig { + // A list of all gestures that are enabled on this scene + gestures: { + pop: LeftToRightGesture, }, - getInitialState: () => { - return { - inputValue: this.context.someValue, - seconds: this.props.foo - }; - }, - // NOTE https://github.com/borisyankov/DefinitelyTyped/pull/5590 - // reset: () => { - // this.replaceState(this.getInitialState()); - // }, - render: () => { - return React.DOM.div(null, - React.DOM.input({ - ref: input => this._input = input, - value: this.state.inputValue - })); + + // Rebound spring parameters when transitioning FROM this scene + springFriction: number; + springTension: number; + + // Velocity to start at when transitioning without gesture + defaultTransitionVelocity: number; + + // Animation interpolators for horizontal transitioning: + animationInterpolators: { + into: AnimationInterpolator, + out: AnimationInterpolator + }; + + } + + // see /NavigatorSceneConfigs.js + export interface SceneConfigs { + FloatFromBottom: SceneConfig; + FloatFromRight: SceneConfig; + PushFromRight: SceneConfig; + FloatFromLeft: SceneConfig; + HorizontalSwipeJump: SceneConfig; + } + + export interface Route { + component?: ComponentClass + id?: string + title?: string + passProps?: Object; + + //anything else + [key: string]: any + + //Commonly found properties + backButtonTitle?: string + content?: string + message?: string; + index?: number + onRightButtonPress?: () => void + rightButtonTitle?: string + sceneConfig?: SceneConfig + wrapperStyle?: any + } + + + /** + * @see https://facebook.github.io/react-native/docs/navigator.html#content + */ + export interface NavigatorProperties extends React.Props { + /** + * Optional function that allows configuration about scene animations and gestures. + * Will be invoked with the route and should return a scene configuration object + * @param route + */ + configureScene?: ( route: Route ) => SceneConfig + /** + * Specify a route to start on. + * A route is an object that the navigator will use to identify each scene to render. + * initialRoute must be a route in the initialRouteStack if both props are provided. + * The initialRoute will default to the last item in the initialRouteStack. + */ + initialRoute?: Route + /** + * Provide a set of routes to initially mount. + * Required if no initialRoute is provided. + * Otherwise, it will default to an array containing only the initialRoute + */ + initialRouteStack?: Route[] + + /** + * Optionally provide a navigation bar that persists across scene transitions + */ + navigationBar?: React.ReactElement + + /** + * Optionally provide the navigator object from a parent Navigator + */ + navigator?: Navigator + + /** + * @deprecated Use navigationContext.addListener('willfocus', callback) instead. + */ + onDidFocus?: Function + + /** + * @deprecated Use navigationContext.addListener('willfocus', callback) instead. + */ + onWillFocus?: Function + + /** + * Required function which renders the scene for a given route. + * Will be invoked with the route and the navigator object + * @param route + * @param navigator + */ + renderScene?: ( route: Route, navigator: Navigator ) => React.ReactElement + + /** + * Styles to apply to the container of each scene + */ + sceneStyle?: ViewStyle + + /** + * //FIXME: not found in doc but found in examples + */ + debugOverlay?: boolean + + } + + /** + * Use Navigator to transition between different scenes in your app. + * To accomplish this, provide route objects to the navigator to identify each scene, + * and also a renderScene function that the navigator can use to render the scene for a given route. + * + * To change the animation or gesture properties of the scene, provide a configureScene prop to get the config object for a given route. + * See Navigator.SceneConfigs for default animations and more info on scene config options. + * @see https://facebook.github.io/react-native/docs/navigator.html + */ + export interface NavigatorStatic extends React.ComponentClass { + SceneConfigs: SceneConfigs; + NavigationBar: NavigatorStatic.NavigationBarStatic; + BreadcrumbNavigationBar: NavigatorStatic.BreadcrumbNavigationBarStatic + + getContext( self: any ): NavigatorStatic; + + /** + * returns the current list of routes + */ + getCurrentRoutes(): Route[]; + + /** + * Jump backward without unmounting the current scen + */ + jumpBack(): void; + + /** + * Jump forward to the next scene in the route stack + */ + jumpForward(): void; + + /** + * Transition to an existing scene without unmounting + */ + jumpTo( route: Route ): void; + + /** + * Navigate forward to a new scene, squashing any scenes that you could jumpForward to + */ + push( route: Route ): void; + + /** + * Transition back and unmount the current scene + */ + pop(): void; + + /** + * Replace the current scene with a new route + */ + replace( route: Route ): void; + + /** + * Replace a scene as specified by an index + */ + replaceAtIndex( route: Route, index: number ): void; + + /** + * Replace the previous scene + */ + replacePrevious( route: Route ): void; + + /** + * Reset every scene with an array of routes + */ + immediatelyResetRouteStack( routes: Route[] ): void; + + /** + * Pop to a particular scene, as specified by its route. All scenes after it will be unmounted + */ + popToRoute( route: Route ): void; + + /** + * Pop to the first scene in the stack, unmounting every other scene + */ + popToTop(): void; + + } + + namespace NavigatorStatic { + + + export interface NavState { + routeStack: Route[] + idStack: number[] + presentedIndex: number } - }); -class ModernComponent extends React.Component - implements React.ChildContextProvider { - - static propTypes: React.ValidationMap = { - foo: React.PropTypes.number - } - - static contextTypes: React.ValidationMap = { - someValue: React.PropTypes.string - } - - static childContextTypes: React.ValidationMap = { - someOtherValue: React.PropTypes.string - } - - static defaultProps: Props; - - context: Context; - - getChildContext() { - return { - someOtherValue: 'foo' + export interface NavigationBarStyle { + //TODO @see NavigationBarStyle.ios.js } + + + export interface NavigationBarRouteMapper { + Title: ( route: Route, nav: Navigator, index: number, navState: NavState ) => React.ReactElement; + LeftButton: ( route: Route, nav: Navigator, index: number, navState: NavState )=> React.ReactElement; + RightButton: ( route: Route, nav: Navigator, index: number, navState: NavState )=> React.ReactElement; + } + + /** + * @see NavigatorNavigationBar.js + */ + export interface NavigationBarProperties extends React.Props { + navigator?: Navigator + routeMapper?: NavigationBarRouteMapper + navState?: NavState + style?: ViewStyle + } + + export interface NavigationBarStatic extends React.ComponentClass { + Styles: NavigationBarStyle + + } + + export type NavigationBar = NavigationBarStatic + export var NavigationBar: NavigationBarStatic + + + export interface BreadcrumbNavigationBarStyle { + //TODO &see NavigatorBreadcrumbNavigationBar.js + } + + export interface BreadcrumbNavigationBarRouteMapper { + rightContentForRoute: ( route: Route, navigator: Navigator ) => React.ReactElement + titleContentForRoute: ( route: Route, navigator: Navigator ) => React.ReactElement + iconForRoute: ( route: Route, navigator: Navigator ) => React.ReactElement + //in samples... + separatorForRoute: ( route: Route, navigator: Navigator ) => React.ReactElement + } + + /** + * @see NavigatorNavigationBar.js + */ + export interface BreadcrumbNavigationBarProperties extends React.Props { + navigator?: Navigator + routeMapper?: BreadcrumbNavigationBarRouteMapper + navState?: NavState + style?: ViewStyle + } + + export interface BreadcrumbNavigationBarStatic extends React.ComponentClass { + Styles: BreadcrumbNavigationBarStyle + } + + export type BreadcrumbNavigationBar = BreadcrumbNavigationBarStatic + var BreadcrumbNavigationBar: BreadcrumbNavigationBarStatic + } - state = { - inputValue: this.context.someValue, - seconds: this.props.foo + + export interface StyleSheetStatic extends React.ComponentClass { + create( styles: T ): T; } - reset() { - this.setState({ - inputValue: this.context.someValue, - seconds: this.props.foo - }); + /** + * //FIXME: Could not find docs. Inferred from examples and jscode : ListViewDataSource.js + */ + export interface DataSourceAssetCallback { + rowHasChanged?: ( r1: any, r2: any ) => boolean + sectionHeaderHasChanged?: ( h1: any, h2: any ) => boolean + getRowData?: ( dataBlob: any, sectionID: number | string, rowID: number | string ) => T + getSectionHeaderData?: ( dataBlob: any, sectionID: number | string ) => T } - private _input: React.HTMLComponent; + /** + * //FIXME: Could not find docs. Inferred from examples and js code: ListViewDataSource.js + */ + export interface ListViewDataSource { + new( onAsset: DataSourceAssetCallback ): ListViewDataSource; + /** + * Clones this `ListViewDataSource` with the specified `dataBlob` and + * `rowIdentities`. The `dataBlob` is just an aribitrary blob of data. At + * construction an extractor to get the interesting informatoin was defined + * (or the default was used). + * + * The `rowIdentities` is is a 2D array of identifiers for rows. + * ie. [['a1', 'a2'], ['b1', 'b2', 'b3'], ...]. If not provided, it's + * assumed that the keys of the section data are the row identities. + * + * Note: This function does NOT clone the data in this data source. It simply + * passes the functions defined at construction to a new data source with + * the data specified. If you wish to maintain the existing data you must + * handle merging of old and new data separately and then pass that into + * this function as the `dataBlob`. + */ + cloneWithRows( dataBlob: Array | {[key: string]: any}, rowIdentities?: Array ): ListViewDataSource - render() { - return React.DOM.div(null, - React.DOM.input({ - ref: input => this._input = input, - value: this.state.inputValue - })); + /** + * This performs the same function as the `cloneWithRows` function but here + * you also specify what your `sectionIdentities` are. If you don't care + * about sections you should safely be able to use `cloneWithRows`. + * + * `sectionIdentities` is an array of identifiers for sections. + * ie. ['s1', 's2', ...]. If not provided, it's assumed that the + * keys of dataBlob are the section identities. + * + * Note: this returns a new object! + */ + cloneWithRowsAndSections( dataBlob: Array | {[key: string]: any}, sectionIdentities?: Array, rowIdentities?: Array> ): ListViewDataSource + + getRowCount(): number + + /** + * Gets the data required to render the row. + */ + getRowData( sectionIndex: number, rowIndex: number ): any + + /** + * Gets the rowID at index provided if the dataSource arrays were flattened, + * or null of out of range indexes. + */ + getRowIDForFlatIndex( index: number ): string + + /** + * Gets the sectionID at index provided if the dataSource arrays were flattened, + * or null for out of range indexes. + */ + getSectionIDForFlatIndex( index: number ): string + + /** + * Returns an array containing the number of rows in each section + */ + getSectionLengths(): Array + + /** + * Returns if the section header is dirtied and needs to be rerendered + */ + sectionHeaderShouldUpdate( sectionIndex: number ): boolean + + /** + * Gets the data required to render the section header + */ + getSectionHeaderData( sectionIndex: number ): any } + + + export interface ImageStatic extends React.ComponentClass { + uri: string; + } + + /** + * @see + */ + export interface TabBarItemProperties { + + } + + export interface TabBarItem extends React.ComponentClass { + } + + /** + * @see + */ + export interface TabBarIOSProperties { + } + + export interface TabBarIOSStatic extends React.ComponentClass { + Item: TabBarItem; + } + + export interface CameraRollFetchParams { + first: number; + groupTypes: string; + after?: string; + } + + export interface CameraRollNodeInfo { + image: Image; + group_name: string; + timestamp: number; + location: any; + } + + export interface CameraRollEdgeInfo { + node: CameraRollNodeInfo; + } + + export interface CameraRollAssetInfo { + edges: CameraRollEdgeInfo[]; + page_info: { + has_next_page: boolean; + end_cursor: string; + }; + } + + export interface CameraRollStatic extends React.ComponentClass { + getPhotos( fetch: CameraRollFetchParams, + onAsset: ( assetInfo: CameraRollAssetInfo ) => void, + logError: ()=> void ): void; + } + + export interface PanHandlers { + + } + + export interface PanResponderEvent { + + } + + export interface PanResponderGestureState { + stateID: number; + moveX: number; + moveY: number; + x0: number; + y0: number; + dx: number; + dy: number; + vx: number; + vy: number; + numberActiveTouches: number; + // All `gestureState` accounts for timeStamps up until: + _accountsForMovesUpTo: number; + } + + /** + * @param {object} config Enhanced versions of all of the responder callbacks + * that provide not only the typical `ResponderSyntheticEvent`, but also the + * `PanResponder` gesture state. Simply replace the word `Responder` with + * `PanResponder` in each of the typical `onResponder*` callbacks. For + * example, the `config` object would look like: + * + * - `onMoveShouldSetPanResponder: (e, gestureState) => {...}` + * - `onMoveShouldSetPanResponderCapture: (e, gestureState) => {...}` + * - `onStartShouldSetPanResponder: (e, gestureState) => {...}` + * - `onStartShouldSetPanResponderCapture: (e, gestureState) => {...}` + * - `onPanResponderReject: (e, gestureState) => {...}` + * - `onPanResponderGrant: (e, gestureState) => {...}` + * - `onPanResponderStart: (e, gestureState) => {...}` + * - `onPanResponderEnd: (e, gestureState) => {...}` + * - `onPanResponderRelease: (e, gestureState) => {...}` + * - `onPanResponderMove: (e, gestureState) => {...}` + * - `onPanResponderTerminate: (e, gestureState) => {...}` + * - `onPanResponderTerminationRequest: (e, gestureState) => {...}` + * + * In general, for events that have capture equivalents, we update the + * gestureState once in the capture phase and can use it in the bubble phase + * as well. + * + * Be careful with onStartShould* callbacks. They only reflect updated + * `gestureState` for start/end events that bubble/capture to the Node. + * Once the node is the responder, you can rely on every start/end event + * being processed by the gesture and `gestureState` being updated + * accordingly. (numberActiveTouches) may not be totally accurate unless you + * are the responder. + */ + export interface PanResponderCallbacks { + onMoveShouldSetPanResponder?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => boolean; + onStartShouldSetPanResponder?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderGrant?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderMove?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderRelease?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderTerminate?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + + onMoveShouldSetPanResponderCapture?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => boolean; + onStartShouldSetPanResponderCapture?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => boolean; + onPanResponderReject?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderStart?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderEnd?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + onPanResponderTerminationRequest?: ( e: PanResponderEvent, gestureState: PanResponderGestureState ) => void; + } + + export interface PanResponderInstance { + panHandlers: PanHandlers; + } + + export interface PanResponderStatic { + create( callbacks: PanResponderCallbacks ): PanResponderInstance; + } + + export interface PixelRatioStatic { + get(): number; + } + + export interface DeviceEventSubscriptionStatic { + remove(): void; + } + + export interface DeviceEventEmitterStatic { + addListener( type: string, onReceived: ( data: T ) => void ): DeviceEventSubscription; + } + + // Used by Dimensions below + export interface ScaledSize { + width: number; + height: number; + scale: number; + } + + // @see https://facebook.github.io/react-native/docs/asyncstorage.html#content + export interface AsyncStorageStatic { + getItem( key: string, callback?: ( error?: Error, result?: string ) => void ): Promise; + setItem( key: string, value: string, callback?: ( error?: Error ) => void ): Promise; + removeItem( key: string, callback?: ( error?: Error ) => void ): Promise; + mergeItem( key: string, value: string, callback?: ( error?: Error ) => void ): Promise; + clear( callback?: ( error?: Error ) => void ): Promise; + getAllKeys( callback?: ( error?: Error, keys?: string[] ) => void ): Promise; + multiGet( keys: string[], callback?: ( errors?: Error[], result?: string[][] ) => void ): Promise; + multiSet( keyValuePairs: string[][], callback?: ( errors?: Error[] ) => void ): Promise; + multiRemove( keys: string[], callback?: ( errors?: Error[] ) => void ): Promise; + multiMerge( keyValuePairs: string[][], callback?: ( errors?: Error[] ) => void ): Promise; + } + + export interface InteractionManagerStatic { + runAfterInteractions( fn: () => void ): void; + } + + + export interface ScrollViewStyle extends FlexStyle, TransformsStyle { + + backfaceVisibility?:string //enum('visible', 'hidden') + backgroundColor?: string + borderColor?: string + borderTopColor?: string + borderRightColor?: string + borderBottomColor?: string + borderLeftColor?: string + borderRadius?: number + borderTopLeftRadius?: number + borderTopRightRadius?: number + borderBottomLeftRadius?: number + borderBottomRightRadius?: number + borderStyle?: string //enum('solid', 'dotted', 'dashed') + borderWidth?: number + borderTopWidth?: number + borderRightWidth?: number + borderBottomWidth?: number + borderLeftWidth?: number + opacity?: number + overflow?: string //enum('visible', 'hidden') + shadowColor?: string + shadowOffset?: {width: number; height: number} + shadowOpacity?: number + shadowRadius?: number + } + + export interface EdgeInsetsProperties { + top: number + left: number + bottom: number + right: number + } + + export interface PointProperties { + x: number + y: number + } + + export interface ScrollViewIOSProperties { + + /** + * When true the scroll view bounces horizontally when it reaches the end + * even if the content is smaller than the scroll view itself. The default + * value is true when `horizontal={true}` and false otherwise. + */ + alwaysBounceHorizontal?: boolean + /** + * When true the scroll view bounces vertically when it reaches the end + * even if the content is smaller than the scroll view itself. The default + * value is false when `horizontal={true}` and true otherwise. + */ + alwaysBounceVertical?: boolean + + /** + * Controls whether iOS should automatically adjust the content inset for scroll views that are placed behind a navigation bar or tab bar/ toolbar. + * The default value is true. + */ + automaticallyAdjustContentInsets?: boolean // true + + /** + * When true the scroll view bounces when it reaches the end of the + * content if the content is larger then the scroll view along the axis of + * the scroll direction. When false it disables all bouncing even if + * the `alwaysBounce*` props are true. The default value is true. + */ + bounces?: boolean + /** + * When true gestures can drive zoom past min/max and the zoom will animate + * to the min/max value at gesture end otherwise the zoom will not exceed + * the limits. + */ + bouncesZoom?: boolean + + /** + * When false once tracking starts won't try to drag if the touch moves. + * The default value is true. + */ + canCancelContentTouches?: boolean + + /** + * When true the scroll view automatically centers the content when the + * content is smaller than the scroll view bounds; when the content is + * larger than the scroll view this property has no effect. The default + * value is false. + */ + centerContent?: boolean + + + /** + * The amount by which the scroll view content is inset from the edges of the scroll view. + * Defaults to {0, 0, 0, 0}. + */ + contentInset?: EdgeInsetsProperties // zeros + + /** + * Used to manually set the starting scroll offset. + * The default value is {x: 0, y: 0} + */ + contentOffset?: PointProperties // zeros + + /** + * A floating-point number that determines how quickly the scroll view + * decelerates after the user lifts their finger. Reasonable choices include + * - Normal: 0.998 (the default) + * - Fast: 0.9 + */ + decelerationRate?: number + + /** + * When true the ScrollView will try to lock to only vertical or horizontal + * scrolling while dragging. The default value is false. + */ + directionalLockEnabled?: boolean + + /** + * The maximum allowed zoom scale. The default value is 1.0. + */ + maximumZoomScale?: number + + /** + * The minimum allowed zoom scale. The default value is 1.0. + */ + minimumZoomScale?: number + + /** + * Called when a scrolling animation ends. + */ + onScrollAnimationEnd?: () => void + + /** + * When true the scroll view stops on multiples of the scroll view's size + * when scrolling. This can be used for horizontal pagination. The default + * value is false. + */ + pagingEnabled?: boolean + + /** + * When false, the content does not scroll. The default value is true + */ + scrollEnabled?: boolean // true + + /** + * This controls how often the scroll event will be fired while scrolling (in events per seconds). + * A higher number yields better accuracy for code that is tracking the scroll position, + * but can lead to scroll performance problems due to the volume of information being send over the bridge. + * The default value is zero, which means the scroll event will be sent only once each time the view is scrolled. + */ + scrollEventThrottle?: number // null + + /** + * The amount by which the scroll view indicators are inset from the edges of the scroll view. + * This should normally be set to the same value as the contentInset. + * Defaults to {0, 0, 0, 0}. + */ + scrollIndicatorInsets?: EdgeInsetsProperties //zeroes + + /** + * When true the scroll view scrolls to top when the status bar is tapped. + * The default value is true. + */ + scrollsToTop?: boolean + + /** + * When snapToInterval is set, snapToAlignment will define the relationship of the the snapping to the scroll view. + * - start (the default) will align the snap at the left (horizontal) or top (vertical) + * - center will align the snap in the center + * - end will align the snap at the right (horizontal) or bottom (vertical) + */ + snapToAlignment?: string + + /** + * When set, causes the scroll view to stop at multiples of the value of snapToInterval. + * This can be used for paginating through children that have lengths smaller than the scroll view. + * Used in combination with snapToAlignment. + */ + snapToInterval?: number + + /** + * An array of child indices determining which children get docked to the + * top of the screen when scrolling. For example passing + * `stickyHeaderIndices={[0]}` will cause the first child to be fixed to the + * top of the scroll view. This property is not supported in conjunction + * with `horizontal={true}`. + */ + stickyHeaderIndices?: number[] + + /** + * The current scale of the scroll view content. The default value is 1.0. + */ + zoomScale?: number + } + + export interface ScrollViewProperties extends ScrollViewIOSProperties { + + /** + * These styles will be applied to the scroll view content container which + * wraps all of the child views. Example: + * + * return ( + * + * + * ); + * ... + * var styles = StyleSheet.create({ + * contentContainer: { + * paddingVertical: 20 + * } + * }); + */ + contentContainerStyle?: ViewStyle + + /** + * When true the scroll view's children are arranged horizontally in a row + * instead of vertically in a column. The default value is false. + */ + horizontal?: boolean + + /** + * Determines whether the keyboard gets dismissed in response to a drag. + * - 'none' (the default) drags do not dismiss the keyboard. + * - 'onDrag' the keyboard is dismissed when a drag begins. + * - 'interactive' the keyboard is dismissed interactively with the drag + * and moves in synchrony with the touch; dragging upwards cancels the + * dismissal. + */ + keyboardDismissMode?: string + + /** + * When false tapping outside of the focused text input when the keyboard + * is up dismisses the keyboard. When true the scroll view will not catch + * taps and the keyboard will not dismiss automatically. The default value + * is false. + */ + keyboardShouldPersistTaps?: boolean + + /** + * Fires at most once per frame during scrolling. + * The frequency of the events can be contolled using the scrollEventThrottle prop. + */ + onScroll?: () => void + + /** + * Experimental: When true offscreen child views (whose `overflow` value is + * `hidden`) are removed from their native backing superview when offscreen. + * This canimprove scrolling performance on long lists. The default value is + * false. + */ + removeClippedSubviews?: boolean + + /** + * When true, shows a horizontal scroll indicator. + */ + showsHorizontalScrollIndicator?: boolean + + /** + * When true, shows a vertical scroll indicator. + */ + showsVerticalScrollIndicator?: boolean + + /** + * Style + */ + style?: ScrollViewStyle + } + + export interface ScrollViewProps extends ScrollViewProperties, React.Props { + + } + + interface ScrollViewStatic extends React.ComponentClass { + + } + + + export interface NativeScrollRectangle { + left: number; + top: number; + bottom: number; + right: number; + } + + export interface NativeScrollPoint { + x: number; + y: number; + } + + export interface NativeScrollSize { + height: number; + width: number; + } + + export interface NativeScrollEvent { + contentInset: NativeScrollRectangle; + contentOffset: NativeScrollPoint; + contentSize: NativeScrollSize; + layoutMeasurement: NativeScrollSize; + zoomScale: number; + } + + export interface AppStateIOSStatic { + currentState: string; + addEventListener( type: string, listener: ( state: string ) => void ): void; + removeEventListener( type: string, listener: ( state: string ) => void ): void; + } + + // exported singletons: + // export var AppRegistry: AppRegistryStatic; + + + export var ActivityIndicatorIOS: ActivityIndicatorIOSStatic; + export type ActivityIndicatorIOS = ActivityIndicatorIOSStatic; + + export var AsyncStorage: AsyncStorageStatic; + export type AsyncStorage = AsyncStorageStatic; + + export var CameraRoll: CameraRollStatic; + export type CameraRoll = CameraRollStatic; + + export var DatePickerIOS: DatePickerIOSStatic + export type DatePickerIOS = DatePickerIOSStatic + + export var Image: ImageStatic; + export type Image = ImageStatic; + + export var ListView: ListViewStatic; + export type ListView = ListViewStatic; + + export var Navigator: NavigatorStatic; + export type Navigator = NavigatorStatic; + + export var NavigatorIOS: NavigatorIOSStatic; + export type NavigatorIOS = NavigatorIOSStatic; + + export var SliderIOS: SliderIOSStatic; + export type SliderIOS = SliderIOSStatic; + + export var ScrollView: ScrollViewStatic + export type ScrollView = ScrollViewStatic + + export var StyleSheet: StyleSheetStatic; + export type StyleSheet = StyleSheetStatic; + + export var TabBarIOS: TabBarIOSStatic; + export type TabBarIOS = TabBarIOSStatic; + + export var Text: TextStatic; + export type Text = TextStatic; + + export var TextInput: TextInputStatic + export type TextInput = TextInputStatic + + export var TouchableHighlight: TouchableHighlightStatic; + export type TouchableHighlight = TouchableHighlightStatic; + + export var TouchableOpacity: TouchableOpacityStatic; + export type TouchableOpacity = TouchableOpacityStatic; + + export var TouchableWithoutFeedback: TouchableWithoutFeedbackStatic; + export type TouchableWithoutFeedback= TouchableWithoutFeedbackStatic; + + export var View: ViewStatic; + export type View = ViewStatic; + + export var AlertIOS: React.ComponentClass; + export var SegmentedControlIOS: React.ComponentClass; + export var SwitchIOS: React.ComponentClass; + + export var PixelRatio: PixelRatioStatic; + export var DeviceEventEmitter: DeviceEventEmitterStatic; + export var DeviceEventSubscription: DeviceEventSubscriptionStatic; + export type DeviceEventSubscription = DeviceEventSubscriptionStatic; + export var InteractionManager: InteractionManagerStatic; + export var PanResponder: PanResponderStatic; + export var AppStateIOS: AppStateIOSStatic; + + + //react re-exported + export type ReactType = React.ReactType; + + export interface ReactElement

    extends React.ReactElement

    {} + + export interface ClassicElement

    extends React.ClassicElement

    {} + + export interface DOMElement

    extends React.DOMElement

    {} + + export type HTMLElement =React.HTMLElement; + export type SVGElement = React.SVGElement; + + // + // Factories + // ---------------------------------------------------------------------- + + export interface Factory

    extends React.Factory

    {} + + export interface ClassicFactory

    extends React.ClassicFactory

    {} + + export interface DOMFactory

    extends React.DOMFactory

    {} + + export type HTMLFactory = React.HTMLFactory; + export type SVGFactory = React.SVGFactory; + export type SVGElementFactory = React.SVGElementFactory; + + // + // React Nodes + // http://facebook.github.io/react/docs/glossary.html + // ---------------------------------------------------------------------- + + export type ReactText = React.ReactText; + export type ReactChild = React.ReactChild; + + // Should be Array but type aliases cannot be recursive + export type ReactFragment = React.ReactFragment; + export type ReactNode = React.ReactNode; + + // + // Top Level API + // ---------------------------------------------------------------------- + + export function createClass( spec: React.ComponentSpec ): React.ClassicComponentClass

    ; + + export function createFactory

    ( type: string ): React.DOMFactory

    ; + export function createFactory

    ( type: React.ClassicComponentClass

    | string ): React.ClassicFactory

    ; + export function createFactory

    ( type: React.ComponentClass

    ): React.Factory

    ; + + export function createElement

    ( type: string, + props?: P, + ...children: React.ReactNode[] ): React.DOMElement

    ; + export function createElement

    ( type: React.ClassicComponentClass

    | string, + props?: P, + ...children: React.ReactNode[] ): React.ClassicElement

    ; + export function createElement

    ( type: React.ComponentClass

    , + props?: P, + ...children: React.ReactNode[] ): React.ReactElement

    ; + + export function cloneElement

    ( element: React.DOMElement

    , + props?: P, + ...children: React.ReactNode[] ): React.DOMElement

    ; + export function cloneElement

    ( element: React.ClassicElement

    , + props?: P, + ...children: React.ReactNode[] ): React.ClassicElement

    ; + export function cloneElement

    ( element: React.ReactElement

    , + props?: P, + ...children: React.ReactNode[] ): React.ReactElement

    ; + + export function isValidElement( object: {} ): boolean; + + export var DOM: React.ReactDOM; + export var PropTypes: React.ReactPropTypes; + export var Children: React.ReactChildren; + + // + // Component API + // ---------------------------------------------------------------------- + + // Base component for plain JS classes + export class Component extends React.Component {} + + export interface ClassicComponent extends React.ClassicComponent {} + + export interface DOMComponent

    extends ClassicComponent { + tagName: string; + } + + export type HTMLComponent = React.HTMLComponent; + export type SVGComponent = React.SVGComponent + + export interface ChildContextProvider extends React.ChildContextProvider {} + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + export interface ComponentClass

    extends React.ComponentClass

    {} + + export interface ClassicComponentClass

    extends React.ClassicComponentClass

    {} + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + export interface ComponentLifecycle extends React.ComponentLifecycle {} + + export interface Mixin extends React.Mixin {} + + export interface ComponentSpec extends React.ComponentSpec {} + + // + // Event System + // ---------------------------------------------------------------------- + + export interface SyntheticEvent extends React.SyntheticEvent {} + + export interface DragEvent extends React.DragEvent {} + + export interface ClipboardEvent extends React.ClipboardEvent {} + + export interface KeyboardEvent extends React.KeyboardEvent {} + + + export interface FocusEvent extends React.FocusEvent {} + + export interface FormEvent extends React.FormEvent {} + + export interface MouseEvent extends React.MouseEvent {} + + export interface TouchEvent extends React.TouchEvent {} + + export interface UIEvent extends React.UIEvent {} + + export interface WheelEvent extends React.WheelEvent {} + + // + // Event Handler Types + // ---------------------------------------------------------------------- + + export interface EventHandler extends React.EventHandler {} + + export interface DragEventHandler extends React.DragEventHandler {} + export interface ClipboardEventHandler extends React.ClipboardEventHandler {} + export interface KeyboardEventHandler extends React.KeyboardEventHandler {} + export interface FocusEventHandler extends React.FocusEventHandler {} + export interface FormEventHandler extends React.FormEventHandler {} + export interface MouseEventHandler extends React.MouseEventHandler {} + export interface TouchEventHandler extends React.TouchEventHandler {} + export interface UIEventHandler extends React.UIEventHandler {} + export interface WheelEventHandler extends React.WheelEventHandler {} + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + export interface Props extends React.Props {} + + export interface DOMAttributesBase extends React.DOMAttributesBase {} + + export interface DOMAttributes extends React.DOMAttributes {} + + // This interface is not complete. Only properties accepting + // unitless numbers are listed here (see CSSProperty.js in React) + export interface CSSProperties extends React.CSSProperties {} + + export interface HTMLAttributesBase extends React.HTMLAttributesBase {} + + export interface HTMLAttributes extends React.HTMLAttributes {} + + export interface SVGElementAttributes extends React.SVGElementAttributes {} + + export interface SVGAttributes extends React.SVGAttributes {} + + // + // React.DOM + // ---------------------------------------------------------------------- + + export interface ReactDOM extends React.ReactDOM {} + + // + // React.PropTypes + // ---------------------------------------------------------------------- + + export interface Validator extends React.Validator {} + + export interface Requireable extends React.Requireable {} + + export interface ValidationMap extends React.ValidationMap {} + + export interface ReactPropTypes extends React.ReactPropTypes {} + + // + // React.Children + // ---------------------------------------------------------------------- + + export interface ReactChildren extends React.ReactChildren {} + + // + // Browser Interfaces + // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts + // ---------------------------------------------------------------------- + + export interface AbstractView extends React.AbstractView {} + + export interface Touch extends React.Touch {} + + export interface TouchList extends React.TouchList {} + + // + // Additional ( and controversial) + // + + export function __spread( target: any, ...sources: any[] ): any; + + + export interface GlobalStatic { + + /** + * Accepts a function as its only argument and calls that function before the next repaint. + * It is an essential building block for animations that underlies all of the JavaScript-based animation APIs. + * In general, you shouldn't need to call this yourself - the animation API's will manage frame updates for you. + * @see https://facebook.github.io/react-native/docs/animations.html#requestanimationframe + */ + requestAnimationFrame( fn: () => void ) : void; + + } + + // + // Add-Ons + // + namespace addons { + + //FIXME: Documentation ? + export interface TestModuleStatic { + + verifySnapshot: (done: (indicator?: any) => void) => void + markTestPassed: (indicator: any) => void + markTestCompleted: () => void + } + + export var TestModule: TestModuleStatic + export type TestModule = TestModuleStatic + } + + } -// React.createFactory -var factory: React.Factory = - React.createFactory(ModernComponent); -var factoryElement: React.ReactElement = - factory(props); +declare module "react-native" { -var classicFactory: React.ClassicFactory = - React.createFactory(ClassicComponent); -var classicFactoryElement: React.ClassicElement = - classicFactory(props); - -var domFactory: React.DOMFactory = - React.createFactory("foo"); -var domFactoryElement: React.DOMElement = - domFactory(); - -// React.createElement -var element: React.ReactElement = - React.createElement(ModernComponent, props); -var classicElement: React.ClassicElement = - React.createElement(ClassicComponent, props); -var domElement: React.HTMLElement = - React.createElement("div"); - -// React.cloneElement -var clonedElement: React.ReactElement = - React.cloneElement(element, props); -var clonedClassicElement: React.ClassicElement = - React.cloneElement(classicElement, props); -var clonedDOMElement: React.HTMLElement = - React.cloneElement(domElement); - -// React.render -var component: React.Component = - React.render(element, container); -var classicComponent: React.ClassicComponent = - React.render(classicElement, container); -var domComponent: React.DOMComponent = - React.render(domElement, container); - -// Other Top-Level API -var unmounted: boolean = React.unmountComponentAtNode(container); -var str: string = React.renderToString(element); -var markup: string = React.renderToStaticMarkup(element); -var notValid: boolean = React.isValidElement(props); // false -var isValid = React.isValidElement(element); // true -React.initializeTouchEvents(true); -var domNode: Element = React.findDOMNode(component); -domNode = React.findDOMNode(domNode); - -// -// React Elements -// -------------------------------------------------------------------------- - -var type = element.type; -var elementProps: Props = element.props; -var key = element.key; - -// -// React Components -// -------------------------------------------------------------------------- - -var displayName: string = ClassicComponent.displayName; -var defaultProps: Props = ClassicComponent.getDefaultProps(); -var propTypes: React.ValidationMap = ClassicComponent.propTypes; - -// -// Component API -// -------------------------------------------------------------------------- - -// modern -var componentState: State = component.state; -component.setState({ inputValue: "!!!" }); -component.forceUpdate(); - -// classic -var htmlElement: Element = classicComponent.getDOMNode(); -var divElement: HTMLDivElement = classicComponent.getDOMNode(); -var isMounted: boolean = classicComponent.isMounted(); -classicComponent.setProps(elementProps); -classicComponent.replaceProps(props); -classicComponent.replaceState({ inputValue: "???", seconds: 60 }); - -var myComponent = component; -myComponent.reset(); - -// -// Attributes -// -------------------------------------------------------------------------- - -var children: any[] = ["Hello world", [null], React.DOM.span(null)]; -var divStyle: React.CSSProperties = { // CSSProperties - flex: "1 1 main-size", - backgroundImage: "url('hello.png')" -}; -var htmlAttr: React.HTMLAttributes = { - key: 36, - ref: "htmlComponent", - children: children, - className: "test-attr", - style: divStyle, - onClick: (event: React.MouseEvent) => { - event.preventDefault(); - event.stopPropagation(); - }, - dangerouslySetInnerHTML: { - __html: "STRONG" - } -}; -React.DOM.div(htmlAttr); -React.DOM.span(htmlAttr); -React.DOM.input(htmlAttr); - -React.DOM.svg({ viewBox: "0 0 48 48" }, - React.DOM.rect({ - x: 22, - y: 10, - width: 4, - height: 28 - }), - React.DOM.rect({ - x: 10, - y: 22, - width: 28, - height: 4 - })); - -// -// React.PropTypes -// -------------------------------------------------------------------------- - -var PropTypesSpecification: React.ComponentSpec = { - propTypes: { - optionalArray: React.PropTypes.array, - optionalBool: React.PropTypes.bool, - optionalFunc: React.PropTypes.func, - optionalNumber: React.PropTypes.number, - optionalObject: React.PropTypes.object, - optionalString: React.PropTypes.string, - optionalNode: React.PropTypes.node, - optionalElement: React.PropTypes.element, - optionalMessage: React.PropTypes.instanceOf(Date), - optionalEnum: React.PropTypes.oneOf(["News", "Photos"]), - optionalUnion: React.PropTypes.oneOfType([ - React.PropTypes.string, - React.PropTypes.number, - React.PropTypes.instanceOf(Date) - ]), - optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number), - optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number), - optionalObjectWithShape: React.PropTypes.shape({ - color: React.PropTypes.string, - fontSize: React.PropTypes.number - }), - requiredFunc: React.PropTypes.func.isRequired, - requiredAny: React.PropTypes.any.isRequired, - customProp: function(props: any, propName: string, componentName: string) { - if (!/matchme/.test(props[propName])) { - return new Error("Validation failed!"); - } - return null; - } - }, - render: (): React.ReactElement => { - return null; - } -}; - -// -// ContextTypes -// -------------------------------------------------------------------------- - -var ContextTypesSpecification: React.ComponentSpec = { - contextTypes: { - optionalArray: React.PropTypes.array, - optionalBool: React.PropTypes.bool, - optionalFunc: React.PropTypes.func, - optionalNumber: React.PropTypes.number, - optionalObject: React.PropTypes.object, - optionalString: React.PropTypes.string, - optionalNode: React.PropTypes.node, - optionalElement: React.PropTypes.element, - optionalMessage: React.PropTypes.instanceOf(Date), - optionalEnum: React.PropTypes.oneOf(["News", "Photos"]), - optionalUnion: React.PropTypes.oneOfType([ - React.PropTypes.string, - React.PropTypes.number, - React.PropTypes.instanceOf(Date) - ]), - optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number), - optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number), - optionalObjectWithShape: React.PropTypes.shape({ - color: React.PropTypes.string, - fontSize: React.PropTypes.number - }), - requiredFunc: React.PropTypes.func.isRequired, - requiredAny: React.PropTypes.any.isRequired, - customProp: function(props: any, propName: string, componentName: string) { - if (!/matchme/.test(props[propName])) { - return new Error("Validation failed!"); - } - return null; - } - }, - render: (): React.ReactElement => { - return null; - } -}; - -// -// React.Children -// -------------------------------------------------------------------------- - -var childMap: { [key: string]: number } = - React.Children.map(children, (child) => { return 42; }); -React.Children.forEach(children, (child) => {}); -var nChildren: number = React.Children.count(children); -var onlyChild = React.Children.only([null, [[["Hallo"], true]], false]); - -// -// Example from http://facebook.github.io/react/ -// -------------------------------------------------------------------------- - -interface TimerState { - secondsElapsed: number; + export default ReactNative } -class Timer extends React.Component, TimerState> { - state = { - secondsElapsed: 0 - } - private _interval: number; - tick() { - this.setState((prevState, props) => ({ - secondsElapsed: prevState.secondsElapsed + 1 - })); - } - componentDidMount() { - this._interval = setInterval(() => this.tick(), 1000); - } - componentWillUnmount() { - clearInterval(this._interval); - } - render() { - return React.DOM.div( - null, - "Seconds Elapsed: ", - this.state.secondsElapsed - ); + + +declare module "Dimensions" { + import React from 'react-native'; + + interface Dimensions { + get( what: string ): React.ScaledSize; } + + var ExportDimensions: Dimensions; + export = ExportDimensions; } -React.render(React.createElement(Timer), container); -// -// React.addons -// -------------------------------------------------------------------------- +declare var global: ReactNative.GlobalStatic -var cx = React.addons.classSet; -var className: string = cx({ a: true, b: false, c: true }); -className = cx("a", null, "b"); - -React.addons.createFragment({ - a: React.DOM.div(), - b: ["a", false, React.createElement("span")] -}); - -// -// React.addons (Transitions) -// -------------------------------------------------------------------------- - -React.createFactory(React.addons.TransitionGroup)({ component: "div" }); -React.createFactory(React.addons.CSSTransitionGroup)({ - component: React.createClass({ - render: (): React.ReactElement => null - }), - childFactory: (c) => c, - transitionName: "transition", - transitionAppear: false, - transitionEnter: true, - transitionLeave: true -}); - -// -// React.addons.TestUtils -// -------------------------------------------------------------------------- - -var node: Element; -TestUtils.Simulate.click(node); -TestUtils.Simulate.change(node); -TestUtils.Simulate.keyDown(node, { key: "Enter" }); - -var renderer: React.ShallowRenderer = - TestUtils.createRenderer(); -renderer.render(React.createElement(Timer)); -var output: React.ReactElement> = - renderer.getRenderOutput(); +declare function require( name: string ): any From c8ad4f59ef31ee057841988c3985128fddf952a2 Mon Sep 17 00:00:00 2001 From: bgrieder Date: Wed, 11 Nov 2015 10:34:31 +0100 Subject: [PATCH 82/86] Image fixes & add ImageResize --- react-native/react-native.d.ts | 241 +++++++++++++++++++++++---------- 1 file changed, 168 insertions(+), 73 deletions(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index 10cfb50c5..485fdf5c0 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -436,7 +436,7 @@ declare namespace ReactNative { /** * Callback that is called when the text input's text changes. */ - onChange?: () => void + onChange?: (event: {nativeEvent: {text: string}}) => void /** * Callback that is called when the text input's text changes. @@ -447,7 +447,7 @@ declare namespace ReactNative { /** * Callback that is called when text input ends. */ - onEndEditing?: () => void + onEndEditing?: (event: {nativeEvent: {text: string}}) => void /** * Callback that is called when the text input is focused @@ -457,12 +457,12 @@ declare namespace ReactNative { /** * Invoked on mount and layout changes with {x, y, width, height}. */ - onLayout?: () => void + onLayout?: (event: {nativeEvent: {x: number, y: number, width: number, height: number}}) => void /** * Callback that is called when the text input's submit button is pressed. */ - onSubmitEditing?: () => void + onSubmitEditing?: (event: {nativeEvent: {text: string}}) => void /** * The string that will be rendered before text input has been entered @@ -872,6 +872,58 @@ declare namespace ReactNative { export interface ActivityIndicatorIOSStatic extends React.ComponentClass { } + + export interface DatePickerIOSProperties extends React.Props { + + /** + * The currently selected date. + */ + date?: Date + + + /** + * Maximum date. + * Restricts the range of possible date/time values. + */ + maximumDate?: Date + + /** + * Maximum date. + * Restricts the range of possible date/time values. + */ + minimumDate?: Date + + /** + * enum(1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30) + * The interval at which minutes can be selected. + */ + minuteInterval?: number + + /** + * enum('date', 'time', 'datetime') + * The date picker mode. + */ + mode?: string + + /** + * Date change handler. + * This is called when the user changes the date or time in the UI. + * The first and only argument is a Date object representing the new date and time. + */ + onDateChange?: (newDate: Date) => void + + /** + * Timezone offset in minutes. + * By default, the date picker will use the device's timezone. With this parameter, it is possible to force a certain timezone offset. + * For instance, to show times in Pacific Standard Time, pass -7 * 60. + */ + timeZoneOffsetInMinutes?: number + + } + + export interface DatePickerIOSStatic extends React.ComponentClass { + } + /** * @see https://facebook.github.io/react-native/docs/sliderios.html */ @@ -933,27 +985,97 @@ declare namespace ReactNative { /// TODO } + /** + * @see ImageResizeMode.js + */ + export interface ImageResizeModeStatic { + /** + * contain - The image will be resized such that it will be completely + * visible, contained within the frame of the View. + */ + contain: string + /** + * cover - The image will be resized such that the entire area of the view + * is covered by the image, potentially clipping parts of the image. + */ + cover: string + /** + * stretch - The image will be stretched to fill the entire frame of the + * view without clipping. This may change the aspect ratio of the image, + * distoring it. Only supported on iOS. + */ + stretch: string + } + /** * Image style * @see https://facebook.github.io/react-native/docs/image.html#style */ - export interface ImageStyle extends FlexStyle { - color?: string; - containerBackgroundColor?: string; - fontFamily?: string; - fontSize?: number; - fontStyle?: string; // 'normal' | 'italic'; - fontWeight?: string; // enum("normal", 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900') - letterSpacing?: number; - lineHeight?: number; - textAlign?: string; // enum("auto", 'left', 'right', 'center') - writingDirection?: string; //enum("auto", 'ltr', 'rtl') + export interface ImageStyle extends FlexStyle, TransformsStyle { + resizeMode?: string //Object.keys(ImageResizeMode) + backgroundColor?: string + borderColor?: string + borderWidth?: number + borderRadius?: number + overflow?: string // enum('visible', 'hidden') + tintColor?: string + opacity?: number + } + + export interface ImagePropertiesIOS { + /** + * The text that's read by the screen reader when the user interacts with the image. + */ + accessibilityLabel?: string; + + /** + * When true, indicates the image is an accessibility element. + */ + accessible?: boolean; + + /** + * When the image is resized, the corners of the size specified by capInsets will stay a fixed size, + * but the center content and borders of the image will be stretched. + * This is useful for creating resizable rounded buttons, shadows, and other resizable assets. + * More info on Apple documentation + */ + capInsets?: {top: number, left: number, bottom: number, right: number} + + /** + * A static image to display while downloading the final image off the network. + */ + defaultSource?: {uri: string} + + /** + * Invoked on load error with {nativeEvent: {error}} + */ + onError?: ( error: {nativeEvent: any} ) => void + + /** + * Invoked when load completes successfully + */ + onLoad?: () => void + + /** + * Invoked when load either succeeds or fails + */ + onLoadEnd?: () => void + + /** + * Invoked on load start + */ + onLoadStart?: () => void + + /** + * Invoked on download progress with {nativeEvent: {loaded, total}} + */ + onProgress?: ()=> void } /** * @see https://facebook.github.io/react-native/docs/image.html */ - export interface ImageProperties extends React.Props { + export interface ImageProperties extends ImagePropertiesIOS, React.Props { /** * onLayout function * @@ -966,8 +1088,10 @@ declare namespace ReactNative { /** * Determines how to resize the image when the frame doesn't match the raw image dimensions. + * + * enum('cover', 'contain', 'stretch') */ - resizeMode?: string; // enum('cover', 'contain', 'stretch') + resizeMode?: string; /** * uri is a string representing the resource identifier for the image, @@ -987,55 +1111,14 @@ declare namespace ReactNative { */ testID?: string; - /** - * The text that's read by the screen reader when the user interacts with the image. - */ - iosaccessibilityLabel?: string; - - /** - * When true, indicates the image is an accessibility element. - */ - iosaccessible?: boolean; - - /** - * When the image is resized, the corners of the size specified by capInsets will stay a fixed size, - * but the center content and borders of the image will be stretched. - * This is useful for creating resizable rounded buttons, shadows, and other resizable assets. - * More info on Apple documentation - */ - ioscapInsets?: {top: number, left: number, bottom: number, right: number} - - /** - * A static image to display while downloading the final image off the network. - */ - iosdefaultSource?: {uri: string} - - /** - * Invoked on load error with {nativeEvent: {error}} - */ - iosonError?: ( error: {nativeEvent: any} ) => void - - /** - * Invoked when load completes successfully - */ - iosonLoad?: () => void - - /** - * Invoked when load either succeeds or fails - */ - iosonLoadEnd?: () => void - - /** - * Invoked on load start - */ - iosonLoadStart?: () => void - - /** - * Invoked on download progress with {nativeEvent: {loaded, total}} - */ - iosonProgress?: ()=> void } + export interface ImageStatic extends React.ComponentClass { + uri: string; + resizeMode: ImageResizeModeStatic + } + + /** * @see https://facebook.github.io/react-native/docs/listview.html#props */ @@ -1636,9 +1719,6 @@ declare namespace ReactNative { } - export interface ImageStatic extends React.ComponentClass { - uri: string; - } /** * @see @@ -2127,6 +2207,9 @@ declare namespace ReactNative { export var CameraRoll: CameraRollStatic; export type CameraRoll = CameraRollStatic; + export var DatePickerIOS: DatePickerIOSStatic + export type DatePickerIOS = DatePickerIOSStatic + export var Image: ImageStatic; export type Image = ImageStatic; @@ -2136,12 +2219,6 @@ declare namespace ReactNative { export var Navigator: NavigatorStatic; export type Navigator = NavigatorStatic; - //export var NavigationBar: NavigationBarStatic - //export type NavigationBar = NavigationBarStatic - - //export var BreadcrumbNavigationBar: BreadcrumbNavigationBarStatic - //export type BreadcrumbNavigationBar = BreadcrumbNavigationBarStatic - export var NavigatorIOS: NavigatorIOSStatic; export type NavigatorIOS = NavigatorIOSStatic; @@ -2415,6 +2492,24 @@ declare namespace ReactNative { } + // + // Add-Ons + // + namespace addons { + + //FIXME: Documentation ? + export interface TestModuleStatic { + + verifySnapshot: (done: (indicator?: any) => void) => void + markTestPassed: (indicator: any) => void + markTestCompleted: () => void + } + + export var TestModule: TestModuleStatic + export type TestModule = TestModuleStatic + } + + } declare module "react-native" { From 72aebc82130ef7b19566ab203e096e8458f82936 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Wed, 11 Nov 2015 10:35:06 +0000 Subject: [PATCH 83/86] Update ngbootbox.d.ts --- ngbootbox/ngbootbox.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ngbootbox/ngbootbox.d.ts b/ngbootbox/ngbootbox.d.ts index b81a07501..4c6233dab 100644 --- a/ngbootbox/ngbootbox.d.ts +++ b/ngbootbox/ngbootbox.d.ts @@ -6,7 +6,7 @@ /// /// -interface IBootboxDialog { +interface NgBootboxDialog { title?: string; message?: string; templateUrl?: string; @@ -22,7 +22,7 @@ interface IBootboxDialog { buttons?: BootboxButtonMap; } -interface IBootboxService { +interface BootboxService { alert(msg: string): Promise; confirm(msg: string): Promise; prompt(msg: string): Promise; @@ -35,4 +35,4 @@ interface IBootboxService { setLocale(name: string): void; } -declare var $ngBootbox: IBootboxService; +declare var $ngBootbox: BootboxService; From dc6ed0fd0a50890143b41b1f1c601965725260ab Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Wed, 11 Nov 2015 10:35:40 +0000 Subject: [PATCH 84/86] Update ngbootbox.d.ts --- ngbootbox/ngbootbox.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ngbootbox/ngbootbox.d.ts b/ngbootbox/ngbootbox.d.ts index 4c6233dab..e99e47979 100644 --- a/ngbootbox/ngbootbox.d.ts +++ b/ngbootbox/ngbootbox.d.ts @@ -26,7 +26,7 @@ interface BootboxService { alert(msg: string): Promise; confirm(msg: string): Promise; prompt(msg: string): Promise; - customDialog(options: IBootboxDialog): void; + customDialog(options: NgBootboxDialog): void; setDefaults(options: BootboxDefaultOptions): void; hideAll(): void; From 3f67d589738d4616ca62583d08df3e6fc2971acf Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Wed, 11 Nov 2015 10:36:16 +0000 Subject: [PATCH 85/86] Update ngbootbox-tests.ts --- ngbootbox/ngbootbox-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ngbootbox/ngbootbox-tests.ts b/ngbootbox/ngbootbox-tests.ts index 7e8196fec..ec4fb2830 100644 --- a/ngbootbox/ngbootbox-tests.ts +++ b/ngbootbox/ngbootbox-tests.ts @@ -3,7 +3,7 @@ class TestBootboxController { - constructor(private $scope: angular.IScope, $ngBootbox: IBootboxService) { + constructor(private $scope: angular.IScope, $ngBootbox: BootboxService) { $ngBootbox.alert('An important message!').then(function() { console.log('Alert closed'); @@ -21,7 +21,7 @@ class TestBootboxController { console.log('Prompt dismissed!'); }); - var options: IBootboxDialog = { + var options: NgBootboxDialog = { message: 'This is a message!', title: 'The title!', className: 'test-class', From b13a8c64ffd368b4528f222f404f67b4c7d76cfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Ba=C5=A1e?= Date: Wed, 11 Nov 2015 12:54:47 +0100 Subject: [PATCH 86/86] JQuery - removed number[] from .val() --- jquery/jquery-tests.ts | 1 - jquery/jquery.d.ts | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 13c568cb3..27eea1c81 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -3129,7 +3129,6 @@ function test_val() { $("#multiple").val(["Multiple2", "Multiple3"]); $("input").val(["check1", "check2", "radio1"]); $("input").val(1); - $("input").val([1, 2, 3]); } function test_selector() { diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 9cf3a5864..29b7697b2 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -1363,9 +1363,9 @@ interface JQuery { /** * Set the value of each element in the set of matched elements. * - * @param value A string of text, an array of strings, number or an array of numbers corresponding to the value of each matched element to set as selected/checked. + * @param value A string of text, an array of strings or number corresponding to the value of each matched element to set as selected/checked. */ - val(value: string|string[]|number|number[]): JQuery; + val(value: string|string[]|number): JQuery; /** * Set the value of each element in the set of matched elements. *