diff --git a/ajv/ajv-tests.ts b/ajv/ajv-tests.ts new file mode 100644 index 0000000000..e6413fd824 --- /dev/null +++ b/ajv/ajv-tests.ts @@ -0,0 +1,74 @@ +/// + +import * as Ajv from 'ajv'; +var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} +var validate = ajv.compile({}); +var valid = validate({}); +if (!valid) console.log(validate.errors); + +var valid = ajv.validate({}, {}); +if (!valid) console.log(ajv.errors); + +ajv.addSchema({}, 'mySchema'); +var valid = ajv.validate('mySchema', {}); +if (!valid) console.log(ajv.errorsText()); + +ajv.addKeyword('range', { + type: 'number', compile: function (sch, parentSchema) { + var min: any = sch[0]; + var max: any = sch[1]; + + return parentSchema.exclusiveRange === true + ? function (data) { return data > min && data < max; } + : function (data) { return data >= min && data <= max; } + } +}); + +var schema = { "range": [2, 4], "exclusiveRange": true }; +var validate = ajv.compile(schema); +console.log(validate(2.01)); // true +console.log(validate(3.99)); // true +console.log(validate(2)); // false +console.log(validate(4)); // false + +declare var request: any; +function loadSchema(uri: any, callback: any) { + request.json(uri, function (err: any, res: any, body: any) { + if (err || res.statusCode >= 400) + callback(err || new Error('Loading error: ' + res.statusCode)); + else + callback(null, body); + }); +} +var ajv = new Ajv({ loadSchema: loadSchema }); + +ajv.compileAsync(schema, function (err, validate) { + if (err) return; + var valid = validate({}); +}); + +declare var knex: any; +function checkIdExists(schema: any, data: any) { + return knex(schema.table) + .select('id') + .where('id', data) + .then(function (rows: any) { + return true; + }); +} + +var validate = ajv.compile(schema); + +(validate({ userId: 1, postId: 19 }) as PromiseLike) + .then(function (valid) { + // "valid" is always true here + console.log('Data is valid'); + }, function (err) { + if (!(err instanceof Ajv.ValidationError)) throw err; + // data is invalid + console.log('Validation errors:', err.errors); + }); + +var ajv = new Ajv({ /* async: 'es7', */ transpile: 'nodent' }); +var validate = ajv.compile(schema); // transpiled es7 async function +(validate({}) as PromiseLike).then(() => { }, () => { }); diff --git a/ajv/ajv.d.ts b/ajv/ajv.d.ts new file mode 100644 index 0000000000..d8bfd56ef3 --- /dev/null +++ b/ajv/ajv.d.ts @@ -0,0 +1,112 @@ +// Type definitions for ajv +// Project: https://github.com/epoberezkin/ajv +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "ajv" { + class Ajv { + /** + * Create Ajv instance. + */ + constructor(options?: Ajv.AjvOptions); + /** + * Generate validating function and cache the compiled schema for future use. + */ + compile(schema: any): Ajv.AjvValidate; + /** + * Asyncronous version of compile method that loads missing remote schemas using asynchronous function in options.loadSchema. + */ + compileAsync(schema: any, callback: (error: Error, validate: Ajv.AjvValidate) => void): void; + /** + * Validate data using passed schema (it will be compiled and cached). + */ + validate(schema: any, data: any): boolean | PromiseLike; + errors: Ajv.ValidationError[]; + /** + * Add schema(s) to validator instance. + */ + addSchema(schema: any, key: string): void; + /** + * Adds meta schema(s) that can be used to validate other schemas. + * That function should be used instead of addSchema because there may be instance options that would compile a meta schema incorrectly (at the moment it is removeAdditional option). + */ + addMetaSchema(schema: any, key: string): void; + /** + * Validates schema. + * This method should be used to validate schemas rather than validate due to the inconsistency of uri format in JSON-Schema standard. + */ + validateSchema(schema: any): Boolean; + /** + * Retrieve compiled schema previously added with addSchema by the key passed to addSchema or by its full reference (id). + * Returned validating function has schema property with the reference to the original schema. + */ + getSchema(key: string): Ajv.AjvValidate; + /** + * Remove added/cached schema. + * Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. + */ + removeSchema(schema: any): void; + /** + * Add custom format to validate strings. It can also be used to replace pre-defined formats for Ajv instance. + */ + addFormat(name: string, format: any): void; + /** + * Add custom validation keyword to Ajv instance. + */ + addKeyword(keyword: string, definition: Ajv.AjxKeywordDefinition): void; + errorsText(): any; + static ValidationError: Function; + } + namespace Ajv { + type AjvOptions = { + v5?: boolean; + allErrors?: boolean; + verbose?: boolean; + jsonPointers?: boolean; + uniqueItems?: boolean; + unicode?: boolean; + format?: string; + formats?: any; + schemas?: any; + missingRefs?: boolean; + loadSchema?(uri: string, callback: (error: Error, body: any) => void): void; + removeAdditional?: boolean; + useDefaults?: boolean; + coerceTypes?: boolean; + async?: any; + transpile?: string; + meta?: boolean; + validateSchema?: boolean; + addUsedSchema?: boolean; + inlineRefs?: boolean; + passContext?: boolean; + loopRequired?: number; + ownProperties?: boolean; + multipleOfPrecision?: boolean; + errorDataPath?: string, + messages?: boolean; + beautify?: boolean; + cache?: any; + } + type AjvValidate = ((data: any) => boolean | PromiseLike) & { + errors: ValidationError[]; + } + type AjxKeywordDefinition = { + async?: boolean; + type: string; + compile?: (schema: any, parentsSchema: any) => ((data: any) => boolean | PromiseLike); + validate?: (schema: any, data: any) => boolean; + } + type ValidationError = { + keyword: string; + dataPath: string; + schemaPath: string; + params: any; + message: string; + schema: any; + parentSchema: any; + data: any; + } + } + export = Ajv; +} diff --git a/alt/alt.d.ts b/alt/alt.d.ts index 20da159f35..575d476451 100644 --- a/alt/alt.d.ts +++ b/alt/alt.d.ts @@ -53,8 +53,8 @@ declare namespace AltJS { export type Source = {[name:string]: () => SourceModel}; export interface SourceModel { - local(state:any):any; - remote(state:any):Promise; + local(state:any, ...args: any[]):any; + remote(state:any, ...args: any[]):Promise; shouldFetch?(fetchFn:(...args:Array) => boolean):void; loading?:(args:any) => void; success?:(state:S) => void; diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts index 543467feac..7268150c75 100644 --- a/amcharts/AmCharts.d.ts +++ b/amcharts/AmCharts.d.ts @@ -26,6 +26,9 @@ declare namespace AmCharts { /** Clears all the charts on page, removes listeners and intervals. */ function clear(); + + /** Create chart by params. */ + function makeChart(selector: string, params: any, delay?: number): AmChart; /** AmPieChart class creates pie/donut chart. In order to display pie chart you need to set at least three properties - dataProvider, titleField and valueField. @example diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 5e780fe005..c19dae9dbd 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -247,6 +247,7 @@ declare namespace angular.material { extendPalette(name: string, palette: IPalette): IPalette; setDefaultTheme(theme: string): void; alwaysWatchTheme(alwaysWatch: boolean): void; + setNonce(nonce: string): void; } interface IDateLocaleProvider { diff --git a/angular-permission/angular-permission-tests.ts b/angular-permission/angular-permission-tests.ts index cc9cd7c367..c6d5b91a8d 100644 --- a/angular-permission/angular-permission-tests.ts +++ b/angular-permission/angular-permission-tests.ts @@ -1,10 +1,11 @@ /// -import permission = angular.permission; +import permissionNamespace = angular.permission; +import { permission, ngPermission, uiPermission } from "angular-permission"; angular - .module('fooModule', ['permission', 'user']) - .run(function (PermissionStore: permission.PermissionStore, User: any) { + .module('fooModule', [permission, ngPermission, uiPermission, 'user']) + .run(function (PermissionStore: permissionNamespace.PermissionStore, User: any) { // Define anonymous permission PermissionStore .definePermission('anonymous', function (stateParams) { @@ -22,8 +23,8 @@ angular hasPermissionDefinition(permission: string) : angular.IPromise; } - angular.module('barModule', ['permission', 'user']) - .run(function (PermissionStore: permission.PermissionStore, User: BackendUserService, $q: angular.IQService) { + angular.module('barModule', [permission, 'user']) + .run(function (PermissionStore: permissionNamespace.PermissionStore, User: BackendUserService, $q: angular.IQService) { PermissionStore // Define user permission calling back-end .definePermission('user', function (stateParams) { @@ -64,14 +65,14 @@ angular PermissionStore.removePermissionDefinition('user'); - let permissions: Array = PermissionStore.getStore(); + let permissions: Array = PermissionStore.getStore(); }); angular - .module('fooModule', ['permission', 'user']) - .run(function (RoleStore: permission.RoleStore, User: any) { + .module('fooModule', [permission, 'user']) + .run(function (RoleStore: permissionNamespace.RoleStore, User: any) { RoleStore // Permission array validated role // Library will internally validate if 'user' and 'editor' permissions are valid when checking if role is valid @@ -88,5 +89,5 @@ angular RoleStore.removeRoleDefinition('user'); - let roles: Array = RoleStore.getStore(); + let roles: Array = RoleStore.getStore(); }); diff --git a/angular-permission/angular-permission.d.ts b/angular-permission/angular-permission.d.ts index fecbafb29b..138c8892ce 100644 --- a/angular-permission/angular-permission.d.ts +++ b/angular-permission/angular-permission.d.ts @@ -173,3 +173,9 @@ declare namespace angular.permission { options?: angular.ui.IStateOptions; } } + +declare module "angular-permission" { + export var permission: string; + export var ngPermission: string; + export var uiPermission: string; +} diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index de7db4eb54..0187e33cab 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -95,6 +95,7 @@ declare namespace angular.translate { use(key: string): ITranslateProvider; storageKey(): string; storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here + uniformLanguageTag(options: string | Object): ITranslateProvider; useUrlLoader(url: string): ITranslateProvider; useStaticFilesLoader(options: IStaticFilesLoaderOptions | { files: IStaticFilesLoaderOptions[] }): ITranslateProvider; useLoader(loaderFactory: string, options?: any): ITranslateProvider; diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index bb028f3425..e64496604f 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -118,14 +118,14 @@ declare namespace angular { fromJson(json: string): any; identity(arg?: T): T; injector(modules?: any[], strictDi?: boolean): auto.IInjectorService; - isArray(value: any): boolean; - isDate(value: any): boolean; + isArray(value: any): value is Array; + isDate(value: any): value is Date; isDefined(value: any): boolean; isElement(value: any): boolean; - isFunction(value: any): boolean; - isNumber(value: any): boolean; - isObject(value: any): boolean; - isString(value: any): boolean; + isFunction(value: any): value is Function; + isNumber(value: any): value is number; + isObject(value: any): value is Object; + isString(value: any): value is string; isUndefined(value: any): boolean; lowercase(str: string): string; @@ -387,6 +387,7 @@ declare namespace angular { $invalid: boolean; $submitted: boolean; $error: any; + $name: string; $pending: any; $addControl(control: INgModelController | IFormController): void; $removeControl(control: INgModelController | IFormController): void; diff --git a/applicationinsights-js/applicationinsights-js.d.ts b/applicationinsights-js/applicationinsights-js.d.ts index 9047f44b9f..ba154e5fe6 100644 --- a/applicationinsights-js/applicationinsights-js.d.ts +++ b/applicationinsights-js/applicationinsights-js.d.ts @@ -790,7 +790,7 @@ declare module Microsoft.ApplicationInsights { } declare module 'applicationinsights-js' { - export = appInsights; + export let AppInsights: Microsoft.ApplicationInsights.IAppInsights; } declare var appInsights: Microsoft.ApplicationInsights.IAppInsights; \ No newline at end of file diff --git a/async/async-tests.ts b/async/async-tests.ts index e7af9120a1..63640cecf6 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -392,13 +392,6 @@ function (results) { ]); }); -var sys; -var iterator = async.iterator([ - function () { sys.p('one'); }, - function () { sys.p('two'); }, - function () { sys.p('three'); } -]); - async.parallel([ async.apply(fs.writeFile, 'testfile1', 'test1'), async.apply(fs.writeFile, 'testfile2', 'test2'), diff --git a/async/async.d.ts b/async/async.d.ts index 6288a269a1..96da35c1ea 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Async 1.4.2 +// Type definitions for Async 2.0.1 // Project: https://github.com/caolan/async // Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -37,6 +37,13 @@ interface AsyncQueue { pause(): void resume(): void; kill(): void; + workersList(): { + data: T, + callback: Function + }[]; + error(error: Error, data: any): void; + unsaturated(): void; + buffer: number; } interface AsyncPriorityQueue { @@ -54,6 +61,14 @@ interface AsyncPriorityQueue { pause(): void; resume(): void; kill(): void; + workersList(): { + data: T, + priority: number, + callback: Function + }[]; + error(error: Error, data: any): void; + unsaturated(): void; + buffer: number; } interface AsyncCargo { @@ -85,6 +100,9 @@ interface Async { map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; mapSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + mapValuesLimit(obj: {[name: string]: T}, limit: number, iteratee: (value: string, key: T, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; + mapValues(obj: {[name: string]: T}, iteratee: (value: string, key: T, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; + mapValuesSeries: typeof async.mapValues; filter(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; select(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; filterSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; @@ -100,11 +118,17 @@ interface Async { reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; detect(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; + find: typeof async.detect; detectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; + findSeries: typeof async.detectSeries; detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; + findLimit: typeof async.detectLimit; sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; some(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + anyLimit: typeof async.someLimit; + someSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + anySeries: typeof async.someSeries; any(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; every(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; everyLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; @@ -134,18 +158,35 @@ interface Async { queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; - auto(tasks: any, callback?: (error: Error, results: any) => void): void; + auto(tasks: any, concurrency?: number, callback?: (error: Error, results: any) => void): void; + autoInject(tasks: any, callback?: (error: Error, results: any) => void): void; retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: (error: Error, results: any) => void): void; retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: (error: Error, results: any) => void): void; - iterator(tasks: Function[]): Function; + retryable(opts: number | {times: number, interval: number}, task: AsyncFunction): AsyncFunction; apply(fn: Function, ...arguments: any[]): AsyncFunction; - nextTick(callback: Function): void; - setImmediate(callback: Function): void; + nextTick(callback: Function, ...args: any[]): void; + setImmediate: typeof async.nextTick; + + allLimit(arr: T[], limit: number, iteratee: AsyncBooleanIterator, cb?: (result: boolean) => any) : any; + everySeries(arr: T[], iteratee: AsyncBooleanIterator, cb?: (result: boolean) => any) : any + allSeries: typeof async.everySeries; + + reflect(fn: AsyncFunction) : (callback: (err: void, result: {error?: Error, value?: T}) => void) => void; + reflectAll(tasks: AsyncFunction[]): ((callback: (err: void, result: {error?: Error, value?: T}) => void) => void)[]; + + timeout(fn: AsyncFunction, milliseconds: number, info: any): AsyncFunction; times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + transform(arr: T[], iteratee: (acc: R[], item: T, key: string, callback: (error?: Error) => void) => void): void; + transform(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: string, callback: (error?: Error) => void) => void): void; + transform(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: Error) => void) => void): void; + transform(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: Error) => void) => void): void; + + race(tasks: (AsyncFunction)[], callback: AsyncResultCallback) : void; + // Utils memoize(fn: Function, hasher?: Function): Function; unmemoize(fn: Function): Function; @@ -155,7 +196,6 @@ interface Async { wrapSync(fn: Function): Function; log(fn: Function, ...arguments: any[]): void; dir(fn: Function, ...arguments: any[]): void; - noConflict(): Async; } declare var async: Async; diff --git a/autobahn/autobahn.d.ts b/autobahn/autobahn.d.ts index 7fd344f727..bb7a0c86ae 100644 --- a/autobahn/autobahn.d.ts +++ b/autobahn/autobahn.d.ts @@ -163,6 +163,7 @@ declare namespace autobahn { } interface IPublishOptions { + acknowledge?: boolean; exclude?: number[]; eligible?: number[]; disclose_me?: Boolean; diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts new file mode 100644 index 0000000000..fd289dcb7f --- /dev/null +++ b/aws-lambda/aws-lambda-tests.ts @@ -0,0 +1,49 @@ +/// + +import lambda = require('aws-lambda'); + +var str: string; +var date: Date; +var sns: lambda.SNS; +var kinesis: lambda.Kinesis; +var recordsList: lambda.Record[]; +var anyObj: any; +var num: number; + +/* Records */ +var records: lambda.Records; + +recordsList = records.Records; + +/* Record */ +var record: lambda.Record; + +str = record.EventVersion; +str = record.EventSubscriptionArn; +str = record.EnventSource; +sns = record.Sns; +kinesis = record.kinesis; + +/* SNS */ +str = sns.Type; +str = sns.MessageId; +str = sns.TopicArn; +str = sns.Subject; +str = sns.Message; +date = sns.Timestamp; + +/* Kinesis */ +var kinesis: lambda.Kinesis; + +str = kinesis.data; + +/* Context */ +var context: lambda.Context; + +context.log(str, anyObj); +context.fail(str); +context.succeed(str); +context.succeed(anyObj); +context.succeed(str, anyObj); +str = context.awsRequestId; +num = context.getRemainingTimeInMillis(); \ No newline at end of file diff --git a/aws-lambda/aws-lambda.d.ts b/aws-lambda/aws-lambda.d.ts new file mode 100644 index 0000000000..cdd8e2f506 --- /dev/null +++ b/aws-lambda/aws-lambda.d.ts @@ -0,0 +1,43 @@ +// Type definitions for AWS Lambda +// Project: http://docs.aws.amazon.com/lambda +// Definitions by: Michael Skarum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "aws-lambda" { + + export interface Records { + Records: Record[]; + } + interface Record { + EventVersion: string; + EventSubscriptionArn: string; + EnventSource: string; + Sns: SNS; + kinesis: Kinesis; + } + interface SNS { + Type: string; + MessageId: string; + TopicArn: string; + Subject: string; + Message: string; + Timestamp: Date; + } + + interface Kinesis { + data: string; + } + + export interface Context { + log(message: string, object: any): void; + fail(message: string): void; + succeed(message: string): void; + succeed(object: any): void; + succeed(message: string, object: any): void; + awsRequestId: string; + getRemainingTimeInMillis(): number; + } + + + export type Callback = (error?: Error, message?: string) => void; +} \ No newline at end of file diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index a5341fcb45..f061353812 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -9,1496 +9,1804 @@ declare module "aws-sdk" { - export var config: ClientConfig; + export var config: ClientConfig; - export function Config(json: any): void; + export function Config(json: any): void; - export class Credentials { - constructor(accessKeyId: string, secretAccessKey: string, sessionToken?: string); - accessKeyId: string; - } + export class Credentials { + constructor(accessKeyId: string, secretAccessKey: string, sessionToken?: string); + accessKeyId: string; + } - export class EnvironmentCredentials extends Credentials { - constructor(profile: string); - } + export class EnvironmentCredentials extends Credentials { + constructor(profile: string); + } - export interface Logger { - write?: (chunk: any, encoding?: string, callback?: () => void) => void; - log?: (...messages: any[]) => void; - } + export interface Logger { + write?: (chunk: any, encoding?: string, callback?: () => void) => void; + log?: (...messages: any[]) => void; + } - export interface HttpOptions { - proxy?: string; - agent?: any; - timeout?: number; - xhrAsync?: boolean; - xhrWithCredentials?: boolean; - } + export interface HttpOptions { + proxy?: string; + agent?: any; + timeout?: number; + xhrAsync?: boolean; + xhrWithCredentials?: boolean; + } - export class Endpoint { - constructor(endpoint:string); + export class Endpoint { + constructor(endpoint: string); - host:string; - hostname:string; - href:string; - port:number; - protocol:string; - } + host: string; + hostname: string; + href: string; + port: number; + protocol: string; + } - export interface Services { - autoscaling?: any; - cloudformation?: any; - cloudfront?: any; - cloudsearch?: any; - cloudsearchdomain?: any; - cloudtrail?: any; - cloudwatch?: any; - cloudwatchlogs?: any; - cognitoidentity?: any; - cognitosync?: any; - datapipeline?: any; - directconnect?: any; - dynamodb?: any; - ec2?: any; - ecs?: any; - elasticache?: any; - elasticbeanstalk?: any; - elastictranscoder?: any; - elb?: any; - emr?: any; - glacier?: any; - httpOptions?: HttpOptions; - iam?: any; - importexport?: any; - kinesis?: any; - opsworks?: any; - rds?: any; - redshift?: any; - route53?: any; - route53domains?: any; - s3?: any; - ses?: any; - simpledb?: any; - sns?: any; - sqs?: any; - storagegateway?: any; - sts?: any; - support?: any; - swf?: any; - } + interface AwsError extends Error { + stack: string; + } - export interface ClientConfigPartial extends Services { - credentials?: Credentials; - region?: string; - accessKeyId?: string; - secretAccessKey?: string; - computeChecksums?: boolean; - convertResponseTypes?: boolean; - logger?: Logger; - maxRedirects?: number; - maxRetries?: number; - paramValidation?: boolean; - s3ForcePathStyle?: boolean; - apiVersion?: any; - apiVersions?: Services; - signatureVersion?: string; - sslEnabled?: boolean; - systemClockOffset?: number; - } + export interface Services { + autoscaling?: any; + cloudformation?: any; + cloudfront?: any; + cloudsearch?: any; + cloudsearchdomain?: any; + cloudtrail?: any; + cloudwatch?: any; + cloudwatchlogs?: any; + cognitoidentity?: any; + cognitosync?: any; + datapipeline?: any; + directconnect?: any; + dynamodb?: any; + ec2?: any; + ecs?: any; + elasticache?: any; + elasticbeanstalk?: any; + elastictranscoder?: any; + elb?: any; + emr?: any; + glacier?: any; + httpOptions?: HttpOptions; + iam?: any; + importexport?: any; + kinesis?: any; + opsworks?: any; + rds?: any; + redshift?: any; + route53?: any; + route53domains?: any; + s3?: any; + ses?: any; + simpledb?: any; + sns?: any; + sqs?: any; + storagegateway?: any; + sts?: any; + support?: any; + swf?: any; + } - export interface ClientConfig extends ClientConfigPartial { - update?: (options: ClientConfigPartial, allUnknownKeys?: boolean) => void; - getCredentials?: (callback: (err?: any) => void) => void ; - loadFromPath?: (path: string) => void; - credentials: Credentials; - region: string; - } + export interface ClientConfigPartial extends Services { + credentials?: Credentials; + region?: string; + accessKeyId?: string; + secretAccessKey?: string; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + logger?: Logger; + maxRedirects?: number; + maxRetries?: number; + paramValidation?: boolean; + s3ForcePathStyle?: boolean; + apiVersion?: any; + apiVersions?: Services; + signatureVersion?: string; + sslEnabled?: boolean; + systemClockOffset?: number; + } - export class SQS { - constructor(options?: any); - endpoint:Endpoint; + export interface ClientConfig extends ClientConfigPartial { + update?: (options: ClientConfigPartial, allUnknownKeys?: boolean) => void; + getCredentials?: (callback: (err?: any) => void) => void; + loadFromPath?: (path: string) => void; + credentials: Credentials; + region: string; + } - 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 Lambda { + constructor(options?: any); + endpoint: Endpoint; - export class SES { - constructor(options?: any); - public client: Ses.Client; - } + addPermission(params: Lambda.AddPermissionParams, callback: (err: AwsError, data: any) => void): void; + createAlias(params: Lambda.CreateAliasParams, callback: (err: AwsError, data: any) => void): void; + createEventSourceMapping(params: Lambda.CreateEventSourceMappingParams, callback: (err: AwsError, data: any) => void): void; + createFunction(params: Lambda.CreateFunctionParams, callback: (err: AwsError, data: any) => void): void; + deleteAlias(params: Lambda.DeleteAliasParams, callback: (err: AwsError, data: any) => void): void; + deleteEventSourceMapping(params: Lambda.DeleteEventSourceMappingParams, callback: (err: AwsError, data: any) => void): void; + deleteFunction(params: Lambda.DeleteFunctionParams, callback: (err: AwsError, data: any) => void): void; + getAlias(params: Lambda.GetAliasParams, callback: (err: AwsError, data: any) => void): void; + getEventSourceMapping(params: Lambda.GetEventSourceMappingParams, callback: (err: AwsError, data: any) => void): void; + getFunction(params: Lambda.GetFunctionParams, callback: (err: AwsError, data: any) => void): void; + getFunctionConfiguration(params: Lambda.GetFunctionConfigurationParams, callback: (err: AwsError, data: any) => void): void; + getPolicy(params: Lambda.GetPolicyParams, callback: (err: AwsError, data: any) => void): void; + invoke(params: Lambda.InvokeParams, callback: (err: AwsError, data: any) => void): void; + listAliases(params: Lambda.ListAliasesParams, callback: (err: AwsError, data: any) => void): void; + listEventSourceMappings(params: Lambda.ListEventSourceMappingsParams, callback: (err: AwsError, data: any) => void): void; + listFunctions(params: Lambda.ListFunctionsParams, callback: (err: AwsError, data: any) => void): void; + listVersionsByFunction(params: Lambda.ListVersionsByFunctionParams, callback: (err: AwsError, data: any) => void): void; + publishVersion(params: Lambda.PublishVersionParams, callback: (err: AwsError, data: any) => void): void; + removePermission(params: Lambda.RemovePermissionParams, callback: (err: AwsError, data: any) => void): void; + updateAlias(params: Lambda.UpdateAliasParams, callback: (err: AwsError, data: any) => void): void; + updateEventSourceMapping(params: Lambda.UpdateEventSourceMappingParams, callback: (err: AwsError, data: any) => void): void; + updateFunctionCode(params: Lambda.UpdateFunctionCodeParams, callback: (err: AwsError, data: any) => void): void; + updateFunctionConfiguration(params: Lambda.UpdateFunctionConfigurationParams, callback: (err: AwsError, data: any) => void): void; + } - export class SNS { - constructor(options?: any); - publish(request: Sns.PublishRequest, callback: (err: any, data: any) => void): void; - } + export class SQS { + constructor(options?: any); + endpoint: Endpoint; - export class SimpleWorkflow { - constructor(options?: any); - public client: Swf.Client; - } + addPermission(params: SQS.AddPermissionParams, callback: (err: AwsError, data: any) => void): void; + changeMessageVisibility(params: SQS.ChangeMessageVisibilityParams, callback: (err: AwsError, data: any) => void): void; + changeMessageVisibilityBatch(params: SQS.ChangeMessageVisibilityBatchParams, callback: (err: AwsError, data: SQS.ChangeMessageVisibilityBatchResponse) => void): void; + createQueue(params: SQS.CreateQueueParams, callback: (err: AwsError, data: SQS.CreateQueueResult) => void): void; + deleteMessage(params: SQS.DeleteMessageParams, callback: (err: AwsError, data: any) => void): void; + deleteMessageBatch(params: SQS.DeleteMessageBatchParams, callback: (err: AwsError, data: SQS.DeleteMessageBatchResult) => void): void; + deleteQueue(params: { QueueUrl: string; }, callback: (err: AwsError, data: any) => void): void; + getQueueAttributes(params: SQS.GetQueueAttributesParams, callback: (err: AwsError, data: SQS.GetQueueAttributesResult) => void): void; + getQueueUrl(params: SQS.GetQueueUrlParams, callback: (err: AwsError, data: { QueueUrl: string; }) => void): void; + listDeadLetterSourceQueues(params: { QueueUrl: string }, callback: (err: AwsError, data: { queueUrls: string[] }) => void): void; + listQueues(params: { QueueNamePrefix?: string }, callback: (err: AwsError, data: { QueueUrls: string[] }) => void): void; + purgeQueue(params: { QueueUrl: string }, callback: (err: AwsError, data: any) => void): void; + receiveMessage(params: SQS.ReceiveMessageParams, callback: (err: AwsError, data: SQS.ReceiveMessageResult) => void): void; + removePermission(params: { QueueUrl: string, Label: string }, callback: (err: AwsError, data: any) => void): void; + sendMessage(params: SQS.SendMessageParams, callback: (err: AwsError, data: SQS.SendMessageResult) => void): void; + sendMessageBatch(params: SQS.SendMessageBatchParams, callback: (err: AwsError, data: SQS.SendMessageBatchResult) => void): void; + setQueueAttributes(params: SQS.SetQueueAttributesParams, callback: (err: AwsError, data: any) => void): void; + } - export class S3 { - constructor(options?: any); - getObject(params: s3.GetObjectRequest, callback: (err: Error, data: any) => void): void; - putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void; - deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void; - headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void; - getSignedUrl(operation: string, params: any): string; - getSignedUrl(operation: string, params: any, callback: (err: Error, url: string) => void): void; - upload(params?: s3.PutObjectRequest, options?: s3.UploadOptions, callback?: (err: Error, data: any) => void): void; - } + export class SES { + constructor(options?: any); + endpoint: Endpoint; - export class STS{ - constructor(options?: any); + sendEmail(params: any, callback: (err: any, data: SES.SendEmailResult) => void): void; + } + + export class SNS { + constructor(options?: any); + endpoint: Endpoint; + + publish(request: Sns.PublishRequest, callback: (err: any, data: any) => void): void; + } + + export class SWF { + constructor(options?: any); + endpoint: Endpoint; + + countClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countPendingActivityTasks(params: any, callback: (err: any, data: any) => void): void; + countPendingDecisionTasks(params: any, callback: (err: any, data: any) => void): void; + deprecateActivityType(params: any, callback: (err: any, data: any) => void): void; + deprecateDomain(params: any, callback: (err: any, data: any) => void): void; + deprecateWorkflowType(params: any, callback: (err: any, data: any) => void): void; + describeActivityType(params: any, callback: (err: any, data: any) => void): void; + describeDomain(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowType(params: any, callback: (err: any, data: any) => void): void; + getWorkflowExecutionHistory(params: any, callback: (err: any, data: any) => void): void; + listActivityTypes(params: any, callback: (err: any, data: any) => void): void; + listClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listDomains(params: any, callback: (err: any, data: any) => void): void; + listOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listWorkflowTypes(params: any, callback: (err: any, data: any) => void): void; + pollForActivityTask(params: any, callback: (err: any, data: Swf.ActivityTask) => void): void; + pollForDecisionTask(params: any, callback: (err: any, data: Swf.DecisionTask) => void): void; + recordActivityTaskHeartbeat(params: any, callback: (err: any, data: any) => void): void; + registerActivityType(params: any, callback: (err: any, data: any) => void): void; + registerDomain(params: any, callback: (err: any, data: any) => void): void; + registerWorkflowType(params: any, callback: (err: any, data: any) => void): void; + requestCancelWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + respondActivityTaskCanceled(params: Swf.RespondActivityTaskCanceledRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskCompleted(params: Swf.RespondActivityTaskCompletedRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskFailed(params: Swf.RespondActivityTaskFailedRequest, callback: (err: any, data: any) => void): void; + respondDecisionTaskCompleted(params: Swf.RespondDecisionTaskCompletedRequest, callback: (err: any, data: any) => void): void; + signalWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + startWorkflowExecution(params: any, callback: (err: any, data: Swf.StartWorkflowExecutionResult) => void): void; + terminateWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + + } + + export class S3 { + constructor(options?: any); + endpoint: Endpoint; + + getObject(params: s3.GetObjectRequest, callback: (err: Error, data: any) => void): void; + putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void; + deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void; + headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void; + getSignedUrl(operation: string, params: any): string; + getSignedUrl(operation: string, params: any, callback: (err: Error, url: string) => void): void; + upload(params?: s3.PutObjectRequest, options?: s3.UploadOptions, callback?: (err: Error, data: any) => void): void; + listObjects(params: s3.ListObjectRequest, callback: (err: Error, data: s3.ListObjectResponse) => void): void; + listObjectsV2(params: s3.ListObjectV2Request, callback: (err: Error, data: s3.ListObjectV2Response) => void): void; + } + + export class STS { + constructor(options?: any); + endpoint: Endpoint; /** * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that you can use to access AWS resources that you might not normally have access to. */ - assumeRole(params: sts.AssumeRoleParams, callback: (err: any, data: sts.AssumeRoleCallbackData) => void): void; + assumeRole(params: sts.AssumeRoleParams, callback: (err: any, data: sts.AssumeRoleCallbackData) => void): void; /** * Returns a set of temporary security credentials for users who have been authenticated via a SAML authentication response. */ - assumeRoleWithSAML(params: sts.AssumeRoleWithSAMLParams, callback: (err: any, data: any) => void): void; + assumeRoleWithSAML(params: sts.AssumeRoleWithSAMLParams, callback: (err: any, data: any) => void): void; /** * Returns a set of temporary security credentials for users who have been authenticated in a mobile or web application with a web identity provider, such as Amazon Cognito, Login with Amazon, Facebook, Google, or any OpenID Connect-compatible identity provider. */ - assumeRoleWithWebIdentity(params: sts.AssumeRoleWithWebIdentityParams, callback: (err: any, data: any) => void): void; + assumeRoleWithWebIdentity(params: sts.AssumeRoleWithWebIdentityParams, callback: (err: any, data: any) => void): void; /** * Creates a credentials object from STS response data containing credentials information. */ - credentialsFrom(params: sts.CredentialsFromParams, callback: (err: any, data: any) => void): void; + credentialsFrom(params: sts.CredentialsFromParams, callback: (err: any, data: any) => void): void; /** * Decodes additional information about the authorization status of a request from an encoded message returned in response to an AWS request. */ - decodeAuthorizationMessage(params: sts.DecodeAuthorizationMessageParams, callback: (err: any, data: any) => void): void; + decodeAuthorizationMessage(params: sts.DecodeAuthorizationMessageParams, callback: (err: any, data: any) => void): void; /** * Returns details about the IAM identity whose credentials are used to call the API. */ - getCallerIdentity(params: {}, callback: (err: any, data: any) => void): void; + getCallerIdentity(params: {}, callback: (err: any, data: any) => void): void; /** * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) for a federated user. */ - getFederationToken(params: sts.GetFederationTokenParams, callback: (err: any, data: any) => void): void; + getFederationToken(params: sts.GetFederationTokenParams, callback: (err: any, data: any) => void): void; /** * Returns a set of temporary credentials for an AWS account or IAM user. */ - getSessionToken(params: sts.GetSessionTokenParams, callback: (err: any, data: any) => void): void; + getSessionToken(params: sts.GetSessionTokenParams, callback: (err: any, data: any) => void): void; - } + } - export class ECS { - constructor(options?: any); - /** - * Runs and maintains a desired number of tasks from a specified task definition. If the number of tasks running in a service drops below desiredCount, Amazon ECS spawns another instantiation of the task in the specified cluster. To update an existing service, see UpdateService. - */ - createService(params: ecs.CreateServicesParams, callback: (err: any, data: any) => void): void; + export class ECS { + constructor(options?: any); + endpoint: Endpoint; + /** + * Runs and maintains a desired number of tasks from a specified task definition. If the number of tasks running in a service drops below desiredCount, Amazon ECS spawns another instantiation of the task in the specified cluster. To update an existing service, see UpdateService. + */ + createService(params: ecs.CreateServicesParams, callback: (err: any, data: any) => void): void; /** * Describes one or more of your clusters. */ - describeClusters(params: ecs.DescribeClustersParams, callback: (err: any, data: any) => void): void; + describeClusters(params: ecs.DescribeClustersParams, callback: (err: any, data: any) => void): void; /** * Describes the specified services running in your cluster. */ - describeServices(params: ecs.DescribeServicesParams, callback: (err: any, data: any) => void): void; + describeServices(params: ecs.DescribeServicesParams, callback: (err: any, data: any) => void): void; /** * Describes a specified task or tasks. */ - describeTasks(params: ecs.DescribeTasksParams, callback: (err: any, data: any) => void): void; + describeTasks(params: ecs.DescribeTasksParams, callback: (err: any, data: any) => void): void; /** * Describes a task definition. You can specify a family and revision to find information about a specific task definition, or you can simply specify the family to find the latest ACTIVE revision in that family. */ - describeTaskDefinition(params: ecs.DescribeTaskDefinitionParams, callback: (err: any, data: any) => void): void; + describeTaskDefinition(params: ecs.DescribeTaskDefinitionParams, callback: (err: any, data: any) => void): void; /** * Registers a new task definition from the supplied family and containerDefinitions. Optionally, you can add data volumes to your containers with the volumes parameter. For more information about task definition parameters and defaults, see Amazon ECS Task Definitions in the Amazon EC2 Container Service Developer Guide. */ - registerTaskDefinition(params: ecs.RegisterTaskDefinitionParams, callback: (err: any, data: any) => void): void; + registerTaskDefinition(params: ecs.RegisterTaskDefinitionParams, callback: (err: any, data: any) => void): void; /** * Modifies the desired count, deployment configuration, or task definition used in a service. */ - updateService(params: ecs.UpdateServiceParams, callback: (err: any, data: any) => void): void; - } - - export class DynamoDB { - constructor(options?: any); - } - - // ========================================================== - - export module DynamoDB { - - interface _DDBDC_Generic { - TableName: string; - ExpressionAttributeNames?: string[]; - ReturnConsumedCapacity?: "INDEXES" | "TOTAL" | "NONE"; - } - - type _DDBDC_ComparisonOperator = "EQ" | "NE" | "IN" | "LE" | "LT" | "GE" | "GT" | "BETWEEN" | "NOT_NULL" | "NULL" | "CONTAINS" | "NOT_CONTAINS" | "BEGINS_WITH" - type _DDBDC_Keys = { [someKey: string]: any }; - type _DDBDC_KeyComparison = { - [someKey: string]: { - AttributeValueList: any[]; - ComparisonOperator: _DDBDC_ComparisonOperator; - } - }; - - interface _DDBDC_Reader extends _DDBDC_Generic { - ConsistentRead?: boolean; - ProjectionExpression?: string; - AttributesToGet?: string[]; - } - - interface _DDBDC_Writer extends _DDBDC_Generic { - ExpressionAttributeValues?: _DDBDC_Keys; - ReturnItemCollectionMetrics?: "SIZE" | "NONE"; - ReturnValues?: "NONE" | "ALL_OLD" | "UPDATED_OLD" | "ALL_NEW" | "UPDATED_NEW"; - ConditionExpression?: string; - ConditionalOperator?: "AND" | "OR"; - Expected?: { - [someKey: string]: { - AttributeValueList: any[]; - ComparisonOperator: _DDBDC_ComparisonOperator; - Exists: boolean; - Value: any; - } - } - } - - interface UpdateParam extends _DDBDC_Writer { - Key: _DDBDC_Keys; - AttributeUpdates: { - [someKey: string]: { - Action: "PUT" | "ADD" | "DELETE"; - Value: any - } - } - } - - interface QueryParam extends _DDBDC_Reader { - ConditionalOperator?: "AND" | "OR"; - ExclusiveStartKey?: _DDBDC_Keys; - ExpressionAttributeValues?: _DDBDC_Keys; - FilterExpression?: string; - IndexName?: string; - KeyConditionExpression?: string; - KeyConditions?: _DDBDC_KeyComparison; - Limit?: number; - QueryFilter?: _DDBDC_KeyComparison; - ScanIndexForward?: boolean; - Select?: "ALL_ATTRIBUTES" | "ALL_PROJECTED_ATTRIBUTES" | "SPECIFIC_ATTRIBUTES" | "COUNT"; - } - - interface ScanParam extends QueryParam { - Segment?: number; - ScanFilter?: _DDBDC_KeyComparison; - TotalSegments?: number; - } - - interface GetParam extends _DDBDC_Reader { - Key: _DDBDC_Keys; - } - - interface PutParam extends _DDBDC_Writer { - Item: _DDBDC_Keys; - } - - interface DeleteParam extends _DDBDC_Writer { - Key: _DDBDC_Keys; - } - - export class DocumentClient { - constructor(options?: any); - get(params: GetParam, next: (err: any, data: any) => void): void; - put(params: PutParam, next: (err: any, data: any) => void): void; - delete(params: DeleteParam, next: (err: any, data: any) => void): void; - query(params: QueryParam, next: (err: any, data: any) => void): void; - scan(params: ScanParam, next: (err: any, data: any) => void): void; - update(params: UpdateParam, next: (err: any, data: any) => void): void; - createSet(list: any[], options?: { validate?: boolean }): { values: any[], type: string }; - batchGet(params: any, next: (err: any, data: any) => void): void; - batchWrite(params: any, next: (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 SendMessageParams { - QueueUrl?: string; - MessageBody: string; - DelaySeconds?: number; - MessageAttributes?: { [name:string]: MessageAttribute; } - } - - export interface ReceiveMessageParams { - QueueUrl: string; - MaxNumberOfMessages?: number; - VisibilityTimeout?: number; - AttributeNames?: string[]; - MessageAttributeNames?: string[]; - WaitTimeSeconds?:number; - } - - export interface DeleteMessageBatchParams { - QueueUrl: string; - Entries: DeleteMessageBatchRequestEntry[]; - } - - export interface DeleteMessageBatchRequestEntry { - Id: string; - ReceiptHandle: string; - } - - export interface DeleteMessageParams { - QueueUrl: string; - ReceiptHandle: string; - } - - export interface SendMessageBatchParams { - QueueUrl: string; - Entries: SendMessageBatchRequestEntry[]; - } - - export interface SendMessageBatchRequestEntry { - Id: string; - MessageBody: string; - DelaySeconds?: number; - MessageAttributes?: { [name:string]: MessageAttribute; } - } - - export interface CreateQueueParams { - QueueName: string; - Attributes: QueueAttributes; - } - - 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 interface ReceiveMessageResult { - Messages: Message[]; - } - - export interface Message { - MessageId: string; - ReceiptHandle: string; - MD5OfBody: string; - Body: string; - Attributes: { [name:string]:any }; - MD5OfMessageAttributes:string; - MessageAttributes: { [name:string]: MessageAttribute; } - } - - 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 interface DeleteMessageBatchResultEntry { - Id: string; - } - - export interface BatchResultErrorEntry { - Id: string; - Code: string; - Message?: string; - SenderFault: boolean; - } - - export interface SendMessageBatchResult { - Successful: SendMessageBatchResultEntry[]; - Failed: BatchResultErrorEntry[]; - } - - export interface SendMessageBatchResultEntry { - Id: string; - MessageId: string; - MD5OfMessageBody: string; - MD5OfMessageAttributes:string; - } - - export interface CreateQueueResult { - QueueUrl: string; - } - - export interface SetQueueAttributesParams { - QueueUrl: string; - Attributes: QueueAttributes; - } - - } - - export module Ses { - - export interface Client { - config: ClientConfig; - - sendEmail(params: any, callback: (err: any, data: SendEmailResult) => void): void; - } - - export interface SendEmailRequest { - Source: string; - Destination: Destination; - Message: Message; - ReplyToAddresses: string[]; - ReturnPath: string; - } - - export class Destination { - ToAddresses: string[]; - CcAddresses: string[]; - BccAddresses: string[]; - } - - export class Message { - Subject: Content; - Body: Body; - } - - export class Content { - Data: string; - Charset: string; - } - - export class Body { - Text: Content; - Html: Content; - } - - export class SendEmailResult { - MessageId: string; - } - - } - - export module Swf { - - export class Client { - //constructor(options?: any); - public config: ClientConfig; - - countClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - countOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - countPendingActivityTasks(params: any, callback: (err: any, data: any) => void): void; - countPendingDecisionTasks(params: any, callback: (err: any, data: any) => void): void; - deprecateActivityType(params: any, callback: (err: any, data: any) => void): void; - deprecateDomain(params: any, callback: (err: any, data: any) => void): void; - deprecateWorkflowType(params: any, callback: (err: any, data: any) => void): void; - describeActivityType(params: any, callback: (err: any, data: any) => void): void; - describeDomain(params: any, callback: (err: any, data: any) => void): void; - describeWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - describeWorkflowType(params: any, callback: (err: any, data: any) => void): void; - getWorkflowExecutionHistory(params: any, callback: (err: any, data: any) => void): void; - listActivityTypes(params: any, callback: (err: any, data: any) => void): void; - listClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - listDomains(params: any, callback: (err: any, data: any) => void): void; - listOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - listWorkflowTypes(params: any, callback: (err: any, data: any) => void): void; - pollForActivityTask(params: any, callback: (err: any, data: ActivityTask) => void): void; - pollForDecisionTask(params: any, callback: (err: any, data: DecisionTask) => void): void; - recordActivityTaskHeartbeat(params: any, callback: (err: any, data: any) => void): void; - registerActivityType(params: any, callback: (err: any, data: any) => void): void; - registerDomain(params: any, callback: (err: any, data: any) => void): void; - registerWorkflowType(params: any, callback: (err: any, data: any) => void): void; - requestCancelWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - respondActivityTaskCanceled(params: RespondActivityTaskCanceledRequest, callback: (err: any, data: any) => void): void; - respondActivityTaskCompleted(params: RespondActivityTaskCompletedRequest, callback: (err: any, data: any) => void): void; - respondActivityTaskFailed(params: RespondActivityTaskFailedRequest, callback: (err: any, data: any) => void): void; - respondDecisionTaskCompleted(params: RespondDecisionTaskCompletedRequest, callback: (err: any, data: any) => void): void; - signalWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - startWorkflowExecution(params: any, callback: (err: any, data: StartWorkflowExecutionResult) => void): void; - terminateWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - } - - export interface PollForActivityTaskRequest { - domain?: string; - taskList?: TaskList; - identity?: string; - } - - export interface TaskList { - name?: string; - } - - export interface PollForDecisionTaskRequest { - domain?: string; - taskList?: TaskList; - identity?: string; - nextPageToken?: string; - maximumPageSize?: number; - reverseOrder?: Boolean; - } - - export interface StartWorkflowExecutionRequest { - domain?: string; - workflowId?: string; - workflowType?: WorkflowType; - taskList?: TaskList; - input?: string; - executionStartToCloseTimeout?: string; - tagList?: string[]; - taskStartToCloseTimeout?: string; - childPolicy?: string; - } - - export interface WorkflowType { - name?: string; - version?: string; - } - - export interface RespondDecisionTaskCompletedRequest { - taskToken?: string; - decisions?: Decision[]; - executionContext?: string; - } - - export interface Decision { - decisionType?: string; - scheduleActivityTaskDecisionAttributes?: ScheduleActivityTaskDecisionAttributes; - requestCancelActivityTaskDecisionAttributes?: RequestCancelActivityTaskDecisionAttributes; - completeWorkflowExecutionDecisionAttributes?: CompleteWorkflowExecutionDecisionAttributes; - failWorkflowExecutionDecisionAttributes?: FailWorkflowExecutionDecisionAttributes; - cancelWorkflowExecutionDecisionAttributes?: CancelWorkflowExecutionDecisionAttributes; - continueAsNewWorkflowExecutionDecisionAttributes?: ContinueAsNewWorkflowExecutionDecisionAttributes; - recordMarkerDecisionAttributes?: RecordMarkerDecisionAttributes; - startTimerDecisionAttributes?: StartTimerDecisionAttributes; - cancelTimerDecisionAttributes?: CancelTimerDecisionAttributes; - signalExternalWorkflowExecutionDecisionAttributes?: SignalExternalWorkflowExecutionDecisionAttributes; - requestCancelExternalWorkflowExecutionDecisionAttributes?: RequestCancelExternalWorkflowExecutionDecisionAttributes; - startChildWorkflowExecutionDecisionAttributes?: StartChildWorkflowExecutionDecisionAttributes; - } - - export interface ScheduleActivityTaskDecisionAttributes { - activityType?: ActivityType; - activityId?: string; - control?: string; - input?: string; - scheduleToCloseTimeout?: string; - taskList?: TaskList; - scheduleToStartTimeout?: string; - startToCloseTimeout?: string; - heartbeatTimeout?: string; - } - - export interface ActivityType { - name?: string; - version?: string; - } - - export interface RequestCancelActivityTaskDecisionAttributes { - activityId?: string; - } - - export interface CompleteWorkflowExecutionDecisionAttributes { - result?: string; - } - - export interface FailWorkflowExecutionDecisionAttributes { - reason?: string; - details?: string; - } - - export interface CancelWorkflowExecutionDecisionAttributes { - details?: string; - } - - export interface ContinueAsNewWorkflowExecutionDecisionAttributes { - input?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - taskStartToCloseTimeout?: string; - childPolicy?: string; - tagList?: string[]; - workflowTypeVersion?: string; - } - - export interface RecordMarkerDecisionAttributes { - markerName?: string; - details?: string; - } - - export interface StartTimerDecisionAttributes { - timerId?: string; - control?: string; - startToFireTimeout?: string; - } - - export interface CancelTimerDecisionAttributes { - timerId?: string; - } - - export interface SignalExternalWorkflowExecutionDecisionAttributes { - workflowId?: string; - runId?: string; - signalName?: string; - input?: string; - control?: string; - } - - export interface RequestCancelExternalWorkflowExecutionDecisionAttributes { - workflowId?: string; - runId?: string; - control?: string; - } - - export interface StartChildWorkflowExecutionDecisionAttributes { - workflowType?: WorkflowType; - workflowId?: string; - control?: string; - input?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - taskStartToCloseTimeout?: string; - childPolicy?: string; - tagList?: string[]; - } - - export interface RespondActivityTaskCompletedRequest { - taskToken?: string; - result?: string; - } - - export interface RespondActivityTaskFailedRequest { - taskToken?: string; - reason?: string; - details?: string; - } - - export interface RespondActivityTaskCanceledRequest { - taskToken?: string; - details?: string; - } - - export interface DecisionTask { - taskToken?: string; - startedEventId?: number; - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - events?: HistoryEvent[]; - nextPageToken?: string; - previousStartedEventId?: number; - } - - export interface WorkflowExecution { - workflowId?: string; - runId?: string; - } - - export interface HistoryEvent { - eventTimestamp?: any; - eventType?: string; - eventId?: number; - workflowExecutionStartedEventAttributes?: WorkflowExecutionStartedEventAttributes; - workflowExecutionCompletedEventAttributes?: WorkflowExecutionCompletedEventAttributes; - completeWorkflowExecutionFailedEventAttributes?: CompleteWorkflowExecutionFailedEventAttributes; - workflowExecutionFailedEventAttributes?: WorkflowExecutionFailedEventAttributes; - failWorkflowExecutionFailedEventAttributes?: FailWorkflowExecutionFailedEventAttributes; - workflowExecutionTimedOutEventAttributes?: WorkflowExecutionTimedOutEventAttributes; - workflowExecutionCanceledEventAttributes?: WorkflowExecutionCanceledEventAttributes; - cancelWorkflowExecutionFailedEventAttributes?: CancelWorkflowExecutionFailedEventAttributes; - workflowExecutionContinuedAsNewEventAttributes?: WorkflowExecutionContinuedAsNewEventAttributes; - continueAsNewWorkflowExecutionFailedEventAttributes?: ContinueAsNewWorkflowExecutionFailedEventAttributes; - workflowExecutionTerminatedEventAttributes?: WorkflowExecutionTerminatedEventAttributes; - workflowExecutionCancelRequestedEventAttributes?: WorkflowExecutionCancelRequestedEventAttributes; - decisionTaskScheduledEventAttributes?: DecisionTaskScheduledEventAttributes; - decisionTaskStartedEventAttributes?: DecisionTaskStartedEventAttributes; - decisionTaskCompletedEventAttributes?: DecisionTaskCompletedEventAttributes; - decisionTaskTimedOutEventAttributes?: DecisionTaskTimedOutEventAttributes; - activityTaskScheduledEventAttributes?: ActivityTaskScheduledEventAttributes; - activityTaskStartedEventAttributes?: ActivityTaskStartedEventAttributes; - activityTaskCompletedEventAttributes?: ActivityTaskCompletedEventAttributes; - activityTaskFailedEventAttributes?: ActivityTaskFailedEventAttributes; - activityTaskTimedOutEventAttributes?: ActivityTaskTimedOutEventAttributes; - activityTaskCanceledEventAttributes?: ActivityTaskCanceledEventAttributes; - activityTaskCancelRequestedEventAttributes?: ActivityTaskCancelRequestedEventAttributes; - workflowExecutionSignaledEventAttributes?: WorkflowExecutionSignaledEventAttributes; - markerRecordedEventAttributes?: MarkerRecordedEventAttributes; - timerStartedEventAttributes?: TimerStartedEventAttributes; - timerFiredEventAttributes?: TimerFiredEventAttributes; - timerCanceledEventAttributes?: TimerCanceledEventAttributes; - startChildWorkflowExecutionInitiatedEventAttributes?: StartChildWorkflowExecutionInitiatedEventAttributes; - childWorkflowExecutionStartedEventAttributes?: ChildWorkflowExecutionStartedEventAttributes; - childWorkflowExecutionCompletedEventAttributes?: ChildWorkflowExecutionCompletedEventAttributes; - childWorkflowExecutionFailedEventAttributes?: ChildWorkflowExecutionFailedEventAttributes; - childWorkflowExecutionTimedOutEventAttributes?: ChildWorkflowExecutionTimedOutEventAttributes; - childWorkflowExecutionCanceledEventAttributes?: ChildWorkflowExecutionCanceledEventAttributes; - childWorkflowExecutionTerminatedEventAttributes?: ChildWorkflowExecutionTerminatedEventAttributes; - signalExternalWorkflowExecutionInitiatedEventAttributes?: SignalExternalWorkflowExecutionInitiatedEventAttributes; - externalWorkflowExecutionSignaledEventAttributes?: ExternalWorkflowExecutionSignaledEventAttributes; - signalExternalWorkflowExecutionFailedEventAttributes?: SignalExternalWorkflowExecutionFailedEventAttributes; - externalWorkflowExecutionCancelRequestedEventAttributes?: ExternalWorkflowExecutionCancelRequestedEventAttributes; - requestCancelExternalWorkflowExecutionInitiatedEventAttributes?: RequestCancelExternalWorkflowExecutionInitiatedEventAttributes; - requestCancelExternalWorkflowExecutionFailedEventAttributes?: RequestCancelExternalWorkflowExecutionFailedEventAttributes; - scheduleActivityTaskFailedEventAttributes?: ScheduleActivityTaskFailedEventAttributes; - requestCancelActivityTaskFailedEventAttributes?: RequestCancelActivityTaskFailedEventAttributes; - startTimerFailedEventAttributes?: StartTimerFailedEventAttributes; - cancelTimerFailedEventAttributes?: CancelTimerFailedEventAttributes; - startChildWorkflowExecutionFailedEventAttributes?: StartChildWorkflowExecutionFailedEventAttributes; - } - - export interface WorkflowExecutionStartedEventAttributes { - input?: string; - executionStartToCloseTimeout?: string; - taskStartToCloseTimeout?: string; - childPolicy?: string; - taskList?: TaskList; - workflowType?: WorkflowType; - tagList?: string[]; - continuedExecutionRunId?: string; - parentWorkflowExecution?: WorkflowExecution; - parentInitiatedEventId?: number; - } - - export interface WorkflowExecutionCompletedEventAttributes { - result?: string; - decisionTaskCompletedEventId?: number; - } - - export interface CompleteWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionFailedEventAttributes { - reason?: string; - details?: string; - decisionTaskCompletedEventId?: number; - } - - export interface FailWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionTimedOutEventAttributes { - timeoutType?: string; - childPolicy?: string; - } - - export interface WorkflowExecutionCanceledEventAttributes { - details?: string; - decisionTaskCompletedEventId?: number; - } - - export interface CancelWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionContinuedAsNewEventAttributes { - input?: string; - decisionTaskCompletedEventId?: number; - newExecutionRunId?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - taskStartToCloseTimeout?: string; - childPolicy?: string; - tagList?: string[]; - workflowType?: WorkflowType; - } - - export interface ContinueAsNewWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionTerminatedEventAttributes { - reason?: string; - details?: string; - childPolicy?: string; - cause?: string; - } - - export interface WorkflowExecutionCancelRequestedEventAttributes { - externalWorkflowExecution?: WorkflowExecution; - externalInitiatedEventId?: number; - cause?: string; - } - - export interface DecisionTaskScheduledEventAttributes { - taskList?: TaskList; - startToCloseTimeout?: string; - } - - export interface DecisionTaskStartedEventAttributes { - identity?: string; - scheduledEventId?: number; - } - - export interface DecisionTaskCompletedEventAttributes { - executionContext?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface DecisionTaskTimedOutEventAttributes { - timeoutType?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface ActivityTaskScheduledEventAttributes { - activityType?: ActivityType; - activityId?: string; - input?: string; - control?: string; - scheduleToStartTimeout?: string; - scheduleToCloseTimeout?: string; - startToCloseTimeout?: string; - taskList?: TaskList; - decisionTaskCompletedEventId?: number; - heartbeatTimeout?: string; - } - - export interface ActivityTaskStartedEventAttributes { - identity?: string; - scheduledEventId?: number; - } - - export interface ActivityTaskCompletedEventAttributes { - result?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface ActivityTaskFailedEventAttributes { - reason?: string; - details?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface ActivityTaskTimedOutEventAttributes { - timeoutType?: string; - scheduledEventId?: number; - startedEventId?: number; - details?: string; - } - - export interface ActivityTaskCanceledEventAttributes { - details?: string; - scheduledEventId?: number; - startedEventId?: number; - latestCancelRequestedEventId?: number; - } - - export interface ActivityTaskCancelRequestedEventAttributes { - decisionTaskCompletedEventId?: number; - activityId?: string; - } - - export interface WorkflowExecutionSignaledEventAttributes { - signalName?: string; - input?: string; - externalWorkflowExecution?: WorkflowExecution; - externalInitiatedEventId?: number; - } - - export interface MarkerRecordedEventAttributes { - markerName?: string; - details?: string; - decisionTaskCompletedEventId?: number; - } - - export interface TimerStartedEventAttributes { - timerId?: string; - control?: string; - startToFireTimeout?: string; - decisionTaskCompletedEventId?: number; - } - - export interface TimerFiredEventAttributes { - timerId?: string; - startedEventId?: number; - } - - export interface TimerCanceledEventAttributes { - timerId?: string; - startedEventId?: number; - decisionTaskCompletedEventId?: number; - } - - export interface StartChildWorkflowExecutionInitiatedEventAttributes { - workflowId?: string; - workflowType?: WorkflowType; - control?: string; - input?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - decisionTaskCompletedEventId?: number; - childPolicy?: string; - taskStartToCloseTimeout?: string; - tagList?: string[]; - } - - export interface ChildWorkflowExecutionStartedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - initiatedEventId?: number; - } - - export interface ChildWorkflowExecutionCompletedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - result?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionFailedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - reason?: string; - details?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionTimedOutEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - timeoutType?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionCanceledEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - details?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionTerminatedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface SignalExternalWorkflowExecutionInitiatedEventAttributes { - workflowId?: string; - runId?: string; - signalName?: string; - input?: string; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ExternalWorkflowExecutionSignaledEventAttributes { - workflowExecution?: WorkflowExecution; - initiatedEventId?: number; - } - - export interface SignalExternalWorkflowExecutionFailedEventAttributes { - workflowId?: string; - runId?: string; - cause?: string; - initiatedEventId?: number; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ExternalWorkflowExecutionCancelRequestedEventAttributes { - workflowExecution?: WorkflowExecution; - initiatedEventId?: number; - } - - export interface RequestCancelExternalWorkflowExecutionInitiatedEventAttributes { - workflowId?: string; - runId?: string; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface RequestCancelExternalWorkflowExecutionFailedEventAttributes { - workflowId?: string; - runId?: string; - cause?: string; - initiatedEventId?: number; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ScheduleActivityTaskFailedEventAttributes { - activityType?: ActivityType; - activityId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface RequestCancelActivityTaskFailedEventAttributes { - activityId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface StartTimerFailedEventAttributes { - timerId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface CancelTimerFailedEventAttributes { - timerId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface StartChildWorkflowExecutionFailedEventAttributes { - workflowType?: WorkflowType; - cause?: string; - workflowId?: string; - initiatedEventId?: number; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ActivityTask { - taskToken?: string; - activityId?: string; - startedEventId?: number; - workflowExecution?: WorkflowExecution; - activityType?: ActivityType; - input?: string; - } - - export interface PollForActivityTaskResult { - activityTask?: ActivityTask; - } - - export interface PollForDecisionTaskResult { - decisionTask?: DecisionTask; - } - - export interface StartWorkflowExecutionResult { - run?: Run; - } - - export interface Run { - runId?: string; - } - - } - - export module Sns { - - export interface Client { - config: ClientConfig; - - publish(params: PublishRequest, callback: (err: any, data: PublishResult) => void): void; - createTopic(params: CreateTopicRequest, callback: (err: any, data: CreateTopicResult) => void): void; - deleteTopic(params: DeleteTopicRequest, callback: (err: any, data: any) => void): void; - } - - export interface PublishRequest { - TopicArn?: string; - TargetArn?: string; - MessageAttributes?: { [name: string]: MessageAttribute; }; - Message?: string; - MessageStructure?: string; - Subject?: string; - } - - export interface MessageAttribute { - DataType: string; - StringValue?: string; - BinaryValue: any; // (Buffer, Typed Array, Blob, String) - } - - export interface PublishResult { - MessageId?: string; - } - - export interface CreateTopicRequest { - Name?: string; - } - - export interface CreateTopicResult { - TopicArn?: string; - } - - export interface DeleteTopicRequest { - TopicArn?: string; - } - - } - - export module s3 { - export interface PutObjectRequest { - ACL?: string; - Body?: any; - Bucket: string; - CacheControl?: string; - ContentDisposition?: string; - ContentEncoding?: string; - ContentLanguage?: string; - ContentLength?: string; - ContentMD5?: string; - ContentType?: string; - Expires?: any; - GrantFullControl?: string; - GrantRead?: string; - GrantReadACP?: string; - GrantWriteACP?: string; - Key: string; - Metadata?: { [key: string]:string; }; - ServerSideEncryption?: string; - StorageClass?: string; - WebsiteRedirectLocation?: string; + updateService(params: ecs.UpdateServiceParams, callback: (err: any, data: any) => void): void; + } + + export class DynamoDB { + constructor(options?: any); + endpoint: Endpoint; + + } + + // ========================================================== + + export module DynamoDB { + + interface _DDBDC_Generic { + TableName: string; + ExpressionAttributeNames?: string[]; + ReturnConsumedCapacity?: "INDEXES" | "TOTAL" | "NONE"; + } + + type _DDBDC_ComparisonOperator = "EQ" | "NE" | "IN" | "LE" | "LT" | "GE" | "GT" | "BETWEEN" | "NOT_NULL" | "NULL" | "CONTAINS" | "NOT_CONTAINS" | "BEGINS_WITH" + type _DDBDC_Keys = { [someKey: string]: any }; + type _DDBDC_KeyComparison = { + [someKey: string]: { + AttributeValueList: any[]; + ComparisonOperator: _DDBDC_ComparisonOperator; + } + }; + + interface _DDBDC_Reader extends _DDBDC_Generic { + ConsistentRead?: boolean; + ProjectionExpression?: string; + AttributesToGet?: string[]; + } + + interface _DDBDC_Writer extends _DDBDC_Generic { + ExpressionAttributeValues?: _DDBDC_Keys; + ReturnItemCollectionMetrics?: "SIZE" | "NONE"; + ReturnValues?: "NONE" | "ALL_OLD" | "UPDATED_OLD" | "ALL_NEW" | "UPDATED_NEW"; + ConditionExpression?: string; + ConditionalOperator?: "AND" | "OR"; + Expected?: { + [someKey: string]: { + AttributeValueList: any[]; + ComparisonOperator: _DDBDC_ComparisonOperator; + Exists: boolean; + Value: any; } + } + } - export interface GetObjectRequest { - Bucket: string; - IfMatch?: string; - IfModifiedSince?: any; - IfNoneMatch?: string; - IfUnmodifiedSince?: any; - Key: string; - Range?: string; - ResponseCacheControl?: string; - ResponseContentDisposition?: string; - ResponseContentEncoding?: string; - ResponseContentLanguage?: string; - ResponseContentType?: string; - ResponseExpires?: any; - VersionId?: string; + interface UpdateParam extends _DDBDC_Writer { + Key: _DDBDC_Keys; + AttributeUpdates: { + [someKey: string]: { + Action: "PUT" | "ADD" | "DELETE"; + Value: any } + } + } - export interface DeleteObjectRequest { - Bucket: string; - Key: string; - MFA?: string; - RequestPayer?: string; - VersionId?: string; - } + interface QueryParam extends _DDBDC_Reader { + ConditionalOperator?: "AND" | "OR"; + ExclusiveStartKey?: _DDBDC_Keys; + ExpressionAttributeValues?: _DDBDC_Keys; + FilterExpression?: string; + IndexName?: string; + KeyConditionExpression?: string; + KeyConditions?: _DDBDC_KeyComparison; + Limit?: number; + QueryFilter?: _DDBDC_KeyComparison; + ScanIndexForward?: boolean; + Select?: "ALL_ATTRIBUTES" | "ALL_PROJECTED_ATTRIBUTES" | "SPECIFIC_ATTRIBUTES" | "COUNT"; + } - export interface HeadObjectRequest { - Bucket: string; - Key: string; - IfMatch?: string; - IfModifiedSince?: Date; - IfNoneMatch?: string; - IfUnmodifiedSince?: Date; - Range?: string; - RequestPayer?: string; - SSECustomerAlgorithm?: string; - SSECustomerKey?: Buffer | string; - SSECustomerKeyMD5?: string; - VersionId?: string; - } + interface ScanParam extends QueryParam { + Segment?: number; + ScanFilter?: _DDBDC_KeyComparison; + TotalSegments?: number; + } - export interface UploadOptions { - partSize?: number; - queueSize?: number; - } - } + interface GetParam extends _DDBDC_Reader { + Key: _DDBDC_Keys; + } - export module ecs { - export interface CreateServicesParams { - desiredCount: number; - serviceName: string; - taskDefinition: string; - clientToken?: string; - cluster?: string; - deploymentConfiguration?: { - maximumPercent?: number; - minimumHealthyPercent?: number; - }; - loadBalancers?: { - containerName?: string; - containerPort?: number; - loadBalancerName?: string; - }[]; - role?: string; - } + interface PutParam extends _DDBDC_Writer { + Item: _DDBDC_Keys; + } - export interface DescribeServicesParams { + interface DeleteParam extends _DDBDC_Writer { + Key: _DDBDC_Keys; + } + + export class DocumentClient { + constructor(options?: any); + get(params: GetParam, next: (err: any, data: any) => void): void; + put(params: PutParam, next: (err: any, data: any) => void): void; + delete(params: DeleteParam, next: (err: any, data: any) => void): void; + query(params: QueryParam, next: (err: any, data: any) => void): void; + scan(params: ScanParam, next: (err: any, data: any) => void): void; + update(params: UpdateParam, next: (err: any, data: any) => void): void; + createSet(list: any[], options?: { validate?: boolean }): { values: any[], type: string }; + batchGet(params: any, next: (err: any, data: any) => void): void; + batchWrite(params: any, next: (err: any, data: any) => void): void; + } + + } + + // =========================================================== + + export module Lambda { + + export interface AddPermissionParams { + Action: string; + FunctionName: string; + Principal: string; + StatementId: string; + Qualifier?: string; + SourceAccount?: string; + SourceArn?: string; + } + + export interface CreateAliasParams { + FunctionName: string; + FunctionVersion: string; + Name: string; + Description?: string; + } + + export interface CreateEventSourceMappingParams { + EventSourceArn: string; + FunctionName: string; + StartingPosition: string; /* TRIM_HORIZON | LATEST */ + BatchSize?: number; + Enabled?: boolean + } + + export interface CreateFunctionParams { + Code: { + S3Bucket?: string; + S3Key?: string; + S3ObjectVersion?: string; + ZipFile?: any; // new Buffer('...') || string; + }, + FunctionName: string; + Handler: string; + Role: string; + Runtime: string; /* 'nodejs | java8 | python2.7', */ + Description?: string; + MemorySize?: number; + Publish?: boolean; + Timeout?: number; + VpcConfig?: { + SecurityGroupIds?: string[]; + SubnetIds?: string[]; + } + } + + export interface DeleteAliasParams { + FunctionName: string; + Name: string; + } + + export interface DeleteEventSourceMappingParams { + UUID: string; + } + + export interface DeleteFunctionParams { + FunctionName: string; + Qualifier?: string; + } + export interface GetAliasParams { + FunctionName: string; + Name: string; + } + + export interface GetEventSourceMappingParams { + UUID: string; + } + + export interface GetFunctionParams { + FunctionName: string; + Qualifier?: string; + } + + export interface GetFunctionConfigurationParams { + FunctionName: string; + Qualifier?: string; + } + + export interface GetPolicyParams { + FunctionName: string; + Qualifier?: string; + } + + export interface InvokeParams { + FunctionName: string; + ClientContext?: string; + InvocationType?: string;/* 'Event | RequestResponse | DryRun' */ + LogType?: string; /* 'None | Tail' */ + Payload?: any; /* new Buffer('...') || string */ + Qualifier?: string; + } + + export interface ListAliasesParams { + FunctionName: string; + FunctionVersion?: string; + Marker?: string; + MaxItems?: number + } + + export interface ListEventSourceMappingsParams { + EventSourceArn?: string; + FunctionName?: string; + Marker?: string; + MaxItems?: number + } + + export interface ListFunctionsParams { + Marker?: string; + MaxItems?: number + } + + export interface ListVersionsByFunctionParams { + FunctionName: string; + Marker?: string; + MaxItems?: number + } + + export interface PublishVersionParams { + FunctionName: string; + CodeSha256?: string; + Description?: string; + } + + export interface RemovePermissionParams { + FunctionName: string; + StatementId: string; + Qualifier?: string; + } + + export interface UpdateAliasParams { + FunctionName: string; + Name: string; + Description?: string; + FunctionVersion?: string; + } + + export interface UpdateEventSourceMappingParams { + UUID: string; + BatchSize?: number; + Enabled?: boolean; + FunctionName?: string; + } + + export interface UpdateFunctionCodeParams { + FunctionName: string; + Publish?: boolean; + S3Bucket?: string; + S3Key?: string; + S3ObjectVersion?: string; + ZipFile?: any; /* new Buffer('...') || string; */ + + } + + export interface UpdateFunctionConfigurationParams { + FunctionName: string; + Description?: string; + Handler?: string; + MemorySize?: number; + Role?: string; + Timeout?: number; + VpcConfig?: { + SecurityGroupIds?: string[]; + SubnetIds?: string[]; + } + } + } + + 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 SendMessageParams { + QueueUrl?: string; + MessageBody: string; + DelaySeconds?: number; + MessageAttributes?: { [name: string]: MessageAttribute; } + } + + export interface ReceiveMessageParams { + QueueUrl: string; + MaxNumberOfMessages?: number; + VisibilityTimeout?: number; + AttributeNames?: string[]; + MessageAttributeNames?: string[]; + WaitTimeSeconds?: number; + } + + export interface DeleteMessageBatchParams { + QueueUrl: string; + Entries: DeleteMessageBatchRequestEntry[]; + } + + export interface DeleteMessageBatchRequestEntry { + Id: string; + ReceiptHandle: string; + } + + export interface DeleteMessageParams { + QueueUrl: string; + ReceiptHandle: string; + } + + export interface SendMessageBatchParams { + QueueUrl: string; + Entries: SendMessageBatchRequestEntry[]; + } + + export interface SendMessageBatchRequestEntry { + Id: string; + MessageBody: string; + DelaySeconds?: number; + MessageAttributes?: { [name: string]: MessageAttribute; } + } + + export interface CreateQueueParams { + QueueName: string; + Attributes: QueueAttributes; + } + + 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 interface ReceiveMessageResult { + Messages: Message[]; + } + + export interface Message { + MessageId: string; + ReceiptHandle: string; + MD5OfBody: string; + Body: string; + Attributes: { [name: string]: any }; + MD5OfMessageAttributes: string; + MessageAttributes: { [name: string]: MessageAttribute; } + } + + 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 interface DeleteMessageBatchResultEntry { + Id: string; + } + + export interface BatchResultErrorEntry { + Id: string; + Code: string; + Message?: string; + SenderFault: boolean; + } + + export interface SendMessageBatchResult { + Successful: SendMessageBatchResultEntry[]; + Failed: BatchResultErrorEntry[]; + } + + export interface SendMessageBatchResultEntry { + Id: string; + MessageId: string; + MD5OfMessageBody: string; + MD5OfMessageAttributes: string; + } + + export interface CreateQueueResult { + QueueUrl: string; + } + + export interface SetQueueAttributesParams { + QueueUrl: string; + Attributes: QueueAttributes; + } + + } + + export module SES { + + export interface Client { + config: ClientConfig; + + sendEmail(params: any, callback: (err: any, data: SendEmailResult) => void): void; + } + + export interface SendEmailRequest { + Source: string; + Destination: Destination; + Message: Message; + ReplyToAddresses: string[]; + ReturnPath: string; + } + + export class Destination { + ToAddresses: string[]; + CcAddresses: string[]; + BccAddresses: string[]; + } + + export class Message { + Subject: Content; + Body: Body; + } + + export class Content { + Data: string; + Charset: string; + } + + export class Body { + Text: Content; + Html: Content; + } + + export class SendEmailResult { + MessageId: string; + } + + } + + export module Swf { + + export interface Client { + //constructor(options?: any); + config: ClientConfig; + + countClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countPendingActivityTasks(params: any, callback: (err: any, data: any) => void): void; + countPendingDecisionTasks(params: any, callback: (err: any, data: any) => void): void; + deprecateActivityType(params: any, callback: (err: any, data: any) => void): void; + deprecateDomain(params: any, callback: (err: any, data: any) => void): void; + deprecateWorkflowType(params: any, callback: (err: any, data: any) => void): void; + describeActivityType(params: any, callback: (err: any, data: any) => void): void; + describeDomain(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowType(params: any, callback: (err: any, data: any) => void): void; + getWorkflowExecutionHistory(params: any, callback: (err: any, data: any) => void): void; + listActivityTypes(params: any, callback: (err: any, data: any) => void): void; + listClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listDomains(params: any, callback: (err: any, data: any) => void): void; + listOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listWorkflowTypes(params: any, callback: (err: any, data: any) => void): void; + pollForActivityTask(params: any, callback: (err: any, data: ActivityTask) => void): void; + pollForDecisionTask(params: any, callback: (err: any, data: DecisionTask) => void): void; + recordActivityTaskHeartbeat(params: any, callback: (err: any, data: any) => void): void; + registerActivityType(params: any, callback: (err: any, data: any) => void): void; + registerDomain(params: any, callback: (err: any, data: any) => void): void; + registerWorkflowType(params: any, callback: (err: any, data: any) => void): void; + requestCancelWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + respondActivityTaskCanceled(params: RespondActivityTaskCanceledRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskCompleted(params: RespondActivityTaskCompletedRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskFailed(params: RespondActivityTaskFailedRequest, callback: (err: any, data: any) => void): void; + respondDecisionTaskCompleted(params: RespondDecisionTaskCompletedRequest, callback: (err: any, data: any) => void): void; + signalWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + startWorkflowExecution(params: any, callback: (err: any, data: StartWorkflowExecutionResult) => void): void; + terminateWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + } + + export interface PollForActivityTaskRequest { + domain?: string; + taskList?: TaskList; + identity?: string; + } + + export interface TaskList { + name?: string; + } + + export interface PollForDecisionTaskRequest { + domain?: string; + taskList?: TaskList; + identity?: string; + nextPageToken?: string; + maximumPageSize?: number; + reverseOrder?: Boolean; + } + + export interface StartWorkflowExecutionRequest { + domain?: string; + workflowId?: string; + workflowType?: WorkflowType; + taskList?: TaskList; + input?: string; + executionStartToCloseTimeout?: string; + tagList?: string[]; + taskStartToCloseTimeout?: string; + childPolicy?: string; + } + + export interface WorkflowType { + name?: string; + version?: string; + } + + export interface RespondDecisionTaskCompletedRequest { + taskToken?: string; + decisions?: Decision[]; + executionContext?: string; + } + + export interface Decision { + decisionType?: string; + scheduleActivityTaskDecisionAttributes?: ScheduleActivityTaskDecisionAttributes; + requestCancelActivityTaskDecisionAttributes?: RequestCancelActivityTaskDecisionAttributes; + completeWorkflowExecutionDecisionAttributes?: CompleteWorkflowExecutionDecisionAttributes; + failWorkflowExecutionDecisionAttributes?: FailWorkflowExecutionDecisionAttributes; + cancelWorkflowExecutionDecisionAttributes?: CancelWorkflowExecutionDecisionAttributes; + continueAsNewWorkflowExecutionDecisionAttributes?: ContinueAsNewWorkflowExecutionDecisionAttributes; + recordMarkerDecisionAttributes?: RecordMarkerDecisionAttributes; + startTimerDecisionAttributes?: StartTimerDecisionAttributes; + cancelTimerDecisionAttributes?: CancelTimerDecisionAttributes; + signalExternalWorkflowExecutionDecisionAttributes?: SignalExternalWorkflowExecutionDecisionAttributes; + requestCancelExternalWorkflowExecutionDecisionAttributes?: RequestCancelExternalWorkflowExecutionDecisionAttributes; + startChildWorkflowExecutionDecisionAttributes?: StartChildWorkflowExecutionDecisionAttributes; + } + + export interface ScheduleActivityTaskDecisionAttributes { + activityType?: ActivityType; + activityId?: string; + control?: string; + input?: string; + scheduleToCloseTimeout?: string; + taskList?: TaskList; + scheduleToStartTimeout?: string; + startToCloseTimeout?: string; + heartbeatTimeout?: string; + } + + export interface ActivityType { + name?: string; + version?: string; + } + + export interface RequestCancelActivityTaskDecisionAttributes { + activityId?: string; + } + + export interface CompleteWorkflowExecutionDecisionAttributes { + result?: string; + } + + export interface FailWorkflowExecutionDecisionAttributes { + reason?: string; + details?: string; + } + + export interface CancelWorkflowExecutionDecisionAttributes { + details?: string; + } + + export interface ContinueAsNewWorkflowExecutionDecisionAttributes { + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + workflowTypeVersion?: string; + } + + export interface RecordMarkerDecisionAttributes { + markerName?: string; + details?: string; + } + + export interface StartTimerDecisionAttributes { + timerId?: string; + control?: string; + startToFireTimeout?: string; + } + + export interface CancelTimerDecisionAttributes { + timerId?: string; + } + + export interface SignalExternalWorkflowExecutionDecisionAttributes { + workflowId?: string; + runId?: string; + signalName?: string; + input?: string; + control?: string; + } + + export interface RequestCancelExternalWorkflowExecutionDecisionAttributes { + workflowId?: string; + runId?: string; + control?: string; + } + + export interface StartChildWorkflowExecutionDecisionAttributes { + workflowType?: WorkflowType; + workflowId?: string; + control?: string; + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + } + + export interface RespondActivityTaskCompletedRequest { + taskToken?: string; + result?: string; + } + + export interface RespondActivityTaskFailedRequest { + taskToken?: string; + reason?: string; + details?: string; + } + + export interface RespondActivityTaskCanceledRequest { + taskToken?: string; + details?: string; + } + + export interface DecisionTask { + taskToken?: string; + startedEventId?: number; + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + events?: HistoryEvent[]; + nextPageToken?: string; + previousStartedEventId?: number; + } + + export interface WorkflowExecution { + workflowId?: string; + runId?: string; + } + + export interface HistoryEvent { + eventTimestamp?: any; + eventType?: string; + eventId?: number; + workflowExecutionStartedEventAttributes?: WorkflowExecutionStartedEventAttributes; + workflowExecutionCompletedEventAttributes?: WorkflowExecutionCompletedEventAttributes; + completeWorkflowExecutionFailedEventAttributes?: CompleteWorkflowExecutionFailedEventAttributes; + workflowExecutionFailedEventAttributes?: WorkflowExecutionFailedEventAttributes; + failWorkflowExecutionFailedEventAttributes?: FailWorkflowExecutionFailedEventAttributes; + workflowExecutionTimedOutEventAttributes?: WorkflowExecutionTimedOutEventAttributes; + workflowExecutionCanceledEventAttributes?: WorkflowExecutionCanceledEventAttributes; + cancelWorkflowExecutionFailedEventAttributes?: CancelWorkflowExecutionFailedEventAttributes; + workflowExecutionContinuedAsNewEventAttributes?: WorkflowExecutionContinuedAsNewEventAttributes; + continueAsNewWorkflowExecutionFailedEventAttributes?: ContinueAsNewWorkflowExecutionFailedEventAttributes; + workflowExecutionTerminatedEventAttributes?: WorkflowExecutionTerminatedEventAttributes; + workflowExecutionCancelRequestedEventAttributes?: WorkflowExecutionCancelRequestedEventAttributes; + decisionTaskScheduledEventAttributes?: DecisionTaskScheduledEventAttributes; + decisionTaskStartedEventAttributes?: DecisionTaskStartedEventAttributes; + decisionTaskCompletedEventAttributes?: DecisionTaskCompletedEventAttributes; + decisionTaskTimedOutEventAttributes?: DecisionTaskTimedOutEventAttributes; + activityTaskScheduledEventAttributes?: ActivityTaskScheduledEventAttributes; + activityTaskStartedEventAttributes?: ActivityTaskStartedEventAttributes; + activityTaskCompletedEventAttributes?: ActivityTaskCompletedEventAttributes; + activityTaskFailedEventAttributes?: ActivityTaskFailedEventAttributes; + activityTaskTimedOutEventAttributes?: ActivityTaskTimedOutEventAttributes; + activityTaskCanceledEventAttributes?: ActivityTaskCanceledEventAttributes; + activityTaskCancelRequestedEventAttributes?: ActivityTaskCancelRequestedEventAttributes; + workflowExecutionSignaledEventAttributes?: WorkflowExecutionSignaledEventAttributes; + markerRecordedEventAttributes?: MarkerRecordedEventAttributes; + timerStartedEventAttributes?: TimerStartedEventAttributes; + timerFiredEventAttributes?: TimerFiredEventAttributes; + timerCanceledEventAttributes?: TimerCanceledEventAttributes; + startChildWorkflowExecutionInitiatedEventAttributes?: StartChildWorkflowExecutionInitiatedEventAttributes; + childWorkflowExecutionStartedEventAttributes?: ChildWorkflowExecutionStartedEventAttributes; + childWorkflowExecutionCompletedEventAttributes?: ChildWorkflowExecutionCompletedEventAttributes; + childWorkflowExecutionFailedEventAttributes?: ChildWorkflowExecutionFailedEventAttributes; + childWorkflowExecutionTimedOutEventAttributes?: ChildWorkflowExecutionTimedOutEventAttributes; + childWorkflowExecutionCanceledEventAttributes?: ChildWorkflowExecutionCanceledEventAttributes; + childWorkflowExecutionTerminatedEventAttributes?: ChildWorkflowExecutionTerminatedEventAttributes; + signalExternalWorkflowExecutionInitiatedEventAttributes?: SignalExternalWorkflowExecutionInitiatedEventAttributes; + externalWorkflowExecutionSignaledEventAttributes?: ExternalWorkflowExecutionSignaledEventAttributes; + signalExternalWorkflowExecutionFailedEventAttributes?: SignalExternalWorkflowExecutionFailedEventAttributes; + externalWorkflowExecutionCancelRequestedEventAttributes?: ExternalWorkflowExecutionCancelRequestedEventAttributes; + requestCancelExternalWorkflowExecutionInitiatedEventAttributes?: RequestCancelExternalWorkflowExecutionInitiatedEventAttributes; + requestCancelExternalWorkflowExecutionFailedEventAttributes?: RequestCancelExternalWorkflowExecutionFailedEventAttributes; + scheduleActivityTaskFailedEventAttributes?: ScheduleActivityTaskFailedEventAttributes; + requestCancelActivityTaskFailedEventAttributes?: RequestCancelActivityTaskFailedEventAttributes; + startTimerFailedEventAttributes?: StartTimerFailedEventAttributes; + cancelTimerFailedEventAttributes?: CancelTimerFailedEventAttributes; + startChildWorkflowExecutionFailedEventAttributes?: StartChildWorkflowExecutionFailedEventAttributes; + } + + export interface WorkflowExecutionStartedEventAttributes { + input?: string; + executionStartToCloseTimeout?: string; + taskStartToCloseTimeout?: string; + childPolicy?: string; + taskList?: TaskList; + workflowType?: WorkflowType; + tagList?: string[]; + continuedExecutionRunId?: string; + parentWorkflowExecution?: WorkflowExecution; + parentInitiatedEventId?: number; + } + + export interface WorkflowExecutionCompletedEventAttributes { + result?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CompleteWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionFailedEventAttributes { + reason?: string; + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface FailWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionTimedOutEventAttributes { + timeoutType?: string; + childPolicy?: string; + } + + export interface WorkflowExecutionCanceledEventAttributes { + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CancelWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionContinuedAsNewEventAttributes { + input?: string; + decisionTaskCompletedEventId?: number; + newExecutionRunId?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + workflowType?: WorkflowType; + } + + export interface ContinueAsNewWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionTerminatedEventAttributes { + reason?: string; + details?: string; + childPolicy?: string; + cause?: string; + } + + export interface WorkflowExecutionCancelRequestedEventAttributes { + externalWorkflowExecution?: WorkflowExecution; + externalInitiatedEventId?: number; + cause?: string; + } + + export interface DecisionTaskScheduledEventAttributes { + taskList?: TaskList; + startToCloseTimeout?: string; + } + + export interface DecisionTaskStartedEventAttributes { + identity?: string; + scheduledEventId?: number; + } + + export interface DecisionTaskCompletedEventAttributes { + executionContext?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface DecisionTaskTimedOutEventAttributes { + timeoutType?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskScheduledEventAttributes { + activityType?: ActivityType; + activityId?: string; + input?: string; + control?: string; + scheduleToStartTimeout?: string; + scheduleToCloseTimeout?: string; + startToCloseTimeout?: string; + taskList?: TaskList; + decisionTaskCompletedEventId?: number; + heartbeatTimeout?: string; + } + + export interface ActivityTaskStartedEventAttributes { + identity?: string; + scheduledEventId?: number; + } + + export interface ActivityTaskCompletedEventAttributes { + result?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskFailedEventAttributes { + reason?: string; + details?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskTimedOutEventAttributes { + timeoutType?: string; + scheduledEventId?: number; + startedEventId?: number; + details?: string; + } + + export interface ActivityTaskCanceledEventAttributes { + details?: string; + scheduledEventId?: number; + startedEventId?: number; + latestCancelRequestedEventId?: number; + } + + export interface ActivityTaskCancelRequestedEventAttributes { + decisionTaskCompletedEventId?: number; + activityId?: string; + } + + export interface WorkflowExecutionSignaledEventAttributes { + signalName?: string; + input?: string; + externalWorkflowExecution?: WorkflowExecution; + externalInitiatedEventId?: number; + } + + export interface MarkerRecordedEventAttributes { + markerName?: string; + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface TimerStartedEventAttributes { + timerId?: string; + control?: string; + startToFireTimeout?: string; + decisionTaskCompletedEventId?: number; + } + + export interface TimerFiredEventAttributes { + timerId?: string; + startedEventId?: number; + } + + export interface TimerCanceledEventAttributes { + timerId?: string; + startedEventId?: number; + decisionTaskCompletedEventId?: number; + } + + export interface StartChildWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + workflowType?: WorkflowType; + control?: string; + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + decisionTaskCompletedEventId?: number; + childPolicy?: string; + taskStartToCloseTimeout?: string; + tagList?: string[]; + } + + export interface ChildWorkflowExecutionStartedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + initiatedEventId?: number; + } + + export interface ChildWorkflowExecutionCompletedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + result?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionFailedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + reason?: string; + details?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionTimedOutEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + timeoutType?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionCanceledEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + details?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionTerminatedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface SignalExternalWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + runId?: string; + signalName?: string; + input?: string; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ExternalWorkflowExecutionSignaledEventAttributes { + workflowExecution?: WorkflowExecution; + initiatedEventId?: number; + } + + export interface SignalExternalWorkflowExecutionFailedEventAttributes { + workflowId?: string; + runId?: string; + cause?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ExternalWorkflowExecutionCancelRequestedEventAttributes { + workflowExecution?: WorkflowExecution; + initiatedEventId?: number; + } + + export interface RequestCancelExternalWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + runId?: string; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface RequestCancelExternalWorkflowExecutionFailedEventAttributes { + workflowId?: string; + runId?: string; + cause?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ScheduleActivityTaskFailedEventAttributes { + activityType?: ActivityType; + activityId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface RequestCancelActivityTaskFailedEventAttributes { + activityId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface StartTimerFailedEventAttributes { + timerId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CancelTimerFailedEventAttributes { + timerId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface StartChildWorkflowExecutionFailedEventAttributes { + workflowType?: WorkflowType; + cause?: string; + workflowId?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ActivityTask { + taskToken?: string; + activityId?: string; + startedEventId?: number; + workflowExecution?: WorkflowExecution; + activityType?: ActivityType; + input?: string; + } + + export interface PollForActivityTaskResult { + activityTask?: ActivityTask; + } + + export interface PollForDecisionTaskResult { + decisionTask?: DecisionTask; + } + + export interface StartWorkflowExecutionResult { + run?: Run; + } + + export interface Run { + runId?: string; + } + + } + + export module Sns { + + export interface Client { + config: ClientConfig; + + publish(params: PublishRequest, callback: (err: any, data: PublishResult) => void): void; + createTopic(params: CreateTopicRequest, callback: (err: any, data: CreateTopicResult) => void): void; + deleteTopic(params: DeleteTopicRequest, callback: (err: any, data: any) => void): void; + } + + export interface PublishRequest { + TopicArn?: string; + TargetArn?: string; + MessageAttributes?: { [name: string]: MessageAttribute; }; + Message?: string; + MessageStructure?: string; + Subject?: string; + } + + export interface MessageAttribute { + DataType: string; + StringValue?: string; + BinaryValue: any; // (Buffer, Typed Array, Blob, String) + } + + export interface PublishResult { + MessageId?: string; + } + + export interface CreateTopicRequest { + Name?: string; + } + + export interface CreateTopicResult { + TopicArn?: string; + } + + export interface DeleteTopicRequest { + TopicArn?: string; + } + + } + + export module s3 { + interface Owner { + DisplayName: string; + ID: string; + } + + interface ObjectKeyPrefix { + Prefix: string; + } + + export interface ListObjectContent { + Key: string; + LastModified: Date; + ETag: string; + Size: number; + StorageClass: "STANDARD" | "REDUCED_REDUNDANCY" | "GLACIER"; + Owner?: Owner + } + + // This private interface contains the common parts between v1 and v2 of the API Request and is exposed via V1 and V2 subclasses + interface ListObjectRequestBase { + Bucket: string; + Delimiter?: string; + EncodingType?: 'url'; + MaxKeys?: number; + Prefix?: string; + } + + // This private interface contains the common parts between v1 and v2 of the API Response and is exposed via V1 and V2 subclasses + interface ListObjectResponseBase { + IsTruncated: boolean; + Contents: ListObjectContent[]; + Name: string; + Prefix?: string; + Delimiter?: string; + MaxKeys: number; + CommonPrefixes?: ObjectKeyPrefix[]; + EncodingType?: "url"; + } + + export interface PutObjectRequest { + ACL?: string; + Body?: any; + Bucket: string; + CacheControl?: string; + ContentDisposition?: string; + ContentEncoding?: string; + ContentLanguage?: string; + ContentLength?: string; + ContentMD5?: string; + ContentType?: string; + Expires?: any; + GrantFullControl?: string; + GrantRead?: string; + GrantReadACP?: string; + GrantWriteACP?: string; + Key: string; + Metadata?: { [key: string]: string; }; + ServerSideEncryption?: string; + StorageClass?: string; + WebsiteRedirectLocation?: string; + } + + export interface GetObjectRequest { + Bucket: string; + IfMatch?: string; + IfModifiedSince?: any; + IfNoneMatch?: string; + IfUnmodifiedSince?: any; + Key: string; + Range?: string; + ResponseCacheControl?: string; + ResponseContentDisposition?: string; + ResponseContentEncoding?: string; + ResponseContentLanguage?: string; + ResponseContentType?: string; + ResponseExpires?: any; + VersionId?: string; + } + + export interface DeleteObjectRequest { + Bucket: string; + Key: string; + MFA?: string; + RequestPayer?: string; + VersionId?: string; + } + + export interface HeadObjectRequest { + Bucket: string; + Key: string; + IfMatch?: string; + IfModifiedSince?: Date; + IfNoneMatch?: string; + IfUnmodifiedSince?: Date; + Range?: string; + RequestPayer?: string; + SSECustomerAlgorithm?: string; + SSECustomerKey?: Buffer | string; + SSECustomerKeyMD5?: string; + VersionId?: string; + } + + export interface UploadOptions { + partSize?: number; + queueSize?: number; + } + + export interface ListObjectRequest extends ListObjectRequestBase { + Marker?: string; + } + + export interface ListObjectV2Request extends ListObjectRequestBase { + ContinuationToken?: string; + FetchOwner?: boolean; + StartAfter?: string; + } + + export interface ListObjectResponse extends ListObjectResponseBase { + Marker?: string; + NextMarker?: string; + } + + export interface ListObjectV2Response extends ListObjectResponseBase { + KeyCount: number; + ContinuationToken?: string; + NextContinuationToken?: string; + StartAfter?: string; + } + } + + export module ecs { + export interface CreateServicesParams { + desiredCount: number; + serviceName: string; + taskDefinition: string; + clientToken?: string; + cluster?: string; + deploymentConfiguration?: { + maximumPercent?: number; + minimumHealthyPercent?: number; + }; + loadBalancers?: { + containerName?: string; + containerPort?: number; + loadBalancerName?: string; + }[]; + role?: string; + } + + export interface DescribeServicesParams { /** * A list of services to describe. */ - services: string[]; + services: string[]; /** * The name of the cluster that hosts the service to describe. If you do not specify a cluster, the default cluster is assumed. */ - cluster?: string; - } + cluster?: string; + } - export interface DescribeClustersParams { + export interface DescribeClustersParams { /** * A space-separated list of cluster names or full cluster Amazon Resource Name (ARN) entries. If you do not specify a cluster, the default cluster is assumed. */ - clusters?: string[]; - } + clusters?: string[]; + } - export interface DescribeTasksParams { + export interface DescribeTasksParams { /** * A space-separated list of task IDs or full Amazon Resource Name (ARN) entries. */ - tasks: string[]; + tasks: string[]; /** * The short name or full Amazon Resource Name (ARN) of the cluster that hosts the task to describe. If you do not specify a cluster, the default cluster is assumed. */ - cluster?: string; - } + cluster?: string; + } - export interface DescribeTaskDefinitionParams { + export interface DescribeTaskDefinitionParams { /** * The `family` for the latest `ACTIVE` revision, `family` and `revision` (`family:revision`) for a specific revision in the family, or full Amazon Resource Name (ARN) of the task definition to describe. */ - taskDefinition: string; - } + taskDefinition: string; + } - export interface RegisterTaskDefinitionParams { - containerDefinitions: { - command?: string[], - cpu?: number, - disableNetworking?: boolean, - dnsSearchDomains?: string[], - dnsServers?: string[], - dockerLabels?: any, - dockerSecurityOptions?: string[], - entryPoint?: string[], - environment?: any[], - essential?: boolean, - extraHosts?: { - hostName: string, - ipAddress: string - }[]; - hostname?: string, - image?: string, - links?: string[], - logConfiguration?: { - logDriver: string, - options: any - }[], - memory?: number, - mountPoints?: { - containerPath: string, - readOnly: boolean, - sourceVolume: string - }[]; - name?: string, - portMappings?: { - containerPort?: number, - hostPort?: number, - protocol: string - }[]; - privileged?: boolean, - readonlyRootFilesystem?: boolean, - ulimits?: { - hardLimit: number, - name: string, - softLimit: number - }[]; - user?: string, - volumesFrom?: { - readOnly?: boolean, - sourceContainer?: string - }[], - workingDirectory?: string - }[]; - family: string; - volumes?: { - host: { - sourcePath: string - }, - name: string - }[]; - } + export interface RegisterTaskDefinitionParams { + containerDefinitions: { + command?: string[], + cpu?: number, + disableNetworking?: boolean, + dnsSearchDomains?: string[], + dnsServers?: string[], + dockerLabels?: any, + dockerSecurityOptions?: string[], + entryPoint?: string[], + environment?: any[], + essential?: boolean, + extraHosts?: { + hostName: string, + ipAddress: string + }[]; + hostname?: string, + image?: string, + links?: string[], + logConfiguration?: { + logDriver: string, + options: any + }[], + memory?: number, + mountPoints?: { + containerPath: string, + readOnly: boolean, + sourceVolume: string + }[]; + name?: string, + portMappings?: { + containerPort?: number, + hostPort?: number, + protocol: string + }[]; + privileged?: boolean, + readonlyRootFilesystem?: boolean, + ulimits?: { + hardLimit: number, + name: string, + softLimit: number + }[]; + user?: string, + volumesFrom?: { + readOnly?: boolean, + sourceContainer?: string + }[], + workingDirectory?: string + }[]; + family: string; + volumes?: { + host: { + sourcePath: string + }, + name: string + }[]; + } - export interface UpdateServiceParams { - service: string; - cluster?: string; - deploymentConfiguration?: { - maximumPercent: number; - minimumHealthyPercent: number; - }; - desiredCount?: number; - taskDefinition: string; - } - } + export interface UpdateServiceParams { + service: string; + cluster?: string; + deploymentConfiguration?: { + maximumPercent: number; + minimumHealthyPercent: number; + }; + desiredCount?: number; + taskDefinition: string; + } + } - export module sts { - export interface AssumeRoleParams { - RoleArn: string; - RoleSessionName: string; - DurationSeconds?: number; - ExternalId?: string; - Policy?: string; - SerialNumber?: string; - TokenCode?: string; - } + export module sts { + export interface AssumeRoleParams { + RoleArn: string; + RoleSessionName: string; + DurationSeconds?: number; + ExternalId?: string; + Policy?: string; + SerialNumber?: string; + TokenCode?: string; + } - export interface AssumeRoleCallbackData{ - Credentials: TemporaryCredentials; - AssumedRoleUser: AssumedRoleUser; - PackedPolicySize: number; - } + export interface AssumeRoleCallbackData { + Credentials: TemporaryCredentials; + AssumedRoleUser: AssumedRoleUser; + PackedPolicySize: number; + } - export interface TemporaryCredentials{ - AccessKeyId: string; - SecretAccessKey: string; - SessionToken: string; - Expiration: Date; - } + export interface TemporaryCredentials { + AccessKeyId: string; + SecretAccessKey: string; + SessionToken: string; + Expiration: Date; + } - export interface AssumedRoleUser{ - AssumedRoleId: string; - Arn: string; - } + export interface AssumedRoleUser { + AssumedRoleId: string; + Arn: string; + } - export interface AssumeRoleWithSAMLParams { - PrincipalArn: string; - RoleArn: string; - SAMLAssertion: string; - DurationSeconds?: number; - Policy?: string; - } + export interface AssumeRoleWithSAMLParams { + PrincipalArn: string; + RoleArn: string; + SAMLAssertion: string; + DurationSeconds?: number; + Policy?: string; + } - export interface AssumeRoleWithWebIdentityParams { - RoleArn: string; - RoleSessionName: string; - WebIdentityToken: string; - DurationSeconds?: number; - Policy?: string; - ProviderId?: string; - } + export interface AssumeRoleWithWebIdentityParams { + RoleArn: string; + RoleSessionName: string; + WebIdentityToken: string; + DurationSeconds?: number; + Policy?: string; + ProviderId?: string; + } - export interface CredentialsFromParams { + export interface CredentialsFromParams { /** * Data retrieved from a call to AWS.STS.getFederatedToken, getSessionToken(), assumeRole(), or assumeRoleWithWebIdentity(). */ - Data: any; + Data: any; /** * An optional credentials object to fill instead of creating a new object. Useful when modifying an existing credentials object from a refresh call. */ - Credentials?: Credentials - } + Credentials?: Credentials + } - export interface DecodeAuthorizationMessageParams { - EncodedMessage: string; - } + export interface DecodeAuthorizationMessageParams { + EncodedMessage: string; + } - export interface GetFederationTokenParams { - Name: string; - DurationSeconds?: number, - Policy?: string - } + export interface GetFederationTokenParams { + Name: string; + DurationSeconds?: number, + Policy?: string + } - export interface GetSessionTokenParams { - DurationSeconds: number, - SerialNumber: string; - TokenCode: string; - } - } + export interface GetSessionTokenParams { + DurationSeconds: number, + SerialNumber: string; + TokenCode: string; + } + } } diff --git a/breeze/breeze.d.ts b/breeze/breeze.d.ts index 3fc54dc5d4..8cc109d746 100644 --- a/breeze/breeze.d.ts +++ b/breeze/breeze.d.ts @@ -12,6 +12,7 @@ // Updated Jan 20 2015 for Breeze 1.5.2 and merging changes from DefinitelyTyped // Updated Feb 28 2015 add any/all clause on Predicate // Updated Jun 27 2016 - Marcel Good (www.ideablade.com) +// Updated Jul 28 2016 - Serkan "coni2k" Holat declare namespace breeze.core { @@ -1043,6 +1044,10 @@ declare namespace breeze.config { @return {an instance of the specified adapter} **/ export function getAdapterInstance(interfaceName: string, adapterName?: string): Object; + + export interface Adapter { + getRoutePrefix: Function + } /** Initializes a single adapter implementation. Initialization means either newing a instance of the specified interface and then calling "initialize" on it or simply calling "initialize" on the instance @@ -1052,7 +1057,7 @@ declare namespace breeze.config { @param isDefault=true {Boolean} - Whether to make this the default "adapter" for this interface. @return {an instance of the specified adapter} **/ - export function initializeAdapterInstance(interfaceName: string, adapterName: string, isDefault?: boolean): void; + export function initializeAdapterInstance(interfaceName: string, adapterName: string, isDefault?: boolean): Adapter; export interface AdapterInstancesConfig { /** the name of a previously registered "ajax" adapter */ diff --git a/cassandra-driver/cassandra-driver.d.ts b/cassandra-driver/cassandra-driver.d.ts index 0da40f2081..ac68985c31 100644 --- a/cassandra-driver/cassandra-driver.d.ts +++ b/cassandra-driver/cassandra-driver.d.ts @@ -480,10 +480,10 @@ declare module "cassandra-driver" { interface QueryOptions { autoPage?: boolean; captureStackTrace?: boolean; - consistency: number; + consistency?: number; customPayload?: any; fetchSize?: number; - hints: Array | Array>; + hints?: Array | Array>; logged?: boolean; pageState?: Buffer|string; prepare?: boolean; @@ -758,4 +758,4 @@ declare module "cassandra-driver" { replicateOnWrite: boolean; } } -} \ No newline at end of file +} diff --git a/chart.js/chart.js.d.ts b/chart.js/chart.js.d.ts index 2d77f4c502..e05d930d4e 100644 --- a/chart.js/chart.js.d.ts +++ b/chart.js/chart.js.d.ts @@ -81,7 +81,7 @@ interface ChartOptions { } interface ChartFontOptions { - defaultFontColor?: string; + defaultFontColor?: ChartColor; defaultFontFamily?: string; defaultFontSize?: number; defaultFontStyle?: string; @@ -93,7 +93,7 @@ interface ChartTitleOptions { fullWdith?: boolean; fontSize?: number; fontFamily?: string; - fontColor?: string; + fontColor?: ChartColor; fontStyle?: string; padding?: number; text?: string; @@ -111,7 +111,7 @@ interface ChartLegendLabelOptions { boxWidth?: number; fontSize?: number; fontStyle?: number; - fontColor?: string; + fontColor?: ChartColor; fontFamily?: string; padding?: number; generateLabels?: (chart: any) => any; @@ -121,22 +121,22 @@ interface ChartTooltipOptions { enabled?: boolean; custom?: (a: any) => void; mode?: string; - backgroundColor?: string; + backgroundColor?: ChartColor; titleFontFamily?: string; titleFontSize?: number; titleFontStyle?: string; - titleFontColor?: string; + titleFontColor?: ChartColor; titleSpacing?: number; titleMarginBottom?: number; bodyFontFamily?: string; bodyFontSize?: number; bodyFontStyle?: string; - bodyFontColor?: string; + bodyFontColor?: ChartColor; bodySpacing?: number; footerFontFamily?: string; footerFontSize?: number; footerFontStyle?: string; - footerFontColor?: string; + footerFontColor?: ChartColor; footerSpacing?: number; footerMarginTop?: number; xPadding?: number; @@ -177,16 +177,16 @@ interface ChartElementsOptions { } interface ChartArcOtpions { - backgroundColor?: string; - borderColor?: string; + backgroundColor?: ChartColor; + borderColor?: ChartColor; borderWidth?: number; } interface ChartLineOptions { tension?: number; - backgroundColor?: string; + backgroundColor?: ChartColor; borderWidth?: number; - borderColor?: string; + borderColor?: ChartColor; borderCapStyle?: string; borderDash?: any[]; borderDashOffset?: number; @@ -196,37 +196,37 @@ interface ChartLineOptions { interface ChartPointOptions { radius?: number; pointStyle?: string; - backgroundColor?: string; + backgroundColor?: ChartColor; borderWidth?: number; - borderColor?: string; + borderColor?: ChartColor; hitRadius?: number; hoverRadius?: number; hoverBorderWidth?: number; } interface ChartRectangleOptions { - backgroundColor?: string; + backgroundColor?: ChartColor; borderWidth?: number; - borderColor?: string; + borderColor?: ChartColor; borderSkipped?: string; } interface GridLineOptions { display?: boolean; - color?: string; + color?: ChartColor; lineWidth?: number; drawBorder?: boolean; drawOnChartArea?: boolean; drawticks?: boolean; tickMarkLength?: number; zeroLineWidth?: number; - zeroLineColor?: string; + zeroLineColor?: ChartColor; offsetGridLines?: boolean; } interface ScaleTitleOptions { display?: boolean; labelString?: string; - fontColor?: string; + fontColor?: ChartColor; fontFamily?: string; fontSize?: number; fontStyle?: string; @@ -236,7 +236,7 @@ interface TickOptions { autoSkip?: boolean; callback?: (value: any, index: any, values: any) => string; display?: boolean; - fontColor?: string; + fontColor?: ChartColor; fontFamily?: string; fontSize?: number; fontStyle?: string; @@ -251,20 +251,20 @@ interface TickOptions { } interface AngleLineOptions { display?: boolean; - color?: string; + color?: ChartColor; lineWidth?: number; } interface PointLabelOptions { callback?: (arg: any) => any; - fontColor?: string; + fontColor?: ChartColor; fontFamily?: string; fontSize?: number; fontStyle?: string; } interface TickOptions { - backdropColor?: string; + backdropColor?: ChartColor; backdropPaddingX?: number; backdropPaddingY?: number; maxTicksLimit?: number; @@ -285,10 +285,12 @@ interface LogarithmicTickOptions extends TickOptions { max?: number; } +type ChartColor = string | CanvasGradient | CanvasPattern; + interface ChartDataSets { - backgroundColor?: string[]; + backgroundColor?: ChartColor; borderWidth?: number; - borderColor?: string[]; + borderColor?: ChartColor; borderCapStyle?: string; borderDash?: number[]; borderDashOffset?: number; @@ -297,14 +299,14 @@ interface ChartDataSets { fill?: boolean; label?: string; lineTension?: number; - pointBorderColor?: string | string[]; - pointBackgroundColor?: string | string[]; + pointBorderColor?: ChartColor | ChartColor[]; + pointBackgroundColor?: ChartColor | ChartColor[]; pointBorderWidth?: number | number[]; pointRadius?: number | number[]; pointHoverRadius?: number | number[]; pointHitRadius?: number | number[]; - pointHoverBackgroundColor?: string | string[]; - pointHoverBorderColor?: string | string[]; + pointHoverBackgroundColor?: ChartColor | ChartColor[]; + pointHoverBorderColor?: ChartColor | ChartColor[]; pointHoverBorderWidth?: number | number[]; pointStyle?: string | string[] | HTMLImageElement | HTMLImageElement[]; xAxisID?: string; @@ -332,6 +334,32 @@ interface ChartScales { gridLines?: GridLineOptions; scaleLabel?: ScaleTitleOptions; ticks?: TickOptions; + xAxes?: ChartXAxe[]; + yAxes?: ChartYAxe[]; +} + +interface ChartXAxe { + type?: string; + display?: boolean; + id?: string; + stacked?: boolean; + categoryPercentage?: number; + barPercentage?: number; + gridLines?: GridLineOptions; + position?: string; + ticks?: TickOptions; + time?: TimeScale; + scaleLabel?: ScaleTitleOptions; +} + +interface ChartYAxe { + type?: string; + display?: boolean; + id?: string; + stacked?: boolean; + position?: string; + ticks?: TickOptions; + scaleLabel?: ScaleTitleOptions; } interface LinearScale extends ChartScales { @@ -343,6 +371,7 @@ interface LogarithmicScale extends ChartScales { } interface TimeScale extends ChartScales { + format?: string; displayFormats?: string; isoWeekday?: boolean; max?: string; diff --git a/ckeditor/ckeditor.d.ts b/ckeditor/ckeditor.d.ts index 9d8728338f..60b6491407 100644 --- a/ckeditor/ckeditor.d.ts +++ b/ckeditor/ckeditor.d.ts @@ -57,6 +57,7 @@ declare namespace CKEDITOR { var basePath: string; var currentInstance: editor; var document: dom.document; + var env: environmentConfig; var instances: editor[]; var loadFullCoreTimeout: number; var revision: string; @@ -1029,6 +1030,12 @@ declare namespace CKEDITOR { } + interface IMenuItemDefinition { + label:string, + command:string, + group:string, + order:number + } class editor extends event { activeEnterMode: number; @@ -1066,13 +1073,14 @@ declare namespace CKEDITOR { addCommand(commandName: string, commandDefinition: commandDefinition): void; addFeature(feature: feature): boolean; addMenuGroup(name: string, order?: number): void; - addMenuItem(name: string, definition?: any): void; - addMenuItems(definitions: any[]): void; + addMenuItem(name: string, definition?: IMenuItemDefinition): void; + addMenuItems(definitions: {[id:string]:IMenuItemDefinition}): void; addMode(mode: string, exec: () => void): void; addRemoveFormatFilter(func: Function): void; applyStyle(style: style): void; attachStyleStateChange(style: style, callback: Function): void; checkDirty(): boolean; + commands:any; createFakeElement(realElement: Object, className: Object, realElementType: Object, isResizable: Object): void; createFakeParserElement(realElement: Object, className: Object, realElementType: Object, isResizable: Object): void; createRange(): dom.range; @@ -1235,6 +1243,11 @@ declare namespace CKEDITOR { } + interface buttonDefinition { + label : string; + command : string; + toolbar : string; + } interface template { @@ -1284,10 +1297,31 @@ declare namespace CKEDITOR { class ui extends event { constructor(editor: editor); add(name: string, type: Object, definition: Object): void; - addButton(name: string, definition: dialog.definition.button): void; + addButton(name: string, definition: buttonDefinition): void; addHandler(type: Object, handler: Object): void; } + class environmentConfig { + air : boolean; + chrome : boolean; + cssClass : string; + edge : boolean; + gecko : boolean; + hc : boolean; + hidpi : boolean; + iOS : boolean; + ie : boolean; + isCompatible : boolean; + mac : boolean; + needsBrFiller : boolean; + needsNbspFiller : boolean; + quirks : boolean; + safari : boolean; + version : number; + webkit : boolean; + secure( ) : boolean; + } + namespace ui { namespace dialog { class uiElement { @@ -1761,6 +1795,7 @@ declare namespace CKEDITOR { namespace tools { var callFunction: Function; + function enableHtml5Elements(doc: Object, withAppend? : Boolean) : void; } @@ -1772,3 +1807,4 @@ declare namespace CKEDITOR { function detect(defaultLanguage: string, probeLanguage: string): string; } } + diff --git a/core-js/core-js.d.ts b/core-js/core-js.d.ts index e9be316364..c633dc4ef6 100644 --- a/core-js/core-js.d.ts +++ b/core-js/core-js.d.ts @@ -31,7 +31,34 @@ interface ObjectConstructor { * Copy the values of all of the enumerable own properties from one or more source objects to a * target object. Returns the target object. * @param target The target object to copy to. - * @param sources One or more source objects to copy properties from. + * @param source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects from which to copy properties */ assign(target: any, ...sources: any[]): any; diff --git a/credential/credential-tests.ts b/credential/credential-tests.ts index 6013436b05..307201c76e 100644 --- a/credential/credential-tests.ts +++ b/credential/credential-tests.ts @@ -1,16 +1,29 @@ /// +// all from current main repo examples + import * as credential from 'credential'; -credential.hash('password', function(err: Error, hash: string) { - if (err) console.error(err); - else console.log(hash); +var pw = credential(); +var newPassword = 'I have a really great password.'; + +pw.hash(newPassword, function (err, hash) { + if (err) { throw err; } + console.log('Store the password hash.', hash); }); -const hash = '{}'; -const password = 'test'; +var storedHash = { + "hash": "gNofnhlBl36AdRyktwATxKoqWKa6hsIEzwCmW/YXN//7PtiJwCRbepV9fUKu0L9TJELCKoDiBy6rGM8ov7lg2yLY", + "salt": "yyN3KUzlr4KrKWMM2K3d2Ddxf8OTq+vkKG+mtnmQVIibxSJz8drfzkYzqcH0EM+PVKR/1nClRr/CPDuJsq+FOcIw", + "keyLength": 66, + "hashMethod": "pbkdf2", + "iterations": 181019 +}; +var userInput = 'I have a really great password.'; -credential.verify(hash, password, function(err: Error, isValid: boolean) { - if (err) console.error(err); - else console.log(isValid ? 'Password match' : 'Incorrect password'); +pw.verify(storedHash, userInput, function (err, isValid) { + var msg: string; + if (err) { throw err; } + msg = isValid ? 'Passwords match!' : 'Wrong password.'; + console.log(msg); }); diff --git a/credential/credential.d.ts b/credential/credential.d.ts index 2934a090d4..af16e0e412 100644 --- a/credential/credential.d.ts +++ b/credential/credential.d.ts @@ -4,15 +4,33 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'credential' { + interface defaultOptions { + keyLength: number; + work: number; + hashMethod: string; + } - type HashCallback = (err: Error, hash: string) => void; - type VerifyCallback = (err: Error, isValid: boolean) => void; + interface hashObject { + hash: string; + salt: string; + keyLength: number; + hashMethod: string; + iterations: number; + } - namespace credential { - function hash(password: string, callback: HashCallback): void; - function verify(hash: string, password: string, callback: VerifyCallback): void; - } + type HashCallback = (err: Error, hash: hashObject) => void; + type VerifyCallback = (err: Error, isValid: boolean) => void; - export = credential; + function credential(defaultOptions?: defaultOptions): { + hash(password: string, callback: HashCallback): void; + hash(password: string): Promise; + // iterations(work: number, base): number; + verify(hash: hashObject | string, password: string, callback: VerifyCallback): void; + verify(hash: hashObject | string, password: string): Promise; + expired(hash: string, days: number): boolean; + } + namespace credential { } + + export = credential; } diff --git a/csv-stringify/csv-stringify.d.ts b/csv-stringify/csv-stringify.d.ts index a1cc16a15b..1effe84f61 100644 --- a/csv-stringify/csv-stringify.d.ts +++ b/csv-stringify/csv-stringify.d.ts @@ -58,8 +58,8 @@ declare module "csv-stringify" { interface Stringifier extends NodeJS.ReadWriteStream { - // Stringifier stream takes array of strings - write(line: string[]): boolean; + // Stringifier stream takes array of strings or Object + write(line: string[] | Object): boolean; // repeat declarations from NodeJS.WritableStream to avoid compile error write(buffer: Buffer, cb?: Function): boolean; diff --git a/draft-js/draft-js.d.ts b/draft-js/draft-js.d.ts index 999741b426..bf10cd22c4 100644 --- a/draft-js/draft-js.d.ts +++ b/draft-js/draft-js.d.ts @@ -180,17 +180,17 @@ declare namespace Draft { namespace Utils { import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; - interface KeyBindingUtil { + class KeyBindingUtil { /** * Check whether the ctrlKey modifier is *not* being used in conjunction with * the altKey modifier. If they are combined, the result is an `altGraph` * key modifier, which should not be handled by this set of key bindings. */ - isCtrlKeyCommand(e: SyntheticKeyboardEvent): boolean; + static isCtrlKeyCommand(e: SyntheticKeyboardEvent): boolean; - isOptionKeyCommand(e: SyntheticKeyboardEvent): boolean; + static isOptionKeyCommand(e: SyntheticKeyboardEvent): boolean; - hasCommandModifier(e: SyntheticKeyboardEvent): boolean; + static hasCommandModifier(e: SyntheticKeyboardEvent): boolean; } /** @@ -797,8 +797,8 @@ declare namespace Draft { type URI = any; - interface AtomicBlockUtils { - insertAtomicBlock(editorState: EditorState, entityKey: string, character: string): EditorState; + class AtomicBlockUtils { + static insertAtomicBlock(editorState: EditorState, entityKey: string, character: string): EditorState; } /** diff --git a/drop/drop-tests.ts b/drop/drop-tests.ts index cc19621fbd..0da04e9445 100644 --- a/drop/drop-tests.ts +++ b/drop/drop-tests.ts @@ -36,3 +36,11 @@ var e = new Drop({ content: () => greenBox }); +var Tooltip = Drop.createContext({ + classPrefix: 'tooltip' +}); + +var t = new Tooltip({ + target: yellowBox, + content: () => greenBox +}); diff --git a/drop/drop.d.ts b/drop/drop.d.ts index 63f9c8621e..87ae4425b9 100644 --- a/drop/drop.d.ts +++ b/drop/drop.d.ts @@ -27,7 +27,7 @@ declare class Drop { public once(event: string, handler: Function, context?: any): void; public off(event: string, handler?: Function): void; - public static createContext(options: Drop.IDropContextOptions): Drop; + public static createContext(options: Drop.IDropContextOptions): typeof Drop; } declare namespace Drop { @@ -59,4 +59,3 @@ declare namespace Drop { declare module "drop" { export = Drop; } - diff --git a/elastic.js/elastic.js-tests.ts b/elastic.js/elastic.js-tests.ts new file mode 100644 index 0000000000..24c9784f81 --- /dev/null +++ b/elastic.js/elastic.js-tests.ts @@ -0,0 +1,6 @@ +/// + +let body = new elasticjs.Request({}) + .query(new elasticjs.MatchQuery('title_field', 'testQuery')) + .facet(new elasticjs.TermsFacet('tags').field('tags')) + .toJSON(); diff --git a/elastic.js/elastic.js.d.ts b/elastic.js/elastic.js.d.ts new file mode 100644 index 0000000000..850d1ccdfa --- /dev/null +++ b/elastic.js/elastic.js.d.ts @@ -0,0 +1,8972 @@ +// Type definitions for elastic.js v1.2.0 +// Project: https://www.npmjs.com/package/elastic.js +// Definitions by: Oleksii Trekhleb +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module elasticjs { + + export interface Facet {} + export interface Geo {} + export interface Suggest {} + export interface Generator {} + export interface Query {} + export interface Filter {} + export interface Aggregation {} + export interface ScoreFunction {} + + export class AggregationMixin implements Aggregation { + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): AggregationMixin; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): AggregationMixin; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A container Filter that allows Boolean AND composition of Filters. + */ + export class AndFilter implements Filter { + + /* + A container Filter that allows Boolean AND composition of Filters. + */ + constructor(f: Filter | Filter[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): AndFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): AndFilter; + + /* + Sets the filters for the filter. If fltr is a single + Filter, it is added to the current filters. If fltr is an array + of Filters, then they replace all existing filters. + */ + filters(fltr: Filter | Filter[]): AndFilter; + + /* + Sets the filter name. + */ + name(name: string): AndFilter; + + /* + Returns the filter object. + */ + toJSON(): AndFilter; + + } + + + /* + A single-value metrics aggregation that computes the average of numeric + values that are extracted from the aggregated documents. These values can be + extracted either from specific numeric fields in the documents, or be + generated by a provided script. + */ + export class AvgAggregation implements Aggregation { + + /* + Aggregation that computes the average of numeric values that are extracted + from the aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the field to operate on. + */ + field(field: string): AvgAggregation; + + /* + The script language being used. + */ + lang(language: string): AvgAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): AvgAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): AvgAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): AvgAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A BoolFilter allows you to build Boolean filter constructs + from individual filters. Similar in concept to Boolean query, except that + the clauses are other filters. Can be placed within queries that accept a + filter. + */ + export class BoolFilter implements Filter { + + /* + A Filter that matches documents matching boolean combinations of other + filters. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): BoolFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): BoolFilter; + + /* + Adds filter to boolean container. Given filter "must" appear in + matching documents. If passed a single Filter it is added to the + list of existing filters. If passed an array of Filters, they + replace all existing filters. + */ + must(oFilter: Filter | Filter[]): BoolFilter; + + /* + Adds filter to boolean container. Given filter "must not" appear + in matching documents. If passed a single Filter it is added to + the list of existing filters. If passed an array of Filters, + they replace all existing filters. + */ + mustNot(oFilter: Filter | Filter[]): BoolFilter; + + /* + Sets the filter name. + */ + name(name: string): BoolFilter; + + /* + Adds filter to boolean container. Given filter "should" appear in + matching documents. If passed a single Filter it is added to + the list of existing filters. If passed an array of Filters, + they replace all existing filters. + */ + should(oFilter: Filter | Filter[]): BoolFilter; + + /* + Returns the filter object. + */ + toJSON(): BoolFilter; + + } + + + /* + A boolQuery allows you to build Boolean query constructs + from individual term or phrase queries. For example you might want to search + for documents containing the terms javascript and python. + */ + export class BoolQuery implements Query { + + /* + A Query that matches documents matching boolean combinations of other + queries, e.g. termQuerys, phraseQuerys or other boolQuerys. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets if the Query should be enhanced with a + MatchAllQuery in order to act as a pure exclude when + only negative (mustNot) clauses exist. Default: true. + */ + adjustPureNegative(trueFalse: string): BoolQuery; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): BoolQuery; + + /* + Enables or disables similarity coordinate scoring of documents + matching the Query. Default: false. + */ + disableCoord(trueFalse: string): BoolQuery; + + /* + Sets the number of optional clauses that must match. + + By default no optional clauses are necessary for a match + (unless there are no required clauses). If this method is used, + then the specified number of clauses is required. + + Use of this method is totally independent of specifying that + any specific clauses are required (or prohibited). This number will + only be compared against the number of matching optional clauses. + */ + minimumNumberShouldMatch(minMatch: number): BoolQuery; + + /* + Adds query to boolean container. Given query "must" appear in matching documents. + */ + must(oQuery: Object): BoolQuery; + + /* + Adds query to boolean container. Given query "must not" appear in matching documents. + */ + mustNot(oQuery: Object): BoolQuery; + + /* + Adds query to boolean container. Given query "should" appear in matching documents. + */ + should(oQuery: Object): BoolQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + The boost_factor score allows you to multiply the score by the provided + boost_factor. This can sometimes be desired since boost value set on specific + queries gets normalized, while for this score function it does not. + */ + export class BoostFactorScoreFunction implements ScoreFunction { + + /* + Multiply the score by the provided boost_factor. + */ + constructor(boostVal: number); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost factor. + */ + boost(b: number): BoostFactorScoreFunction; + + /* + Adds a filter whose matching documents will have the score function applied. + */ + filter(oFilter: Filter): BoostFactorScoreFunction; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + The boosting query can be used to effectively demote results that match + a given query. Unlike the “NOT” clause in bool query, this still selects + documents that contain undesirable terms, but reduces their overall + score. + */ + export class BoostingQuery implements Query { + + /* + Constructs a query that can demote search results. A negative boost. + */ + constructor(positiveQry: Object, negativeQry: Object, negativeBoost: number); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): BoostingQuery; + + /* + Sets the query used to match documents in the positive + query that will be negatively boosted. + */ + negative(oQuery: Object): BoostingQuery; + + /* + Sets the negative boost value. + */ + negativeBoost(boost: number): BoostingQuery; + + /* + Sets the "master" query that determines which results are returned. + */ + positive(oQuery: Object): BoostingQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A single-value metrics aggregation that calculates an approximate count of + distinct values. Values can be extracted either from specific fields in the + document or generated by a script. + */ + export class CardinalityAggregation implements Aggregation { + + /* + Aggregation that calculates an approximate count of distinct values. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the field to operate on. + */ + field(field: string): CardinalityAggregation; + + /* + The script language being used. + */ + lang(language: string): CardinalityAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): CardinalityAggregation; + + /* + Allows to trade memory for accuracy, and defines a unique count below which + counts are expected to be close to accurate. Above this value, counts might + become a bit more fuzzy. The maximum supported value is 40000, thresholds + above this number will have the same effect as a threshold of 40000. + Default value depends on the number of parent aggregations that multiple + create buckets (such as terms or histograms). + */ + precisionThreshold(num: number): CardinalityAggregation; + + /* + Set to false to disable rehashing of values. You must have computed a hash + on the client-side and stored it into your documents if you disable this. + */ + rehash(trueFalse: boolean): CardinalityAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): CardinalityAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A query that executes high-frequency terms in a optional sub-query to + prevent slow queries due to "common" terms like stopwords. + + This query basically builds two queries out of the terms in the query + string where low-frequency terms are added to a required boolean clause and + high-frequency terms are added to an optional boolean clause. The optional + clause is only executed if the required "low-frequency' clause matches. + + CommonTermsQuery has several advantages over stopword + filtering at index or query time since a term can be "classified" based on + the actual document frequency in the index and can prevent slow queries even + across domains without specialized stopword files. + */ + export class CommonTermsQuery implements Query { + + /* + A query that executes high-frequency terms in a optional sub-query. + */ + constructor(field: string, qstr: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the analyzer name used to analyze the Query object. + */ + analyzer(analyzer: string): CommonTermsQuery; + + /* + Sets the boost value for documents commoning the Query. + */ + boost(boost: Number): CommonTermsQuery; + + /* + Sets the maximum threshold/frequency to be considered a low + frequency term. Set to a value between 0 and 1. + */ + cutoffFrequency(freq: Number): CommonTermsQuery; + + /* + Enables or disables similarity coordinate scoring of documents + commoning the Query. Default: false. + */ + disableCoord(trueFalse: string): CommonTermsQuery; + + /* + Sets the field to query against. + */ + field(f: string): CommonTermsQuery; + + /* + Sets the boolean operator to be used for high frequency terms. + Default: AND + */ + highFreqOperator(op: string): CommonTermsQuery; + + /* + Sets the boolean operator to be used for low frequency terms. + Default: AND + */ + lowFreqOperator(op: string): CommonTermsQuery; + + /* + Sets the minimum number of low freq matches that need to match in + a document before that document is returned in the results. + */ + minimumShouldMatch(min: number): CommonTermsQuery; + + /* + Sets the minimum number of high freq matches that need to match in + a document before that document is returned in the results. + */ + minimumShouldMatchHighFreq(min: number): CommonTermsQuery; + + /* + Sets the minimum number of low freq matches that need to match in + a document before that document is returned in the results. + */ + minimumShouldMatchLowFreq(min: number): CommonTermsQuery; + + /* + Sets the query string. + */ + query(qstr: string): CommonTermsQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + export class CompletionSuggester implements Suggest { + + /* + A suggester that allows basic auto-complete functionality. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets analyzer used to analyze the suggest text. + */ + analyzer(analyzer: string): CompletionSuggester; + + /* + Maximum edit distance (fuzziness), defaults to 1. Automatically + enables fuzzy suggestions when set to any value. + */ + editDistance(d: number): CompletionSuggester; + + /* + Sets the field used to generate suggestions from. + */ + field(field: string): CompletionSuggester; + + /* + Enable fuzzy completions which means a can spell a word + incorrectly and still get a suggestion. + */ + fuzzy(trueFalse: boolean): CompletionSuggester; + + /* + Minimum length of the input before fuzzy suggestions are returned, defaults + to 3. Automatically enables fuzzy suggestions when set to any value. + */ + minLength(m: number): CompletionSuggester; + + /* + Minimum length of the input, which is not checked for fuzzy alternatives, defaults + to 1. Automatically enables fuzzy suggestions when set to any value. + */ + prefixLength(l: number): CompletionSuggester; + + /* + Sets the maximum number of suggestions to be retrieved from + each individual shard. + */ + shardSize(s: number): CompletionSuggester; + + /* + Sets the number of suggestions returned for each token. + */ + size(s: number): CompletionSuggester; + + /* + Sets the text to get suggestions for. If not set, the global + suggestion text will be used. + */ + text(txt: string): CompletionSuggester; + + /* + Retrieves the internal suggest object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets if transpositions should be counted as one or two changes, defaults + to true when fuzzy is enabled. Automatically enables fuzzy suggestions + when set to any value. + */ + transpositions(trueFalse: boolean): CompletionSuggester; + + /* + Sets all are measurements (like edit distance, transpositions and lengths) + in unicode code points (actual letters) instead of bytes. Automatically + enables fuzzy suggestions when set to any value. + */ + unicodeAware(trueFalse: boolean): CompletionSuggester; + + } + + + /* + A constant score query wraps another Query or + Filter and returns a constant score for each + result that is equal to the query boost. + + Note that lucene's query normalization (queryNorm) attempts + to make scores between different queries comparable. It does not + change the relevance of your query, but it might confuse you when + you look at the score of your documents and they are not equal to + the query boost value as expected. The scores were normalized by + queryNorm, but maintain the same relevance. + */ + export class ConstantScoreQuery implements Query { + + /* + Constructs a query where each documents returned by the internal + query or filter have a constant score equal to the boost factor. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): ConstantScoreQuery; + + /* + Enables caching of the filter. + */ + cache(trueFalse: boolean): ConstantScoreQuery; + + /* + Set the cache key. + */ + cacheKey(k: string): ConstantScoreQuery; + + /* + Adds the filter to apply a constant score to. + */ + filter(oFilter: Object): ConstantScoreQuery; + + /* + Adds the query to apply a constant score to. + */ + query(oQuery: Object): ConstantScoreQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A multi-bucket aggregation similar to the histogram except it can only be + applied on date values. Since dates are represented in elasticsearch + internally as long values, it is possible to use the normal histogram on + dates as well, though accuracy will be compromised. The reason for this is + in the fact that time based intervals are not fixed (think of leap years and + on the number of days in a month). For this reason, we need a special + support for time based data. From a functionality perspective, this + histogram supports the same features as the normal histogram. The main + difference is that the interval can be specified by date/time expressions. + */ + export class DateHistogramAggregation implements Aggregation { + + /* + Aggregation similar to the histogram except it can only be applied on + date values. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): DateHistogramAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): DateHistogramAggregation; + + /* + Set's the range/bounds for the histogram aggregation. Useful when you + want to include buckets that might be outside the bounds of indexed + documents. + */ + extendedBounds(min: string | number, max: string | number): DateHistogramAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): DateHistogramAggregation; + + /* + Sets the format expression for the terms. Use for number or date + formatting + */ + format(f: string): DateHistogramAggregation; + + /* + Sets the histogram interval. Buckets are generated based on this interval + value. + */ + interval(i: string): DateHistogramAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): DateHistogramAggregation; + + /* + The script language being used. + */ + lang(language: string): DateHistogramAggregation; + + /* + Only return terms that match more than a configured number of hits. + */ + minDocCount(num: number): DateHistogramAggregation; + + /* + Sets order for the aggregated values. + */ + order(order: string, direction: string): DateHistogramAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): DateHistogramAggregation; + + /* + Set the post-rouding offset. + */ + postOffset(offset: string): DateHistogramAggregation; + + /* + Set the post-rouding date time zone. + */ + postZone(tz: string): DateHistogramAggregation; + + /* + Set the pre-rouding offset. + */ + preOffset(offset: string): DateHistogramAggregation; + + /* + Set the pre-rouding date time zone. + */ + preZone(tz: string): DateHistogramAggregation; + + /* + Set to true to apply interval adjusts to day and above intervals. + */ + preZoneAdjustLargeInterval(trueFalse: boolean): DateHistogramAggregation; + + /* + Allows you generate or modify the terms using a script. + */ + script(scriptCode: string): DateHistogramAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): DateHistogramAggregation; + + /* + Set the date time zone. + */ + timeZone(tz: string): DateHistogramAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + The DateHistogram facet works with time-based values by building a histogram across time + intervals of the value field. Each value is rounded into an interval (or + placed in a bucket), and statistics are provided per interval/bucket (count and total). + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class DateHistogramFacet implements Facet { + + /* + A facet which returns the N most frequent terms within a collection + or set of collections. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): DateHistogramFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): DateHistogramFacet; + + /* + The date histogram works on numeric values (since time is stored + in milliseconds since the epoch in UTC). + + But, sometimes, systems will store a different resolution (like seconds since UTC) + in a numeric field. The factor parameter can be used to change the value in the field + to milliseconds to actual do the relevant rounding, and then be applied again to get to + the original unit. + + For example, when storing in a numeric field seconds resolution, + the factor can be set to 1000. + */ + factor(f: number): DateHistogramFacet; + + /* + Sets the field to be used to construct the this facet. + */ + field(fieldName: string): DateHistogramFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): DateHistogramFacet; + + /* + Sets the bucket interval used to calculate the distribution. + */ + interval(timeInterval: string): DateHistogramFacet; + + /* + Allows you to specify a different key field to be used to group intervals. + */ + keyField(fieldName: string): DateHistogramFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): DateHistogramFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): DateHistogramFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): DateHistogramFacet; + + /* + Sets the type of ordering that will be performed on the date + buckets. Valid values are: + + + time - the default, sort by the buckets start time in milliseconds. + count - sort by the number of items in the bucket + total - sort by the sum/total of the items in the bucket + + */ + order(o: string): DateHistogramFacet; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): DateHistogramFacet; + + /* + Set's a specific post-rounding offset. Format is 1d, 1h, etc. + */ + postOffset(offset: string): DateHistogramFacet; + + /* + By default, time values are stored in UTC format. + + This method allows users to set a time zone value that is then used to compute + intervals after rounding on the interval value. The value is an offset from UTC. + The tz offset value is simply added to the resulting bucket's date value. + + For example, to use EST you would set the value to -5. + */ + postZone(tz: number): DateHistogramFacet; + + /* + Set's a specific pre-rounding offset. Format is 1d, 1h, etc. + */ + preOffset(offset: string): DateHistogramFacet; + + /* + By default, time values are stored in UTC format. + + This method allows users to set a time zone value that is then used to + compute intervals before rounding on the interval value. The value is an + offset from UTC. + + For example, to use EST you would set the value to -5. + */ + preZone(tz: number): DateHistogramFacet; + + /* + Enables large date interval conversions (day and up). + + Set to true to enable and then set the interval to an + interval greater than a day. + */ + preZoneAdjustLargeInterval(trueFalse: boolean): DateHistogramFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): DateHistogramFacet; + + /* + By default, time values are stored in UTC format. + + This method allows users to set a time zone value that is then used + to compute intervals before rounding on the interval value. Equalivent to + preZone. Use preZone if possible. The + value is an offset from UTC. + + For example, to use EST you would set the value to -5. + */ + timeZone(tz: number): DateHistogramFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Allows you to specify a different value field to aggrerate over. + */ + valueField(fieldName: string): DateHistogramFacet; + + /* + Allows you modify the value field using a script. The modified value + is then used to compute the statistical data. + */ + valueScript(scriptCode: string): DateHistogramFacet; + + } + + + /* + A range aggregation that is dedicated for date values. The main difference + between this aggregation and the normal range aggregation is that the from + and to values can be expressed in Date Math expressions, and it is also + possible to specify a date format by which the from and to response fields + will be returned. Note that this aggregration includes the from value and + excludes the to value for each range. + + Note that this aggregration includes the from value and excludes the to + value for each range. + */ + export class DateRangeAggregation implements Aggregation { + + /* + Aggregation that is dedicated for date value ranges. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): DateRangeAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): DateRangeAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): DateRangeAggregation; + + /* + Sets the date format expression. + */ + format(f: string): DateRangeAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): DateRangeAggregation; + + /* + The script language being used. + */ + lang(language: string): DateRangeAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): DateRangeAggregation; + + /* + Adds a range to the list of exsiting range expressions. + */ + range(from: string, to: string, key: string): DateRangeAggregation; + + /* + Allows you generate or modify the terms using a script. + */ + script(scriptCode: string): DateRangeAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): DateRangeAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Decay functions score a document with a function that decays depending on + the distance of a numeric field value of the document from a user given + origin. This is similar to a range query, but with smooth edges instead of + boxes. + + Supported decay functions are: linear, exp, and gauss. + */ + export class DecayScoreFunction implements ScoreFunction { + + /* + Score a document with a function that decays depending on the distance + of a numeric field value of the document from given origin. + */ + constructor(field: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the decay value which defines how documents are scored at the distance + given at scale. + */ + decay(d: number): DecayScoreFunction; + + /* + Use the exp decay function. Exponential decay. + */ + exp(): DecayScoreFunction; + + /* + Sets the fields to run the decay function against. + */ + field(f: string): DecayScoreFunction; + + /* + Adds a filter whose matching documents will have the score function applied. + */ + filter(oFilter: Filter): DecayScoreFunction; + + /* + Use the gauss decay function. Normal decay. + */ + gauss(): DecayScoreFunction; + + /* + Use the linear decay function. Linear decay. + */ + linear(): DecayScoreFunction; + + /* + Sets the decay offset. The decay function will only compute a the decay + function for documents with a distance greater that the defined offset. + The default is 0. + */ + offset(o: string): DecayScoreFunction; + + /* + Sets the origin which is the “central point” from which the distance is + calculated. + */ + origin(o: string): DecayScoreFunction; + + /* + Sets the scale/rate of decay. + */ + scale(s: string): DecayScoreFunction; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + DirectGenerator is a candidate generator for PhraseSuggester. + It generates terms based on edit distance and operators much like the + TermSuggester. + */ + export class DirectGenerator implements Generator { + + /* + A candidate generator that generates terms based on edit distance. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the accuracy. How similar the suggested terms at least + need to be compared to the original suggest text. + */ + accuracy(a: number): DirectGenerator; + + /* + Sets the field used to generate suggestions from. + */ + field(field: string): DirectGenerator; + + /* + Sets the maximum edit distance candidate suggestions can have + in order to be considered as a suggestion. + */ + maxEdits(max: number): DirectGenerator; + + /* + The factor that is used to multiply with the size in order + to inspect more candidate suggestions. + */ + maxInspections(max: number): DirectGenerator; + + /* + Sets a maximum threshold in number of documents a suggest text + token can exist in order to be corrected. + */ + maxTermFreq(max: number): DirectGenerator; + + /* + Sets a minimal threshold of the number of documents a suggested + term should appear in. + */ + minDocFreq(min: number): DirectGenerator; + + /* + Sets the minimum length a suggest text term must have in order + to be corrected. + */ + minWordLen(len: number): DirectGenerator; + + /* + Sets an analyzer that is applied to each of the generated tokens + before they are passed to the actual phrase scorer. + */ + postFilter(analyzer: string): DirectGenerator; + + /* + Sets an analyzer that is applied to each of the tokens passed to + this generator. The analyzer is applied to the original tokens, + not the generated tokens. + */ + preFilter(analyzer: string): DirectGenerator; + + /* + Sets the number of suggestions returned for each token. + */ + size(s: number): DirectGenerator; + + /* + Sets the sort mode. Valid values are: + + + score - Sort by score first, then document frequency, and then the term itself + frequency - Sort by document frequency first, then simlarity score and then the term itself + + */ + sort(s: string): DirectGenerator; + + /* + Sets what string distance implementation to use for comparing + how similar suggested terms are. Valid values are: + + + internal - based on damerau_levenshtein but but highly optimized for comparing string distance for terms inside the index + damerau_levenshtein - String distance algorithm based on Damerau-Levenshtein algorithm + levenstein - String distance algorithm based on Levenstein edit distance algorithm + jarowinkler - String distance algorithm based on Jaro-Winkler algorithm + ngram - String distance algorithm based on character n-grams + + */ + stringDistance(s: string): DirectGenerator; + + /* + Sets the suggest mode. Valid values are: + + + missing - Only suggest terms in the suggest text that aren't in the index + popular - Only suggest suggestions that occur in more docs then the original suggest text term + always - Suggest any matching suggestions based on terms in the suggest text + + */ + suggestMode(m: string): DirectGenerator; + + /* + Retrieves the internal generator object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + export class DirectSettingsMixin { + + + /* + Sets the accuracy. How similar the suggested terms at least + need to be compared to the original suggest text. + */ + accuracy(a: number): DirectSettingsMixin; + + /* + Sets the maximum edit distance candidate suggestions can have + in order to be considered as a suggestion. + */ + maxEdits(max: number): DirectSettingsMixin; + + /* + The factor that is used to multiply with the size in order + to inspect more candidate suggestions. + */ + maxInspections(max: number): DirectSettingsMixin; + + /* + Sets a maximum threshold in number of documents a suggest text + token can exist in order to be corrected. + */ + maxTermFreq(max: number): DirectSettingsMixin; + + /* + Sets a minimal threshold of the number of documents a suggested + term should appear in. + */ + minDocFreq(min: number): DirectSettingsMixin; + + /* + Sets the minimum length a suggest text term must have in order + to be corrected. + */ + minWordLen(len: number): DirectSettingsMixin; + + /* + Sets the number of minimal prefix characters that must match in + order be a candidate suggestion. + */ + prefixLen(len: number): DirectSettingsMixin; + + /* + Sets the sort mode. Valid values are: + + + score - Sort by score first, then document frequency, and then the term itself + frequency - Sort by document frequency first, then simlarity score and then the term itself + + */ + sort(s: string): DirectSettingsMixin; + + /* + Sets what string distance implementation to use for comparing + how similar suggested terms are. Valid values are: + + + internal - based on damerau_levenshtein but but highly optimized for comparing string distance for terms inside the index + damerau_levenshtein - String distance algorithm based on Damerau-Levenshtein algorithm + levenstein - String distance algorithm based on Levenstein edit distance algorithm + jarowinkler - String distance algorithm based on Jaro-Winkler algorithm + ngram - String distance algorithm based on character n-grams + + */ + stringDistance(s: string): DirectSettingsMixin; + + /* + Sets the suggest mode. Valid values are: + + + missing - Only suggest terms in the suggest text that aren't in the index + popular - Only suggest suggestions that occur in more docs then the original suggest text term + always - Suggest any matching suggestions based on terms in the suggest text + + */ + suggestMode(m: string): DirectSettingsMixin; + + } + + + /* + A query that generates the union of documents produced by its subqueries, and + that scores each document with the maximum score for that document as produced + by any subquery, plus a tie breaking increment for any additional matching + subqueries. + */ + export class DisMaxQuery implements Query { + + /* + A query that generates the union of documents produced by its subqueries such + as termQuerys, phraseQuerys, boolQuerys, etc. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): DisMaxQuery; + + /* + Updates the queries. If passed a single Query, it is added to the + list of existing queries. If passed an array of Queries, it + replaces all existing values. + */ + queries(qs: Query | Query[]): DisMaxQuery; + + /* + The tie breaker value. + + The tie breaker capability allows results that include the same term in multiple + fields to be judged better than results that include this term in only the best of those + multiple fields, without confusing this with the better case of two different terms in + the multiple fields. + + Default: 0.0. + */ + tieBreaker(tieBreaker: number): DisMaxQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + An existsFilter matches documents where the specified field is present + and the field contains a legitimate value. + */ + export class ExistsFilter implements Filter { + + /* + Filters documents where a specified field exists and contains a value. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): ExistsFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): ExistsFilter; + + /* + Sets the field to check for missing values. + */ + field(name: string): ExistsFilter; + + /* + Sets the filter name. + */ + name(name: string): ExistsFilter; + + /* + Returns the filter object. + */ + toJSON(): ExistsFilter; + + } + + + /* + A multi-value metrics aggregation that computes stats over numeric values + extracted from the aggregated documents. These values can be extracted either + from specific numeric fields in the documents, or be generated by a provided + script. + + The extended_stats aggregations is an extended version of the + StatsAggregation, where additional metrics are added such as + sum_of_squares, variance and std_deviation. + */ + export class ExtendedStatsAggregation implements Aggregation { + + /* + Aggregation that computes extra stats over numeric values extracted from + the aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the field to operate on. + */ + field(field: string): ExtendedStatsAggregation; + + /* + The script language being used. + */ + lang(language: string): ExtendedStatsAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): ExtendedStatsAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): ExtendedStatsAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): ExtendedStatsAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + export class FacetMixin { + + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): FacetMixin; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): FacetMixin; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): FacetMixin; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): FacetMixin; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): FacetMixin; + + /* + Computes values across the the specified scope + */ + scope(scope: string): FacetMixin; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Wrapper to allow SpanQuery objects participate in composite single-field + SpanQueries by 'lying' about their search field. That is, the masked + SpanQuery will function as normal, but when asked for the field it + queries against, it will return the value specified as the masked field vs. + the real field used in the wrapped span query. + */ + export class FieldMaskingSpanQuery implements Query { + + /* + Wraps a SpanQuery and hides the real field being searched across. + */ + constructor(spanQry: Query, field: number); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): FieldMaskingSpanQuery; + + /* + Sets the value of the "masked" field. + */ + field(f: string): FieldMaskingSpanQuery; + + /* + Sets the span query to wrap. + */ + query(spanQuery: Query): FieldMaskingSpanQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Defines a single bucket of all the documents in the current document set + context that match a specified filter. Often this will be used to narrow down + the current aggregation context to a specific set of documents. + */ + export class FilterAggregation implements Aggregation { + + /* + Defines a single bucket of all the documents that match a given filter. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): FilterAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): FilterAggregation; + + /* + Sets the filter to be used for this aggregation. + */ + filter(oFilter: Filter): FilterAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Filter queries allow you to restrict the results returned by a query. There are + several different types of filters that can be applied + (see filter module). A filterQuery + takes a Query and a Filter object as arguments and constructs + a new Query that is then used for the search. + */ + export class FilteredQuery implements Query { + + /* + A query that applies a filter to the results of another query. + */ + constructor(someQuery: Object, someFilter: Object); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): FilteredQuery; + + /* + Enables caching of the filter. + */ + cache(trueFalse: boolean): FilteredQuery; + + /* + Set the cache key. + */ + cacheKey(k: string): FilteredQuery; + + /* + Adds the filter to apply a constant score to. + */ + filter(oFilter: Object): FilteredQuery; + + /* + Adds the query to apply a constant score to. + */ + query(oQuery: Object): FilteredQuery; + + /* + Sets the filter strategy. + + The strategy defines how the filter is applied during document collection. + Valid values are: + + + query_first - advance query scorer first then filter + random_access_random - random access filter + leap_frog - query scorer and filter "leap-frog", query goes first + leap_frog_filter_first - same as leap_frog, but filter goes first + random_access_N - replace N with integer, same as random access + except you can specify a custom threshold + + + This is an advanced setting, use with care. + */ + strategy(strategy: string): FilteredQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + The FilterFacet allows you to specify any valid Filter and + have the number of matching hits returned as the value. + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class FilterFacet implements Facet { + + /* + A facet that return a count of the hits matching the given filter. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): FilterFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): FilterFacet; + + /* + Sets the filter to be used for this facet. + */ + filter(oFilter: Object): FilterFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): FilterFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): FilterFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): FilterFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): FilterFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + export class FilterMixin { + + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): FilterMixin; + + /* + Sets the cache key. + */ + cacheKey(key: string): FilterMixin; + + /* + Sets the filter name. + */ + name(name: string): FilterMixin; + + /* + Returns the filter object. + */ + toJSON(): FilterMixin; + + } + + + /* + The function_score allows you to modify the score of documents that are + retrieved by a query. This can be useful if, for example, a score function is + computationally expensive and it is sufficient to compute the score on a + filtered set of documents. + */ + export class FunctionScoreQuery implements Query { + + /* + A query that allows you to modify the score of matching documents. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): FunctionScoreQuery; + + /* + Set the setermines how the new calculated score is combined with the + score from the original query. Valid values are: multiply, replace, sum, + avg, max, and min. + */ + boostMode(mode: string): FunctionScoreQuery; + + /* + Set the source filter. + */ + filter(oFilter: Filter): FunctionScoreQuery; + + /* + Add a single score function to the list of existing functions. + */ + //function (func: ScoreFunction): FunctionScoreQuery; + + /* + Sets the score functions. Replaces any existing score functions. + */ + functions(funcs: ScoreFunction[]): FunctionScoreQuery; + + /* + Set the source query. + */ + query(oQuery: Query): FunctionScoreQuery; + + /* + Set the scoring mode which specifies how the computed scores are combined. + Valid values are: avg, max, min, sum, multiply, and first. + */ + scoreMode(mode: string): FunctionScoreQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + The fuzzy_like_this_field query is the same as the fuzzy_like_this + query, except that it runs against a single field. It provides nicer query + DSL over the generic fuzzy_like_this query, and support typed fields + query (automatically wraps typed fields with type filter to match only on + the specific type). + + Fuzzifies ALL terms provided as strings and then picks the best n + differentiating terms. In effect this mixes the behaviour of FuzzyQuery and + MoreLikeThis but with special consideration of fuzzy scoring factors. This + generally produces good results for queries where users may provide details + in a number of fields and have no knowledge of boolean query syntax and + also want a degree of fuzzy matching and a fast query. + + For each source term the fuzzy variants are held in a BooleanQuery with + no coord factor (because we are not looking for matches on multiple variants + in any one doc). Additionally, a specialized TermQuery is used for variants + and does not use that variant term’s IDF because this would favour rarer + terms eg misspellings. Instead, all variants use the same IDF + ranking (the one for the source query term) and this is factored into the + variant’s boost. If the source query term does not exist in the index the + average IDF of the variants is used. + */ + export class FuzzyLikeThisFieldQuery implements Query { + + /* + Constructs a query where each documents returned are “like” provided text + */ + constructor(field: string, likeText: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + The analyzer that will be used to analyze the text. Defaults to the + analyzer associated with the field. + */ + analyzer(analyzerName: string): FuzzyLikeThisFieldQuery; + + /* + Sets the boost value of the Query. + */ + boost(boost: number): FuzzyLikeThisFieldQuery; + + /* + Should the Query fail when an unsupported field + is specified. Defaults to true. + */ + failOnUnsupportedField(trueFalse: boolean): FuzzyLikeThisFieldQuery; + + /* + The field to run the query against. + */ + field(f: string): FuzzyLikeThisFieldQuery; + + /* + Should term frequency be ignored. Defaults to false. + */ + ignoreTf(trueFalse: boolean): FuzzyLikeThisFieldQuery; + + /* + The text to find documents like + */ + likeText(s: string): FuzzyLikeThisFieldQuery; + + /* + The maximum number of query terms that will be included in any + generated query. Defaults to 25. + */ + maxQueryTerms(max: number): FuzzyLikeThisFieldQuery; + + /* + The minimum similarity of the term variants. Defaults to 0.5. + */ + minSimilarity(min: number): FuzzyLikeThisFieldQuery; + + /* + Length of required common prefix on variant terms. Defaults to 0.. + */ + prefixLength(len: number): FuzzyLikeThisFieldQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Fuzzy like this query find documents that are “like” provided text by + running it against one or more fields. + + Fuzzifies ALL terms provided as strings and then picks the best n + differentiating terms. In effect this mixes the behaviour of FuzzyQuery and + MoreLikeThis but with special consideration of fuzzy scoring factors. This + generally produces good results for queries where users may provide details + in a number of fields and have no knowledge of boolean query syntax and + also want a degree of fuzzy matching and a fast query. + + For each source term the fuzzy variants are held in a BooleanQuery with + no coord factor (because we are not looking for matches on multiple variants + in any one doc). Additionally, a specialized TermQuery is used for variants + and does not use that variant term’s IDF because this would favour rarer + terms eg misspellings. Instead, all variants use the same IDF + ranking (the one for the source query term) and this is factored into the + variant’s boost. If the source query term does not exist in the index the + average IDF of the variants is used. + */ + export class FuzzyLikeThisQuery implements Query { + + /* + Constructs a query where each documents returned are “like” provided text + */ + constructor(likeText: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + The analyzer that will be used to analyze the text. Defaults to the + analyzer associated with the field. + */ + analyzer(analyzerName: string): FuzzyLikeThisQuery; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): FuzzyLikeThisQuery; + + /* + Should the Query fail when an unsupported field + is specified. Defaults to true. + */ + failOnUnsupportedField(trueFalse: boolean): FuzzyLikeThisQuery; + + /* + The fields to run the query against. If you call with a single field, + it is added to the existing list of fields. If called with an array + of field names, it replaces any existing values with the new array. + */ + fields(f: string | string[]): FuzzyLikeThisQuery; + + /* + Should term frequency be ignored. Defaults to false. + */ + ignoreTf(trueFalse: boolean): FuzzyLikeThisQuery; + + /* + The text to find documents like + */ + likeText(s: string): FuzzyLikeThisQuery; + + /* + The maximum number of query terms that will be included in any + generated query. Defaults to 25. + */ + maxQueryTerms(max: number): FuzzyLikeThisQuery; + + /* + The minimum similarity of the term variants. Defaults to 0.5. + */ + minSimilarity(min: number): FuzzyLikeThisQuery; + + /* + Length of required common prefix on variant terms. Defaults to 0.. + */ + prefixLength(len: number): FuzzyLikeThisQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A fuzzy search query based on the Damerau-Levenshtein (optimal string + alignment) algorithm, though you can explicitly choose classic Levenshtein + by passing false to the transpositions parameter./p> + + fuzzy query on a numeric field will result in a range query “around” + the value using the min_similarity value. As an example, if you perform a + fuzzy query against a field value of "12" with a min similarity setting + of "2", the query will search for values between "10" and "14". + */ + export class FuzzyQuery implements Query { + + /* + Constructs a query where each documents returned are “like” provided text + */ + constructor(field: string, value: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value of the Query. + */ + boost(boost: number): FuzzyQuery; + + /* + The field to run the query against. + */ + field(f: string): FuzzyQuery; + + /* + The maximum number of query terms that will be included in any + generated query. Defaults to 50. + */ + maxExpansions(max: number): FuzzyQuery; + + /* + The minimum similarity of the term variants. Defaults to 0.5. + */ + minSimilarity(min: number): FuzzyQuery; + + /* + Length of required common prefix on variant terms. Defaults to 0. + */ + prefixLength(len: number): FuzzyQuery; + + /* + Sets rewrite method. Valid values are: + + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): FuzzyQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Set to false to use classic Levenshtein edit distance. + */ + transpositions(trueFalse: boolean): FuzzyQuery; + + /* + The query text to fuzzify. + */ + value(s: string): FuzzyQuery; + + } + + + /* + A filter that restricts matched results/docs to a geographic bounding box described by + the specified lon and lat coordinates. The format conforms with the GeoJSON specification. + */ + export class GeoBboxFilter implements Filter { + + /* + Filter results to those which are contained within the defined bounding box. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the bottom-right coordinate of the bounding box + */ + bottomRight(p: GeoPoint): GeoBboxFilter; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): GeoBboxFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): GeoBboxFilter; + + /* + Sets the fields to filter against. + */ + field(f: string): GeoBboxFilter; + + /* + Sets the filter name. + */ + name(name: string): GeoBboxFilter; + + /* + If the lat/long points should be normalized to lie within their + respective normalized ranges. + + Normalized ranges are: + lon = -180 (exclusive) to 180 (inclusive) range + lat = -90 to 90 (both inclusive) range + */ + normalize(trueFalse: string): GeoBboxFilter; + + /* + Returns the filter object. + */ + toJSON(): GeoBboxFilter; + + /* + Sets the top-left coordinate of the bounding box + */ + topLeft(p: GeoPoint): GeoBboxFilter; + + /* + Sets the type of the bounding box execution. Valid values are + "memory" and "indexed". Default is memory. + */ + type(type: string): GeoBboxFilter; + + } + + + /* + A multi-bucket aggregation that works on geo_point fields and conceptually + works very similar to the range aggregation. The user can define a point of + origin and a set of distance range buckets. The aggregation evaluate the + distance of each document value from the origin point and determines the + buckets it belongs to based on the ranges (a document belongs to a bucket + if the distance between the document and the origin falls within the distance + range of the bucket). + */ + export class GeoDistanceAggregation implements Aggregation { + + /* + Aggregation that works on geo_point fields and conceptually works very + similar to the range aggregation. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): GeoDistanceAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): GeoDistanceAggregation; + + /* + Sets the point of origin from where distances will be measured. Same as + origin. + */ + center(p: GeoPoint): GeoDistanceAggregation; + + /* + How to compute the distance. Valid values are: + plane, arc, sloppy_arc, and factor. + */ + distanceType(type: string): GeoDistanceAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): GeoDistanceAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): GeoDistanceAggregation; + + /* + Sets the point of origin from where distances will be measured. + */ + origin(p: GeoPoint): GeoDistanceAggregation; + + /* + Sets the point of origin from where distances will be measured. Same as + origin. + */ + point(p: GeoPoint): GeoDistanceAggregation; + + /* + Adds a range to the list of exsiting range expressions. + */ + range(from: string, to: string, key: string): GeoDistanceAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the distance unit. Valid values are: + in, yd, ft, km, NM, mm, cm, mi, and m. + */ + unit(unit: Number): GeoDistanceAggregation; + + } + + + /* + The geoDistanceFacet facet provides information over a range of distances from a + provided point. This includes the number of hits that fall within each range, + along with aggregate information (like total). + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class GeoDistanceFacet implements Facet { + + /* + A facet which provides information over a range of distances from a provided point. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Adds a new bounded range. + */ + addRange(from: Number, to: Number): GeoDistanceFacet; + + /* + Adds a new unbounded lower limit. + */ + addUnboundedFrom(from: Number): GeoDistanceFacet; + + /* + Adds a new unbounded upper limit. + */ + addUnboundedTo(to: Number): GeoDistanceFacet; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): GeoDistanceFacet; + + /* + How to compute the distance. Can either be arc (better precision) + or plane (faster). Defaults to arc. + */ + distanceType(type: string): GeoDistanceFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): GeoDistanceFacet; + + /* + Sets the document field containing the geo-coordinate to be used + to calculate the distance. Defaults to "location". + */ + field(fieldName: string): GeoDistanceFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): GeoDistanceFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): GeoDistanceFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): GeoDistanceFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): GeoDistanceFacet; + + /* + If the lat/long points should be normalized to lie within their + respective normalized ranges. + + Normalized ranges are: + lon = -180 (exclusive) to 180 (inclusive) range + lat = -90 to 90 (both inclusive) range + */ + normalize(trueFalse: string): GeoDistanceFacet; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): GeoDistanceFacet; + + /* + Sets the point of origin from where distances will be measured. + */ + point(p: GeoPoint): GeoDistanceFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): GeoDistanceFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the distance unit. Valid values are "mi" for miles or "km" + for kilometers. Defaults to "km". + */ + unit(unit: Number): GeoDistanceFacet; + + /* + Allows you to specify a different value field to aggrerate over. + */ + valueField(fieldName: string): GeoDistanceFacet; + + /* + Allows you modify the value field using a script. The modified value + is then used to compute the statistical data. + */ + valueScript(scriptCode: string): GeoDistanceFacet; + + } + + + /* + A filter that restricts matched results/docs to a given distance from the + point of origin. The format conforms with the GeoJSON specification. + */ + export class GeoDistanceFilter implements Filter { + + /* + Filter results to those which fall within the given distance of the point of origin. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): GeoDistanceFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): GeoDistanceFilter; + + /* + Sets the numeric distance to be used. The distance can be a + numeric value, and then the unit (either mi or km can be set) + controlling the unit. Or a single string with the unit as well. + */ + distance(numericDistance: Number): GeoDistanceFilter; + + /* + How to compute the distance. Can either be arc (better precision) + or plane (faster). Defaults to arc. + */ + distanceType(type: string): GeoDistanceFilter; + + /* + Sets the fields to filter against. + */ + field(f: string): GeoDistanceFilter; + + /* + Sets the filter name. + */ + name(name: string): GeoDistanceFilter; + + /* + If the lat/long points should be normalized to lie within their + respective normalized ranges. + + Normalized ranges are: + lon = -180 (exclusive) to 180 (inclusive) range + lat = -90 to 90 (both inclusive) range + */ + normalize(trueFalse: string): GeoDistanceFilter; + + /* + Will an optimization of using first a bounding box check will be + used. Defaults to memory which will do in memory checks. Can also + have values of indexed to use indexed value check, or none which + disables bounding box optimization. + */ + optimizeBbox(t: string): GeoDistanceFilter; + + /* + Sets the point of origin in which distance will be measured from + */ + point(p: GeoPoint): GeoDistanceFilter; + + /* + Returns the filter object. + */ + toJSON(): GeoDistanceFilter; + + /* + Sets the distance unit. Valid values are "mi" for miles or "km" + for kilometers. Defaults to "km". + */ + unit(unit: Number): GeoDistanceFilter; + + } + + + /* + A filter that restricts matched results/docs to a given distance range from the + point of origin. The format conforms with the GeoJSON specification. + */ + export class GeoDistanceRangeFilter implements Filter { + + /* + Filter results to those which fall within the given distance range of the point of origin. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): GeoDistanceRangeFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): GeoDistanceRangeFilter; + + /* + How to compute the distance. Can either be arc (better precision) + or plane (faster). Defaults to arc. + */ + distanceType(type: string): GeoDistanceRangeFilter; + + /* + Sets the fields to filter against. + */ + field(f: string): GeoDistanceRangeFilter; + + /* + Sets the start point of the distance range + */ + from(numericDistance: Number): GeoDistanceRangeFilter; + + /* + Greater than value. Same as setting from to the value, and + include_lower to false, + */ + gt(val: Number): GeoDistanceRangeFilter; + + /* + Greater than or equal to value. Same as setting from to the value, + and include_lower to true. + */ + gte(val: Number): GeoDistanceRangeFilter; + + /* + Should the first from (if set) be inclusive or not. + Defaults to true + */ + includeLower(trueFalse: boolean): GeoDistanceRangeFilter; + + /* + Should the last to (if set) be inclusive or not. Defaults to true. + */ + includeUpper(trueFalse: boolean): GeoDistanceRangeFilter; + + /* + Less than value. Same as setting to to the value, and include_upper + to false. + */ + lt(val: Number): GeoDistanceRangeFilter; + + /* + Less than or equal to value. Same as setting to to the value, + and include_upper to true. + */ + lte(val: Number): GeoDistanceRangeFilter; + + /* + Sets the filter name. + */ + name(name: string): GeoDistanceRangeFilter; + + /* + If the lat/long points should be normalized to lie within their + respective normalized ranges. + + Normalized ranges are: + lon = -180 (exclusive) to 180 (inclusive) range + lat = -90 to 90 (both inclusive) range + */ + normalize(trueFalse: string): GeoDistanceRangeFilter; + + /* + Will an optimization of using first a bounding box check will be + used. Defaults to memory which will do in memory checks. Can also + have values of indexed to use indexed value check, or none which + disables bounding box optimization. + */ + optimizeBbox(t: string): GeoDistanceRangeFilter; + + /* + Sets the point of origin in which distance will be measured from + */ + point(p: GeoPoint): GeoDistanceRangeFilter; + + /* + Sets the end point of the distance range + */ + to(numericDistance: Number): GeoDistanceRangeFilter; + + /* + Returns the filter object. + */ + toJSON(): GeoDistanceRangeFilter; + + /* + Sets the distance unit. Valid values are "mi" for miles or "km" + for kilometers. Defaults to "km". + */ + unit(unit: Number): GeoDistanceRangeFilter; + + } + + + /* + A multi-bucket aggregation that works on geo_point fields and groups points + into buckets that represent cells in a grid. The resulting grid can be sparse + and only contains cells that have matching data. Each cell is labeled using a + geohash which is of user-definable precision. + */ + export class GeoHashGridAggregation implements Aggregation { + + /* + Aggregation that works on geo_point fields and groups points into buckets + that represent cells in a grid. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): GeoHashGridAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): GeoHashGridAggregation; + + /* + Sets the geo field to perform calculations from. + */ + field(field: string): GeoHashGridAggregation; + + /* + Sets the Geo Hash precision. The precision value can be between 1 and 12 + where 12 is the highest precision. + */ + precision(p: number): GeoHashGridAggregation; + + /* + Determines how many geohash_grid the coordinating node will request from + each shard. + */ + shardSize(shardSize: number): GeoHashGridAggregation; + + /* + Sets the number of aggregation entries that will be returned. + */ + size(size: number): GeoHashGridAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A GeoPoint object that can be used in queries and filters that + take a GeoPoint. GeoPoint supports various input formats. + + See http://www.elasticsearch.org/guide/reference/mapping/geo-point-type.html + */ + export class GeoPoint implements Geo { + + /* + Defines a point + */ + constructor(p: any[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the GeoPoint from an array point. The array must contain only + 2 values. The first value is the lat and the 2nd value is the lon. + + Example: + [41.12, -71.34] + */ + array(a: any[]): GeoPoint; + + /* + Sets the GeoPoint as a GeoHash. The hash is a string of + alpha-numeric characters with a precision length that defaults to 12. + + Example: + "drm3btev3e86" + */ + geohash(hash: string, precision: number): GeoPoint; + + /* + Sets the GeoPoint as properties on an object. The object must have + a 'lat' and 'lon' or a 'geohash' property. + + Example: + {lat: 41.12, lon: -71.34} or {geohash: "drm3btev3e86"} + */ + properties(obj: Object): GeoPoint; + + /* + Sets the GeoPoint as a string. The format is "lat,lon". + + Example: + + "41.12,-71.34" + */ + string(s: string): GeoPoint; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A filter for locating documents that fall within a polygon of points. Simply provide a lon/lat + for each document as a Geo Point type. The format conforms with the GeoJSON specification. + */ + export class GeoPolygonFilter { + + /* + Filter results to those which are contained within the polygon of points. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): GeoPolygonFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): GeoPolygonFilter; + + /* + Sets the fields to filter against. + */ + field(f: string): GeoPolygonFilter; + + /* + Sets the filter name. + */ + name(name: string): GeoPolygonFilter; + + /* + If the lat/long points should be normalized to lie within their + respective normalized ranges. + + Normalized ranges are: + lon = -180 (exclusive) to 180 (inclusive) range + lat = -90 to 90 (both inclusive) range + */ + normalize(trueFalse: string): GeoPolygonFilter; + + /* + Sets a series of points that represent a polygon. If passed a + single GeoPoint object, it is added to the current + list of points. If passed an array of GeoPoint + objects it replaces all current values. + */ + points(pointsArray: any[]): GeoPolygonFilter; + + /* + Returns the filter object. + */ + toJSON(): GeoPolygonFilter; + + } + + + /* + Efficient filtering of documents containing shapes indexed using the + geo_shape type. + + Much like the geo_shape type, the geo_shape filter uses a grid square + representation of the filter shape to find those documents which have shapes + that relate to the filter shape in a specified way. In order to do this, the + field being queried must be of geo_shape type. The filter will use the same + PrefixTree configuration as defined for the field. + */ + export class GeoShapeFilter implements Filter { + + /* + A Filter to find documents with a geo_shapes matching a specific shape. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): GeoShapeFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): GeoShapeFilter; + + /* + Sets the field to filter against. + */ + field(f: string): GeoShapeFilter; + + /* + Sets the indexed shape. Use this if you already have shape definitions + already indexed. + */ + indexedShape(indexedShape: string): GeoShapeFilter; + + /* + Sets the filter name. + */ + name(name: string): GeoShapeFilter; + + /* + Sets the shape relation type. A relationship between a Query Shape + and indexed Shapes that will be used to determine if a Document + should be matched or not. Valid values are: intersects, disjoint, + and within. + */ + relation(indexedShape: string): GeoShapeFilter; + + /* + Sets the shape + */ + shape(shape: string): GeoShapeFilter; + + /* + Sets the spatial strategy. + Valid values are: + + + recursive - default, recursively traverse nodes in + the spatial prefix tree. This strategy has support for + searching non-point shapes. + term - uses a large TermsFilter on each node + in the spatial prefix tree. It only supports the search of + indexed Point shapes. + + + This is an advanced setting, use with care. + */ + strategy(strategy: string): GeoShapeFilter; + + /* + Returns the filter object. + */ + toJSON(): GeoShapeFilter; + + } + + + /* + Efficient querying of documents containing shapes indexed using the + geo_shape type. + + Much like the geo_shape type, the geo_shape query uses a grid square + representation of the query shape to find those documents which have shapes + that relate to the query shape in a specified way. In order to do this, the + field being queried must be of geo_shape type. The query will use the same + PrefixTree configuration as defined for the field. + */ + export class GeoShapeQuery implements Query { + + /* + A Query to find documents with a geo_shapes matching a specific shape. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: Number): GeoShapeQuery; + + /* + Sets the field to query against. + */ + field(f: string): GeoShapeQuery; + + /* + Sets the indexed shape. Use this if you already have shape definitions + already indexed. + */ + indexedShape(indexedShape: string): GeoShapeQuery; + + /* + Sets the shape relation type. A relationship between a Query Shape + and indexed Shapes that will be used to determine if a Document + should be matched or not. Valid values are: intersects, disjoint, + and within. + */ + relation(indexedShape: string): GeoShapeQuery; + + /* + Sets the shape + */ + shape(shape: string): GeoShapeQuery; + + /* + Sets the spatial strategy. + Valid values are: + + + recursive - default, recursively traverse nodes in + the spatial prefix tree. This strategy has support for + searching non-point shapes. + term - uses a large TermsFilter on each node + in the spatial prefix tree. It only supports the search of + indexed Point shapes. + + + This is an advanced setting, use with care. + */ + strategy(strategy: string): GeoShapeQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Defines a single bucket of all the documents within the search execution + context. This context is defined by the indices and the document types you’re + searching on, but is not influenced by the search query itself. + */ + export class GlobalAggregation implements Aggregation { + + /* + Defines a single bucket of all the documents within the search context. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): GlobalAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): GlobalAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + The has_child filter results in parent documents that have child docs + matching the query being returned. + */ + export class HasChildFilter implements Filter { + + /* + Returns results that have child documents matching the filter. + */ + constructor(qry: Object, type: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): HasChildFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): HasChildFilter; + + /* + Sets the filter + */ + filter(f: Query): HasChildFilter; + + /* + Sets the filter name. + */ + name(name: string): HasChildFilter; + + /* + Sets the query + */ + query(q: Query): HasChildFilter; + + /* + Sets the scope of the filter. A scope allows to run facets on the + same scope name that will work against the child documents. + */ + scope(s: string): HasChildFilter; + + /* + Sets the cutoff value to short circuit processing. + */ + shortCircuitCutoff(cutoff: number): HasChildFilter; + + /* + Returns the filter object. + */ + toJSON(): HasChildFilter; + + /* + Sets the child document type to search against + */ + type(t: string): HasChildFilter; + + } + + + /* + The has_child query works the same as the has_child filter, + by automatically wrapping the filter with a constant_score. Results in + parent documents that have child docs matching the query being returned. + */ + export class HasChildQuery implements Query { + + /* + Returns results that have child documents matching the query. + */ + constructor(qry: Object, type: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): HasChildQuery; + + /* + Sets the query + */ + query(q: Object): HasChildQuery; + + /* + Sets the scope of the query. A scope allows to run facets on the + same scope name that will work against the child documents. + */ + scope(s: string): HasChildQuery; + + /* + Sets the scoring method. Valid values are: + + none - the default, no scoring + max - the highest score of all matched child documents is used + sum - the sum the all the matched child documents is used + avg - the average of all matched child documents is used + */ + scoreMode(s: string): HasChildQuery; + + /* + Sets the scoring method. Valid values are: + + none - the default, no scoring + max - the highest score of all matched child documents is used + sum - the sum the all the matched child documents is used + avg - the average of all matched child documents is used + */ + scoreType(s: string): HasChildQuery; + + /* + Sets the cutoff value to short circuit processing. + */ + shortCircuitCutoff(cutoff: number): HasChildQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the child document type to search against + */ + type(t: string): HasChildQuery; + + } + + + /* + The has_parent results in child documents that have parent docs matching + the query being returned. + */ + export class HasParentFilter implements Filter { + + /* + Returns results that have parent documents matching the filter. + */ + constructor(qry: Object, parentType: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): HasParentFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): HasParentFilter; + + /* + Sets the filter + */ + filter(f: Object): HasParentFilter; + + /* + Sets the filter name. + */ + name(name: string): HasParentFilter; + + /* + Sets the child document type to search against + */ + parentType(t: string): HasParentFilter; + + /* + Sets the query + */ + query(q: Object): HasParentFilter; + + /* + Sets the scope of the filter. A scope allows to run facets on the + same scope name that will work against the parent documents. + */ + scope(s: string): HasParentFilter; + + /* + Returns the filter object. + */ + toJSON(): HasParentFilter; + + } + + + /* + The has_parent query works the same as the has_parent filter, by + automatically wrapping the filter with a constant_score. Results in + child documents that have parent docs matching the query being returned. + */ + export class HasParentQuery implements Query { + + /* + Returns results that have parent documents matching the query. + */ + constructor(qry: Object, parentType: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): HasParentQuery; + + /* + Sets the child document type to search against + */ + parentType(t: string): HasParentQuery; + + /* + Sets the query + */ + query(q: Object): HasParentQuery; + + /* + Sets the scope of the query. A scope allows to run facets on the + same scope name that will work against the parent documents. + */ + scope(s: string): HasParentQuery; + + /* + Sets the scoring method. Valid values are: + + none - the default, no scoring + score - the score of the parent is used in all child documents. + */ + scoreMode(s: string): HasParentQuery; + + /* + Sets the scoring method. Valid values are: + + none - the default, no scoring + score - the score of the parent is used in all child documents. + */ + scoreType(s: string): HasParentQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Allows to highlight search results on one or more fields. In order to + perform highlighting, the actual content of the field is required. If the + field in question is stored (has store set to yes in the mapping), it will + be used, otherwise, the actual _source will be loaded and the relevant + field will be extracted from it. + + If no term_vector information is provided (by setting it to + with_positions_offsets in the mapping), then the plain highlighter will be + used. If it is provided, then the fast vector highlighter will be used. + When term vectors are available, highlighting will be performed faster at + the cost of bigger index size. + + See http://www.elasticsearch.org/guide/reference/api/search/highlighting.html + */ + export class Highlight { + + /* + Allows to highlight search results on one or more fields. + */ + constructor(fields: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Set's the boundary characters. When highlighting a field that is + mapped with term vectors, boundary_chars can be configured to + define what constitutes a boundary for highlighting. It’s a single + string with each boundary character defined in it. You can apply + the option to a specific field by passing the field name in to + the oField parameter. It defaults to ".,!? \t\n". + */ + boundaryChars(charStr: string, oField: string): Highlight; + + /* + Sets the max number of characters to scan while looking for the + start of a boundary character. You can apply the option to a + specific field by passing the field name in to the + oField parameter. Default: 20 + */ + boundaryMaxScan(cnt: number, oField: string): Highlight; + + /* + Sets highlight encoder. Valid values are: + + default - the default, no encoding + html - to encode html characters if you use html tags + */ + encoder(e: string): Highlight; + + /* + Allows you to set the fields that will be highlighted. You can + specify a single field or an array of fields. All fields are + added to the current list of fields. + */ + fields(vals: string | string[]): Highlight; + + /* + Sets the fragmenter type. You can apply the option + to a specific field by passing the field name in to the + oField parameter. Valid values for order are: + + simple - breaks text up into same-size fragments with no concerns + over spotting sentence boundaries. + span - breaks text up into same-size fragments but does not split + up Spans. + */ + fragmenter(f: string, oField: string): Highlight; + + /* + Sets the size of each highlight fragment in characters. + You can apply the option to a specific field by passing the field + name in to the oField parameter. Default: 100 + */ + fragmentSize(size: number, oField: string): Highlight; + + /* + Enables highlights in documents matched by a filter. + You can apply the option to a specific field by passing the field + name in to the oField parameter. Defaults to false. + */ + highlightFilter(trueFalse: boolean, oField: string): Highlight; + + /* + Sets the number of highlight fragments. + You can apply the option to a specific field by passing the field + name in to the oField parameter. Default: 5 + */ + numberOfFragments(cnt: number, oField: string): Highlight; + + /* + Sets arbitrary options that can be passed to the highlighter + implementation in use. + */ + options(opts: string, oField: Object): Highlight; + + /* + Sets the order of highlight fragments. You can apply the option + to a specific field by passing the field name in to the + oField parameter. Valid values for order are: + + score - the score calculated by Lucene's highlighting framework. + */ + order(o: string, oField: string): Highlight; + + /* + Sets the post tags for highlighted fragments. You can apply the + tags to a specific field by passing the field name in to the + oField parameter. + */ + postTags(tags: string | string[], oField: string): Highlight; + + /* + Sets the pre tags for highlighted fragments. You can apply the + tags to a specific field by passing the field name in to the + oField parameter. + */ + preTags(tags: string | string[], oField: string): Highlight; + + /* + When enabled it will cause a field to be highlighted only if a + query matched that field. false means that terms are highlighted + on all requested fields regardless if the query matches + specifically on them. You can apply the option to a specific + field by passing the field name in to the oField + parameter. Defaults to false. + */ + requireFieldMatch(trueFalse: boolean, oField: string): Highlight; + + /* + Sets the schema to be used for the tags. Valid values are: + + styled - 10 pre tags with css class of hltN, where N is 1-10 + */ + tagsSchema(s: string): Highlight; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the highligher type. You can apply the option + to a specific field by passing the field name in to the + oField parameter. Valid values for order are: + + fast-vector-highlighter - the fast vector based highligher + highlighter - the slower plain highligher + */ + type(t: string, oField: string): Highlight; + + } + + + /* + A multi-bucket values source based aggregation that can be applied on + numeric values extracted from the documents. It dynamically builds fixed + size (a.k.a. interval) buckets over the values. + */ + export class HistogramAggregation implements Aggregation { + + /* + Aggregation that can be applied on numeric values extracted from the + documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): HistogramAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): HistogramAggregation; + + /* + Set's the range/bounds for the histogram aggregation. Useful when you + want to include buckets that might be outside the bounds of indexed + documents. + */ + extendedBounds(min: number, max: number): HistogramAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): HistogramAggregation; + + /* + Sets the format expression for the terms. Use for number or date + formatting + */ + format(f: string): HistogramAggregation; + + /* + Sets the histogram interval. Buckets are generated based on this interval + value. + */ + interval(i: number): HistogramAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): HistogramAggregation; + + /* + The script language being used. + */ + lang(language: string): HistogramAggregation; + + /* + Only return terms that match more than a configured number of hits. + */ + minDocCount(num: number): HistogramAggregation; + + /* + Sets order for the aggregated values. + */ + order(order: string, direction: string): HistogramAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): HistogramAggregation; + + /* + Allows you generate or modify the terms using a script. + */ + script(scriptCode: string): HistogramAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): HistogramAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + The histogram facet works with numeric data by building a histogram across intervals + of the field values. Each value is rounded into an interval (or placed in a + bucket), and statistics are provided per interval/bucket (count and total). + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class HistogramFacet implements Facet { + + /* + A facet which returns the N most frequent terms within a collection + or set of collections. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): HistogramFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): HistogramFacet; + + /* + Sets the field to be used to construct the this facet. + */ + field(fieldName: string): HistogramFacet; + + /* + Sets the "from", "start", or lower bounds bucket. For example if + you have a value of 1023, an interval of 100, and a from value of + 1500, it will be placed into the 1500 bucket vs. the normal bucket + of 1000. + */ + from(from: Number): HistogramFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): HistogramFacet; + + /* + Sets the bucket interval used to calculate the distribution. + */ + interval(numericInterval: Number): HistogramFacet; + + /* + Allows you to specify a different key field to be used to group intervals. + */ + keyField(fieldName: string): HistogramFacet; + + /* + Allows you modify the key field using a script. The modified value + is then used to generate the interval. + */ + keyScript(scriptCode: string): HistogramFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): HistogramFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): HistogramFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): HistogramFacet; + + /* + Sets the type of ordering that will be performed on the date + buckets. Valid values are: + + key - the default, sort by the bucket's key value + count - sort by the number of items in the bucket + total - sort by the sum/total of the items in the bucket + */ + order(o: string): HistogramFacet; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): HistogramFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): HistogramFacet; + + /* + Sets the bucket interval used to calculate the distribution based + on a time value such as "1d", "1w", etc. + */ + timeInterval(timeInterval: Number): HistogramFacet; + + /* + Sets the "to", "end", or upper bounds bucket. For example if + you have a value of 1023, an interval of 100, and a to value of + 900, it will be placed into the 900 bucket vs. the normal bucket + of 1000. + */ + to(to: Number): HistogramFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Allows you to specify a different value field to aggrerate over. + */ + valueField(fieldName: string): HistogramFacet; + + /* + Allows you modify the value field using a script. The modified value + is then used to compute the statistical data. + */ + valueScript(scriptCode: string): HistogramFacet; + + } + + + /* + Filters documents that only have the provided ids. Note, this filter + does not require the _id field to be indexed since it works using the + _uid field. + */ + export class IdsFilter implements Filter { + + /* + Matches documents with the specified id(s). + */ + constructor(ids: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): IdsFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): IdsFilter; + + /* + Sets the filter name. + */ + name(name: string): IdsFilter; + + /* + Returns the filter object. + */ + toJSON(): IdsFilter; + + /* + Sets the type as a single type or an array of types. If type is a + string, it is added to the list of existing types. If type is an + array, it is set as the types and overwrites an existing types. This + parameter is optional. + */ + type(type: string | string[]): IdsFilter; + + /* + Sets the values array or adds a new value. if val is a string, it + is added to the list of existing document ids. If val is an + array it is set as the document values and replaces any existing values. + */ + values(val: string | string[]): IdsFilter; + + } + + + /* + Filters documents that only have the provided ids. Note, this filter + does not require the _id field to be indexed since it works using the + _uid field. + */ + export class IdsQuery implements Query { + + /* + Matches documents with the specified id(s). + */ + constructor(ids: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): IdsQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the type as a single type or an array of types. If type is a + string, it is added to the list of existing types. If type is an + array, it is set as the types and overwrites an existing types. This + parameter is optional. + */ + type(type: string | string[]): IdsQuery; + + /* + Sets the values array or adds a new value. if val is a string, it + is added to the list of existing document ids. If val is an + array it is set as the document values and replaces any existing values. + */ + values(val: string | string[]): IdsQuery; + + } + + + /* + A shape which has already been indexed in another index and/or index + type. This is particularly useful for when you have a pre-defined list of + shapes which are useful to your application and you want to reference this + using a logical name (for example ‘New Zealand’) rather than having to + provide their coordinates each time. + */ + export class IndexedShape implements Geo { + + /* + Defines a shape that already exists in an index/type. + */ + constructor(type: string, id: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the document id of the indexed shape. + */ + id(id: string): IndexedShape; + + /* + Sets the index which the shape is indexed under. + Defaults to "shapes". + */ + index(idx: string): IndexedShape; + + /* + Sets the field name containing the indexed shape. + Defaults to "shape". + */ + shapeFieldName(field: string): IndexedShape; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the type which the shape is indexed under. + */ + type(t: string): IndexedShape; + + } + + + /* + The indices filter can be used when executed across multiple indices, + allowing to have a filter that executes only when executed on an index that + matches a specific list of indices, and another filter that executes when it + is executed on an index that does not match the listed indices. + */ + export class IndicesFilter implements Filter { + + /* + A configurable filter that is dependent on the index name. + */ + constructor(fltr: Object, indices: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): IndicesFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): IndicesFilter; + + /* + Sets the filter to be used when executing on one of the indicies + specified. + */ + filter(f: Object): IndicesFilter; + + /* + Sets the indicies the filter should match. When passed a string, + the index name is added to the current list of indices. When passed + an array, it overwites all current indices. + */ + indices(i: string | string[]): IndicesFilter; + + /* + Sets the filter name. + */ + name(name: string): IndicesFilter; + + /* + Sets the filter to be used on an index that does not match an index + name in the indices list. Can also be set to "none" to not match any + documents or "all" to match all documents. + */ + noMatchFilter(f: Filter | string): IndicesFilter; + + /* + Returns the filter object. + */ + toJSON(): IndicesFilter; + + } + + + /* + The indices query can be used when executed across multiple indices, + allowing to have a query that executes only when executed on an index that + matches a specific list of indices, and another query that executes when it + is executed on an index that does not match the listed indices. + */ + export class IndicesQuery implements Query { + + /* + A configurable query that is dependent on the index name. + */ + constructor(qry: Query, indices: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): IndicesQuery; + + /* + Sets the indicies the query should match. When passed a string, + the index name is added to the current list of indices. When passed + an array, it overwites all current indices. + */ + indices(i: string | string[]): IndicesQuery; + + /* + Sets the query to be used on an index that does not match an index + name in the indices list. Can also be set to "none" to not match any + documents or "all" to match all documents. + */ + noMatchQuery(q: Query | string): IndicesQuery; + + /* + Sets the query to be executed against the indices specified. + */ + query(q: Query): IndicesQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A dedicated range aggregation for IPv4 typed fields. + + Note that this aggregration includes the from value and excludes the to + value for each range. + */ + export class IPv4RangeAggregation implements Aggregation { + + /* + A dedicated range aggregation for IPv4 typed fields. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): IPv4RangeAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): IPv4RangeAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): IPv4RangeAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): IPv4RangeAggregation; + + /* + The script language being used. + */ + lang(language: string): IPv4RangeAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): IPv4RangeAggregation; + + /* + Adds a range to the list of exsiting range expressions. + */ + range(from: string, to: string, key: string): IPv4RangeAggregation; + + /* + Allows you generate or modify the terms using a script. + */ + script(scriptCode: string): IPv4RangeAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): IPv4RangeAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A limit filter limits the number of documents (per shard) to execute on. + */ + export class LimitFilter implements Filter { + + /* + Limits the number of documents to execute on. + */ + constructor(limit: number); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): LimitFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): LimitFilter; + + /* + Sets the filter name. + */ + name(name: string): LimitFilter; + + /* + Returns the filter object. + */ + toJSON(): LimitFilter; + + /* + Sets the limit value. + */ + value(val: number): LimitFilter; + + } + + + /* + This filter can be used to match on all the documents + in a given set of collections and/or types. + */ + export class MatchAllFilter implements Filter { + + /* + A filter that matches on all documents + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): MatchAllFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): MatchAllFilter; + + /* + Sets the filter name. + */ + name(name: string): MatchAllFilter; + + /* + Returns the filter object. + */ + toJSON(): MatchAllFilter; + + } + + + /* + This query can be used to match all the documents + in a given set of collections and/or types. + */ + export class MatchAllQuery implements Query { + + /* + A query that returns all documents. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): MatchAllQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A MatchQuery is a type of Query that accepts + text/numerics/dates, analyzes it, generates a query based on the + MatchQuery type. + */ + export class MatchQuery implements Query { + + /* + A Query that appects text, analyzes it, generates internal query based + on the MatchQuery type. + */ + constructor(field: string, qstr: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the analyzer name used to analyze the Query object. + */ + analyzer(analyzer: string): MatchQuery; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: Number): MatchQuery; + + /* + Sets the maximum threshold/frequency to be considered a low + frequency term in a CommonTermsQuery. + Set to a value between 0 and 1. + */ + cutoffFrequency(freq: Number): MatchQuery; + + /* + Sets the fuzziness value for the Query. + */ + fuzziness(fuzz: number): MatchQuery; + + /* + Sets fuzzy rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + fuzzyRewrite(m: string): MatchQuery; + + /* + Set to false to use classic Levenshtein edit distance in the + fuzzy query. + */ + fuzzyTranspositions(trueFalse: boolean): MatchQuery; + + /* + Enables lenient parsing of the query string. + */ + lenient(trueFalse: boolean): MatchQuery; + + /* + Sets the max expansions of a fuzzy MatchQuery. + */ + maxExpansions(e: number): MatchQuery; + + /* + Sets a percent value controlling how many "should" clauses in the + resulting Query should match. + */ + minimumShouldMatch(minMatch: number): MatchQuery; + + /* + Sets default operator of the Query. Default: or. + */ + operator(op: string): MatchQuery; + + /* + Sets the prefix length for a fuzzy prefix MatchQuery. + */ + prefixLength(l: number): MatchQuery; + + /* + Sets the query string for the Query. + */ + query(qstr: string): MatchQuery; + + /* + Sets rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): MatchQuery; + + /* + Sets the default slop for phrases. If zero, then exact phrase matches + are required. Default: 0. + */ + slop(slop: number): MatchQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the type of the MatchQuery. Valid values are + boolean, phrase, and phrase_prefix. + */ + type(type: string): MatchQuery; + + /* + Sets what happens when no terms match. Valid values are + "all" or "none". + */ + zeroTermsQuery(q: string): MatchQuery; + + } + + + /* + A single-value metrics aggregation that keeps track and returns the + maximum value among the numeric values extracted from the aggregated + documents. These values can be extracted either from specific numeric fields + in the documents, or be generated by a provided script. + */ + export class MaxAggregation implements Aggregation { + + /* + Aggregation that keeps track and returns the maximum value among the + numeric values extracted from the aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the field to operate on. + */ + field(field: string): MaxAggregation; + + /* + The script language being used. + */ + lang(language: string): MaxAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): MaxAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): MaxAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): MaxAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + export class MetricsAggregationMixin implements Aggregation { + + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the field to operate on. + */ + field(field: string): MetricsAggregationMixin; + + /* + The script language being used. + */ + lang(language: string): MetricsAggregationMixin; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): MetricsAggregationMixin; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): MetricsAggregationMixin; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): MetricsAggregationMixin; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A single-value metrics aggregation that keeps track and returns the + minimum value among numeric values extracted from the aggregated documents. + These values can be extracted either from specific numeric fields in the + documents, or be generated by a provided script. + */ + export class MinAggregation implements Aggregation { + + /* + Aggregation that keeps track and returns the minimum value among numeric + values extracted from the aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the field to operate on. + */ + field(field: string): MinAggregation; + + /* + The script language being used. + */ + lang(language: string): MinAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): MinAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): MinAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): MinAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A field data based single bucket aggregation, that creates a bucket of all + documents in the current document set context that are missing a field value + (effectively, missing a field or having the configured NULL value set). + */ + export class MissingAggregation implements Aggregation { + + /* + Defines a bucket of all documents that are missing a field value. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): MissingAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): MissingAggregation; + + /* + Sets the field to gather missing terms from. + */ + field(field: string): MissingAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + An missingFilter matches documents where the specified field contains no legitimate value. + */ + export class MissingFilter implements Filter { + + /* + Filters documents where a specific field has no value present. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): MissingFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): MissingFilter; + + /* + Checks if the field doesn't exist. + */ + existence(trueFalse: boolean): MissingFilter; + + /* + Sets the field to check for missing values. + */ + field(name: string): MissingFilter; + + /* + Sets the filter name. + */ + name(name: string): MissingFilter; + + /* + Checks if the field has null values. + */ + nullValue(trueFalse: boolean): MissingFilter; + + /* + Returns the filter object. + */ + toJSON(): MissingFilter; + + } + + + /* + The more_like_this_field query is the same as the more_like_this query, + except it runs against a single field. + */ + export class MoreLikeThisFieldQuery implements Query { + + /* + Constructs a query where each documents returned are “like” provided text + */ + constructor(field: string, likeText: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + The analyzer that will be used to analyze the text. Defaults to the + analyzer associated with the field. + */ + analyzer(analyzerName: string): MoreLikeThisFieldQuery; + + /* + Sets the boost value of the Query. + */ + boost(boost: number): MoreLikeThisFieldQuery; + + /* + Sets the boost factor to use when boosting terms. + Defaults to 1. + */ + boostTerms(boost: number): MoreLikeThisFieldQuery; + + /* + Should the Query fail when an unsupported field + is specified. Defaults to true. + */ + failOnUnsupportedField(trueFalse: boolean): MoreLikeThisFieldQuery; + + /* + The field to run the query against. + */ + field(f: string): MoreLikeThisFieldQuery; + + /* + The text to find documents like + */ + likeText(s: string): MoreLikeThisFieldQuery; + + /* + The maximum frequency in which words may still appear. Words that + appear in more than this many docs will be ignored. + Defaults to unbounded. + */ + maxDocFreq(max: number): MoreLikeThisFieldQuery; + + /* + The maximum number of query terms that will be included in any + generated query. Defaults to 25. + */ + maxQueryTerms(max: number): MoreLikeThisFieldQuery; + + /* + The maximum word length above which words will be ignored. + Defaults to unbounded (0). + */ + maxWordLen(len: number): MoreLikeThisFieldQuery; + + /* + The frequency at which words will be ignored which do not occur in + at least this many docs. Defaults to 5. + */ + minDocFreq(min: number): MoreLikeThisFieldQuery; + + /* + The frequency below which terms will be ignored in the source doc. + The default frequency is 2. + */ + minTermFreq(freq: number): MoreLikeThisFieldQuery; + + /* + The minimum word length below which words will be ignored. + Defaults to 0. + */ + minWordLen(len: number): MoreLikeThisFieldQuery; + + /* + The percentage of terms to match on (float value). + Defaults to 0.3 (30 percent). + */ + percentTermsToMatch(percent: number): MoreLikeThisFieldQuery; + + /* + An array of stop words. Any word in this set is considered + “uninteresting” and ignored. Even if your Analyzer allows stopwords, + you might want to tell the MoreLikeThis code to ignore them, as for + the purposes of document similarity it seems reasonable to assume + that “a stop word is never interesting”. + */ + stopWords(stopWords: any[]): MoreLikeThisFieldQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + More like this query find documents that are “like” provided text by + running it against one or more fields. + */ + export class MoreLikeThisQuery implements Query { + + /* + Constructs a query where each documents returned are “like” provided text + */ + constructor(fields: string | string[], likeText: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + The analyzer that will be used to analyze the text. Defaults to the + analyzer associated with the field. + */ + analyzer(analyzerName: string): MoreLikeThisQuery; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): MoreLikeThisQuery; + + /* + Sets the boost factor to use when boosting terms. + Defaults to 1. + */ + boostTerms(boost: number): MoreLikeThisQuery; + + /* + Should the Query fail when an unsupported field + is specified. Defaults to true. + */ + failOnUnsupportedField(trueFalse: boolean): MoreLikeThisQuery; + + /* + The fields to run the query against. If you call with a single field, + it is added to the existing list of fields. If called with an array + of field names, it replaces any existing values with the new array. + */ + fields(f: string | string[]): MoreLikeThisQuery; + + /* + The text to find documents like + */ + likeText(s: string): MoreLikeThisQuery; + + /* + The maximum frequency in which words may still appear. Words that + appear in more than this many docs will be ignored. + Defaults to unbounded. + */ + maxDocFreq(max: number): MoreLikeThisQuery; + + /* + The maximum number of query terms that will be included in any + generated query. Defaults to 25. + */ + maxQueryTerms(max: number): MoreLikeThisQuery; + + /* + The maximum word length above which words will be ignored. + Defaults to unbounded (0). + */ + maxWordLen(len: number): MoreLikeThisQuery; + + /* + The frequency at which words will be ignored which do not occur in + at least this many docs. Defaults to 5. + */ + minDocFreq(min: number): MoreLikeThisQuery; + + /* + The frequency below which terms will be ignored in the source doc. + The default frequency is 2. + */ + minTermFreq(freq: number): MoreLikeThisQuery; + + /* + The minimum word length below which words will be ignored. + Defaults to 0. + */ + minWordLen(len: number): MoreLikeThisQuery; + + /* + The percentage of terms to match on (float value). + Defaults to 0.3 (30 percent). + */ + percentTermsToMatch(percent: number): MoreLikeThisQuery; + + /* + An array of stop words. Any word in this set is considered + “uninteresting” and ignored. Even if your Analyzer allows stopwords, + you might want to tell the MoreLikeThis code to ignore them, as for + the purposes of document similarity it seems reasonable to assume + that “a stop word is never interesting”. + */ + stopWords(stopWords: any[]): MoreLikeThisQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A MultiMatchQuery query builds further on top of the + MatchQuery by allowing multiple fields to be specified. + The idea here is to allow to more easily build a concise match type query + over multiple fields instead of using a relatively more expressive query + by using multiple match queries within a bool query. + */ + export class MultiMatchQuery implements Query { + + /* + A Query that allow to more easily build a MatchQuery + over multiple fields + */ + constructor(fields: string | string[], qstr: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the analyzer name used to analyze the Query object. + */ + analyzer(analyzer: string): MultiMatchQuery; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): MultiMatchQuery; + + /* + Sets the maximum threshold/frequency to be considered a low + frequency term in a CommonTermsQuery. + Set to a value between 0 and 1. + */ + cutoffFrequency(freq: Number): MultiMatchQuery; + + /* + Sets the fields to search across. If passed a single value it is + added to the existing list of fields. If passed an array of + values, they overwite all existing values. + */ + fields(f: string | string[]): MultiMatchQuery; + + /* + Sets the fuzziness value for the Query. + */ + fuzziness(fuzz: number): MultiMatchQuery; + + /* + Sets fuzzy rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + fuzzyRewrite(m: string): MultiMatchQuery; + + /* + Enables lenient parsing of the query string. + */ + lenient(trueFalse: boolean): MultiMatchQuery; + + /* + Sets the max expansions of a fuzzy Query. + */ + maxExpansions(e: number): MultiMatchQuery; + + /* + Sets a percent value controlling how many "should" clauses in the + resulting Query should match. + */ + minimumShouldMatch(minMatch: number): MultiMatchQuery; + + /* + Sets default operator of the Query. Default: or. + */ + operator(op: string): MultiMatchQuery; + + /* + Sets the prefix length for a fuzzy prefix Query. + */ + prefixLength(l: number): MultiMatchQuery; + + /* + Sets the query string for the Query. + */ + query(qstr: string): MultiMatchQuery; + + /* + Sets rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): MultiMatchQuery; + + /* + Sets the default slop for phrases. If zero, then exact phrase matches + are required. Default: 0. + */ + slop(slop: number): MultiMatchQuery; + + /* + The tie breaker value. The tie breaker capability allows results + that include the same term in multiple fields to be judged better than + results that include this term in only the best of those multiple + fields, without confusing this with the better case of two different + terms in the multiple fields. Default: 0.0. + */ + tieBreaker(tieBreaker: number): MultiMatchQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the type of the MultiMatchQuery. Valid values are + boolean, phrase, and phrase_prefix or phrasePrefix. + */ + type(type: string): MultiMatchQuery; + + /* + Sets whether or not queries against multiple fields should be combined using Lucene's + + DisjunctionMaxQuery + */ + useDisMax(trueFalse: string): MultiMatchQuery; + + /* + Sets what happens when no terms match. Valid values are + "all" or "none". + */ + zeroTermsQuery(q: string): MultiMatchQuery; + + } + + + /* + A special single bucket aggregation that enables aggregating nested + documents. + */ + export class NestedAggregation implements Aggregation { + + /* + A special single bucket aggregation that enables aggregating nested + documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): NestedAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): NestedAggregation; + + /* + Sets the nested path. + */ + path(path: string): NestedAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Nested filters allow you to search against content within objects that are + embedded inside of other objects. It is similar to XPath + expressions in XML both conceptually and syntactically. + + + The filter is executed against the nested objects / docs as if they were + indexed as separate docs and resulting in the root + parent doc (or parent nested mapping). + */ + export class NestedFilter implements Filter { + + /* + Constructs a filter that is capable of executing a filter against objects + nested within a document. + */ + constructor(path: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value of the nested Query. + */ + boost(boost: number): NestedFilter; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): NestedFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): NestedFilter; + + /* + Sets the nested filter to be executed. + */ + filter(oFilter: Object): NestedFilter; + + /* + If the nested query should be "joined" with the parent document. + Defaults to false. + */ + join(trueFalse: boolean): NestedFilter; + + /* + Sets the filter name. + */ + name(name: string): NestedFilter; + + /* + Sets the root context for the nested filter. + */ + path(p: string): NestedFilter; + + /* + Sets the nested query to be executed. + */ + query(oQuery: Query): NestedFilter; + + /* + Sets the scope of the filter. A scope allows to run facets on the + same scope name that will work against the nested documents. + */ + scope(s: string): NestedFilter; + + /* + Returns the filter object. + */ + toJSON(): NestedFilter; + + } + + + /* + Nested queries allow you to search against content within objects that are + embedded inside of other objects. It is similar to XPath expressions + in XML both conceptually and syntactically. + + The query is executed against the nested objects / docs as if they were + indexed as separate docs and resulting in the rootparent doc (or parent + nested mapping). + */ + export class NestedQuery implements Query { + + /* + Constructs a query that is capable of executing a search against objects + nested within a document. + */ + constructor(path: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): NestedQuery; + + /* + Sets the nested filter to be executed. + */ + filter(oFilter: Object): NestedQuery; + + /* + Sets the root context for the nested query. + */ + path(path: string): NestedQuery; + + /* + Sets the nested query to be executed. + */ + query(oQuery: Object): NestedQuery; + + /* + Sets the scope of the query. A scope allows to run facets on the + same scope name that will work against the nested documents. + */ + scope(s: string): NestedQuery; + + /* + Sets how the inner (nested) matches affect scoring on the parent document. + */ + scoreMode(mode: string): NestedQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A container Filter that excludes the documents matched by the + contained filter. + */ + export class NotFilter implements Filter { + + /* + Container filter that excludes the matched documents of the contained filter. + */ + constructor(oFilter: Object); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): NotFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): NotFilter; + + /* + Sets the filter + */ + filter(fltr: Object): NotFilter; + + /* + Sets the filter name. + */ + name(name: string): NotFilter; + + /* + Returns the filter object. + */ + toJSON(): NotFilter; + + } + + + /* + Filters documents with fields that have values within a certain numeric + range. Similar to range filter, except that it works only with numeric + values, and the filter execution works differently. + + The numeric range filter works by loading all the relevant field values + into memory, and checking for the relevant docs if they satisfy the range + requirements. This requires more memory since the numeric range data are + loaded to memory, but can provide a significant increase in performance. + + Note, if the relevant field values have already been loaded to memory, + for example because it was used in facets or was sorted on, then this + filter should be used. + */ + export class NumericRangeFilter implements Filter { + + /* + A Filter that only accepts numeric values within a specified range. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): NumericRangeFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): NumericRangeFilter; + + /* + Returns the field name used to create this object. + */ + field(field: string): NumericRangeFilter; + + /* + Sets the endpoint for the current range. + */ + from(startPoint: Number): NumericRangeFilter; + + /* + Greater than value. Same as setting from to the value, and + include_lower to false, + */ + gt(val: any): NumericRangeFilter; + + /* + Greater than or equal to value. Same as setting from to the value, + and include_lower to true. + */ + gte(val: any): NumericRangeFilter; + + /* + Should the first from (if set) be inclusive or not. + Defaults to true + */ + includeLower(trueFalse: boolean): NumericRangeFilter; + + /* + Should the last to (if set) be inclusive or not. Defaults to true. + */ + includeUpper(trueFalse: boolean): NumericRangeFilter; + + /* + Less than value. Same as setting to to the value, and include_upper + to false. + */ + lt(val: any): NumericRangeFilter; + + /* + Less than or equal to value. Same as setting to to the value, + and include_upper to true. + */ + lte(val: any): NumericRangeFilter; + + /* + Sets the filter name. + */ + name(name: string): NumericRangeFilter; + + /* + Sets the endpoint for the current range. + */ + to(endPoint: Number): NumericRangeFilter; + + /* + Returns the filter object. + */ + toJSON(): NumericRangeFilter; + + } + + + /* + A container filter that allows Boolean OR composition of filters. + */ + export class OrFilter implements Filter { + + /* + A container Filter that allows Boolean OR composition of filters. + */ + constructor(filters: Filter | Filter[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): OrFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): OrFilter; + + /* + Updates the filters. If passed a single Filter it is added to + the existing filters. If passed an array of Filters, they + replace all existing Filters. + */ + filters(fltr: Filter | Filter[]): OrFilter; + + /* + Sets the filter name. + */ + name(name: string): OrFilter; + + /* + Returns the filter object. + */ + toJSON(): OrFilter; + + } + + + /* + A multi-value metrics aggregation that calculates one or more percentiles + over numeric values extracted from the aggregated documents. These values can + be extracted either from specific numeric fields in the documents, or be + generated by a provided script. + */ + export class PercentilesAggregation implements Aggregation { + + /* + Aggregation that calculates one or more percentiles over numeric values + extracted from the aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Compression controls memory usage and approximation error. The compression + value limits the maximum number of nodes to 100 * compression. By + increasing the compression value, you can increase the accuracy of your + percentiles at the cost of more memory. Larger compression values also make + the algorithm slower since the underlying tree data structure grows in + size, resulting in more expensive operations. The default compression + value is 100. + */ + compression(c: number): PercentilesAggregation; + + /* + Sets the field to operate on. + */ + field(field: string): PercentilesAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): PercentilesAggregation; + + /* + The script language being used. + */ + lang(language: string): PercentilesAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): PercentilesAggregation; + + /* + Add a single percentile to the current list of percentiles. + */ + percent(percentile: number): PercentilesAggregation; + + /* + Sets the percentile bucket array. Overwrites all existing values. + */ + percents(percents: number[]): PercentilesAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): PercentilesAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): PercentilesAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + PhraseSuggester extends the PhraseSuggester and suggests + entire corrected phrases instead of individual tokens. The individual + phrase suggestions are weighted based on ngram-langugage models. In practice + it will be able to make better decision about which tokens to pick based on + co-occurence and frequencies. + */ + export class PhraseSuggester implements Suggest { + + /* + A suggester that suggests entire corrected phrases. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets analyzer used to analyze the suggest text. + */ + analyzer(analyzer: string): PhraseSuggester; + + /* + Sets the confidence level defines a factor applied to the input + phrases score which is used as a threshold for other suggest + candidates. Only candidates that score higher than the threshold + will be included in the result. + */ + confidence(c: number): PhraseSuggester; + + /* + Adds a direct generator. If passed a single Generator + it is added to the list of existing generators. If passed an + array of Generators, they replace all existing generators. + */ + directGenerator(oGenerator: Generator | Generator[]): PhraseSuggester; + + /* + Sets the field used to generate suggestions from. + */ + field(field: string): PhraseSuggester; + + /* + Forces the use of unigrams. + */ + forceUnigrams(trueFalse: boolean): PhraseSuggester; + + /* + Sets the max size of the n-grams (shingles) in the field. If + the field doesn't contain n-grams (shingles) this should be + omitted or set to 1. + */ + gramSize(s: number): PhraseSuggester; + + /* + Enables highlighting of suggestions + */ + highlight(preTag: string, postTag: string): PhraseSuggester; + + /* + A smoothing model that uses an additive smoothing model where a + constant (typically 1.0 or smaller) is added to all counts to + balance weights, The default alpha is 0.5. + */ + laplaceSmoothing(alpha: number): PhraseSuggester; + + /* + A smoothing model that takes the weighted mean of the unigrams, + bigrams and trigrams based on user supplied weights (lambdas). The + sum of tl, bl, and ul must equal 1. + */ + linearSmoothing(tl: number, bl: number, ul: number): PhraseSuggester; + + /* + Sets the maximum percentage of the terms that at most + considered to be misspellings in order to form a correction. + */ + maxErrors(c: number): PhraseSuggester; + + /* + Sets the likelihood of a term being a misspelled even if the + term exists in the dictionary. The default it 0.95 corresponding + to 5% or the real words are misspelled. + */ + realWordErrorLikelihood(l: number): PhraseSuggester; + + /* + Sets the separator that is used to separate terms in the bigram + field. If not set the whitespce character is used as a + separator. + */ + separator(sep: string): PhraseSuggester; + + /* + Sets the maximum number of suggestions to be retrieved from + each individual shard. + */ + shardSize(s: number): PhraseSuggester; + + /* + Sets the number of suggestions returned for each token. + */ + size(s: number): PhraseSuggester; + + /* + A simple backoff model that backs off to lower order n-gram + models if the higher order count is 0 and discounts the lower + order n-gram model by a constant factor. The default discount is + 0.4. + */ + stupidBackoffSmoothing(discount: number): PhraseSuggester; + + /* + Sets the text to get suggestions for. If not set, the global + suggestion text will be used. + */ + text(txt: string): PhraseSuggester; + + /* + Retrieves the internal suggest object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the token limit. + */ + tokenLimit(l: number): PhraseSuggester; + + } + + + /* + Filters documents that have fields containing terms with a specified prefix (not analyzed). Similar + to phrase query, except that it acts as a filter. Can be placed within queries that accept a filter. + */ + export class PrefixFilter implements Filter { + + /* + Filters documents that have fields containing terms with a specified prefix. + */ + constructor(fieldName: string, prefix: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): PrefixFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): PrefixFilter; + + /* + Returns the field name used to create this object. + */ + field(field: string): PrefixFilter; + + /* + Sets the filter name. + */ + name(name: string): PrefixFilter; + + /* + Sets the prefix to search for. + */ + prefix(value: string): PrefixFilter; + + /* + Returns the filter object. + */ + toJSON(): PrefixFilter; + + } + + + /* + Matches documents that have fields containing terms with a specified + prefix (not analyzed). The prefix query maps to Lucene PrefixQuery. + */ + export class PrefixQuery implements Query { + + /* + Matches documents containing the specified un-analyzed prefix. + */ + constructor(field: string, value: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value of the Query. + */ + boost(boost: number): PrefixQuery; + + /* + The field to run the query against. + */ + field(f: string): PrefixQuery; + + /* + Sets rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): PrefixQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + The prefix value. + */ + value(p: string): PrefixQuery; + + } + + + /* + The QueryFacet facet allows you to specify any valid Query and + have the number of matching hits returned as the value. + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class QueryFacet implements Facet { + + /* + A facet that return a count of the hits matching the given query. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): QueryFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): QueryFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): QueryFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): QueryFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): QueryFacet; + + /* + Sets the query to be used for this facet. + */ + query(oQuery: Object): QueryFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): QueryFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Wraps any query to be used as a filter. Can be placed within queries + that accept a filter. + + The result of the filter is not cached by default. Set the cache + parameter to true to cache the result of the filter. This is handy when the + same query is used on several (many) other queries. + + Note, the process of caching the first execution is higher when not + caching (since it needs to satisfy different queries). + */ + export class QueryFilter implements Filter { + + /* + Filters documents matching the wrapped query. + */ + constructor(qry: Object); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): QueryFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): QueryFilter; + + /* + Sets the filter name. + */ + name(name: string): QueryFilter; + + /* + Sets the query + */ + query(q: Object): QueryFilter; + + /* + Returns the filter object. + */ + toJSON(): QueryFilter; + + } + + export class QueryMixin { + + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): QueryMixin; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A query that is parsed using Lucene's default query parser. Although Lucene provides the + ability to create your own queries through its API, it also provides a rich query language + through the Query Parser, a lexer which interprets a string into a Lucene Query. + + See the Lucene Query Parser Syntax + for more information. + */ + export class QueryStringQuery implements Query { + + /* + A query that is parsed using Lucene's default query parser. + */ + constructor(qstr: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets whether or not wildcard characters (* and ?) are allowed as the + first character of the Query. Default: true. + */ + allowLeadingWildcard(trueFalse: boolean): QueryStringQuery; + + /* + Sets the analyzer name used to analyze the Query object. + */ + analyzer(analyzer: string): QueryStringQuery; + + /* + Sets whether or not we should attempt to analyzed wilcard terms in the + Query. By default, wildcard terms are not analyzed. + Analysis of wildcard characters is not perfect. Default: false. + */ + analyzeWildcard(trueFalse: boolean): QueryStringQuery; + + /* + Sets whether or not we should auto generate phrase queries *if* the + analyzer returns more than one term. Default: false. + */ + autoGeneratePhraseQueries(trueFalse: boolean): QueryStringQuery; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): QueryStringQuery; + + /* + Sets the default field/property this query should execute against. + */ + defaultField(fieldName: string): QueryStringQuery; + + /* + Set the default Boolean operator. This operator is used to join individual query + terms when no operator is explicity used in the query string (i.e., this AND that). + Defaults to OR. + */ + defaultOperator(op: string): QueryStringQuery; + + /* + Sets whether or not position increments will be used in the + Query. Default: true. + */ + enablePositionIncrements(trueFalse: boolean): QueryStringQuery; + + /* + If they query string should be escaped or not. + */ + escape(trueFalse: boolean): QueryStringQuery; + + /* + A set of fields/properties this query should execute against. + Pass a single value to add to the existing list of fields and + pass an array to overwrite all existing fields. For each field, + you can apply a field specific boost by appending a ^boost to the + field name. For example, title^10, to give the title field a + boost of 10. + */ + fields(fieldNames: any[]): QueryStringQuery; + + /* + Sets the max number of term expansions for fuzzy queries. + */ + fuzzyMaxExpansions(max: number): QueryStringQuery; + + /* + Set the minimum similarity for fuzzy queries. Default: 0.5. + */ + fuzzyMinSim(minSim: number): QueryStringQuery; + + /* + Sets the prefix length for fuzzy queries. Default: 0. + */ + fuzzyPrefixLength(fuzzLen: number): QueryStringQuery; + + /* + Sets fuzzy rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + fuzzyRewrite(m: string): QueryStringQuery; + + /* + Enables lenient parsing of the query string. + */ + lenient(trueFalse: boolean): QueryStringQuery; + + /* + Sets whether or not terms from wildcard, prefix, fuzzy, and + range queries should automatically be lowercased in the Query + since they are not analyzed. Default: true. + */ + lowercaseExpandedTerms(trueFalse: boolean): QueryStringQuery; + + /* + Sets a percent value controlling how many "should" clauses in the + resulting Query should match. + */ + minimumShouldMatch(minMatch: number): QueryStringQuery; + + /* + Sets the default slop for phrases. If zero, then exact phrase matches + are required. Default: 0. + */ + phraseSlop(slop: number): QueryStringQuery; + + /* + Sets the query string on this Query object. + */ + query(qstr: string): QueryStringQuery; + + /* + Sets the quote analyzer name used to analyze the query + when in quoted text. + */ + quoteAnalyzer(analyzer: string): QueryStringQuery; + + /* + Sets the suffix to automatically add to the field name when + performing a quoted search. + */ + quoteFieldSuffix(s: string): QueryStringQuery; + + /* + Sets rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): QueryStringQuery; + + /* + Sets the tie breaker value for a Query using + DisMax. The tie breaker capability allows results + that include the same term in multiple fields to be judged better than + results that include this term in only the best of those multiple + fields, without confusing this with the better case of two different + terms in the multiple fields. Default: 0.0. + */ + tieBreaker(tieBreaker: number): QueryStringQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets whether or not queries against multiple fields should be combined using Lucene's + + DisjunctionMaxQuery + */ + useDisMax(trueFalse: string): QueryStringQuery; + + } + + + /* + The random_score generates scores via a pseudo random number algorithm + that is initialized with a seed. + */ + export class RandomScoreFunction implements ScoreFunction { + + /* + Randomly score documents. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Adds a filter whose matching documents will have the score function applied. + */ + filter(oFilter: Filter): RandomScoreFunction; + + /* + Sets random seed value. + */ + seed(s: number): RandomScoreFunction; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A multi-bucket value source based aggregation that enables the user to + define a set of ranges - each representing a bucket. During the aggregation + process, the values extracted from each document will be checked against each + bucket range and "bucket" the relevant/matching document. + + Note that this aggregration includes the from value and excludes the to + value for each range. + */ + export class RangeAggregation implements Aggregation { + + /* + Aggregation that enables the user to define a set of ranges that each + represent a bucket. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): RangeAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): RangeAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): RangeAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): RangeAggregation; + + /* + The script language being used. + */ + lang(language: string): RangeAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): RangeAggregation; + + /* + Adds a range to the list of exsiting range expressions. + */ + range(from: string, to: string, key: string): RangeAggregation; + + /* + Allows you generate or modify the terms using a script. + */ + script(scriptCode: string): RangeAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): RangeAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A RangeFacet allows you to specify a set of ranges and get both the number of docs (count) that + fall within each range, and aggregated data based on the field, or another specified field. + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class RangeFacet implements Facet { + + /* + A facet which provides information over a range of numeric intervals. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Adds a new bounded range. + */ + addRange(from: Number, to: Number): RangeFacet; + + /* + Adds a new unbounded lower limit. + */ + addUnboundedFrom(from: Number): RangeFacet; + + /* + Adds a new unbounded upper limit. + */ + addUnboundedTo(to: Number): RangeFacet; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): RangeFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): RangeFacet; + + /* + Sets the document field to be used for the facet. + */ + field(fieldName: string): RangeFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): RangeFacet; + + /* + Allows you to specify an alternate key field to be used to compute the interval. + */ + keyField(fieldName: string): RangeFacet; + + /* + Allows you modify the key field using a script. The modified value + is then used to generate the interval. + */ + keyScript(scriptCode: string): RangeFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): RangeFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): RangeFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): RangeFacet; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): RangeFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): RangeFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Allows you to specify an alternate value field to be used to compute statistical information. + */ + valueField(fieldName: string): RangeFacet; + + /* + Allows you modify the value field using a script. The modified value + is then used to compute the statistical data. + */ + valueScript(scriptCode: string): RangeFacet; + + } + + + /* + Matches documents with fields that have terms within a certain range. + */ + export class RangeFilter implements Filter { + + /* + Filters documents with fields that have terms within a certain range. + */ + constructor(field: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): RangeFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): RangeFilter; + + /* + The field to run the filter against. + */ + field(f: string): RangeFilter; + + /* + The lower bound. Defaults to start from the first. + */ + from(f: any): RangeFilter; + + /* + Greater than value. Same as setting from to the value, and + include_lower to false, + */ + gt(val: any): RangeFilter; + + /* + Greater than or equal to value. Same as setting from to the value, + and include_lower to true. + */ + gte(val: any): RangeFilter; + + /* + Should the first from (if set) be inclusive or not. + Defaults to true + */ + includeLower(trueFalse: boolean): RangeFilter; + + /* + Should the last to (if set) be inclusive or not. Defaults to true. + */ + includeUpper(trueFalse: boolean): RangeFilter; + + /* + Less than value. Same as setting to to the value, and include_upper + to false. + */ + lt(val: any): RangeFilter; + + /* + Less than or equal to value. Same as setting to to the value, + and include_upper to true. + */ + lte(val: any): RangeFilter; + + /* + Sets the filter name. + */ + name(name: string): RangeFilter; + + /* + The upper bound. Defaults to unbounded. + */ + to(t: any): RangeFilter; + + /* + Returns the filter object. + */ + toJSON(): RangeFilter; + + } + + + /* + Matches documents with fields that have terms within a certain range. + The type of the Lucene query depends on the field type, for string fields, + the TermRangeQuery, while for number/date fields, the query is a + NumericRangeQuery. + */ + export class RangeQuery implements Query { + + /* + Matches documents with fields that have terms within a certain range. + */ + constructor(field: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value of the Query. + */ + boost(boost: number): RangeQuery; + + /* + The field to run the query against. + */ + field(f: string): RangeQuery; + + /* + The lower bound. Defaults to start from the first. + */ + from(f: any): RangeQuery; + + /* + Greater than value. Same as setting from to the value, and + include_lower to false, + */ + gt(val: any): RangeQuery; + + /* + Greater than or equal to value. Same as setting from to the value, + and include_lower to true. + */ + gte(val: any): RangeQuery; + + /* + Should the first from (if set) be inclusive or not. + Defaults to true + */ + includeLower(trueFalse: boolean): RangeQuery; + + /* + Should the last to (if set) be inclusive or not. Defaults to true. + */ + includeUpper(trueFalse: boolean): RangeQuery; + + /* + Less than value. Same as setting to to the value, and include_upper + to false. + */ + lt(val: any): RangeQuery; + + /* + Less than or equal to value. Same as setting to to the value, + and include_upper to true. + */ + lte(val: any): RangeQuery; + + /* + The upper bound. Defaults to unbounded. + */ + to(t: any): RangeQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Filters documents that have a field value matching a regular expression. + Based on Lucene 4.0 RegexpFilter which uses automaton to efficiently iterate + over index terms. + */ + export class RegexpFilter implements Filter { + + /* + Matches documents that have fields matching a regular expression. + */ + constructor(field: string, value: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): RegexpFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): RegexpFilter; + + /* + The field to run the filter against. + */ + field(f: string): RegexpFilter; + + /* + The regex flags to use. Valid flags are: + + INTERSECTION - Support for intersection notation + COMPLEMENT - Support for complement notation + EMPTY - Support for the empty language symbol: # + ANYSTRING - Support for the any string symbol: @ + INTERVAL - Support for numerical interval notation: + NONE - Disable support for all syntax options + ALL - Enables support for all syntax options + + Use multiple flags by separating with a "|" character. Example: + + INTERSECTION|COMPLEMENT|EMPTY + */ + flags(f: string): RegexpFilter; + + /* + The regex flags to use as a numeric value. Advanced use only, + it is probably better to stick with the flags option. + */ + flagsValue(v: string): RegexpFilter; + + /* + Sets the filter name. + */ + name(name: string): RegexpFilter; + + /* + Returns the filter object. + */ + toJSON(): RegexpFilter; + + /* + The regexp value. + */ + value(p: string): RegexpFilter; + + } + + + /* + Matches documents that have fields matching a regular expression. Based + on Lucene 4.0 RegexpQuery which uses automaton to efficiently iterate over + index terms. + */ + export class RegexpQuery implements Query { + + /* + Matches documents that have fields matching a regular expression. + */ + constructor(field: string, value: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value of the Query. + */ + boost(boost: number): RegexpQuery; + + /* + The field to run the query against. + */ + field(f: string): RegexpQuery; + + /* + The regex flags to use. Valid flags are: + + INTERSECTION - Support for intersection notation + COMPLEMENT - Support for complement notation + EMPTY - Support for the empty language symbol: # + ANYSTRING - Support for the any string symbol: @ + INTERVAL - Support for numerical interval notation: + NONE - Disable support for all syntax options + ALL - Enables support for all syntax options + + Use multiple flags by separating with a "|" character. Example: + + INTERSECTION|COMPLEMENT|EMPTY + */ + flags(f: string): RegexpQuery; + + /* + The regex flags to use as a numeric value. Advanced use only, + it is probably better to stick with the flags option. + */ + flagsValue(v: string): RegexpQuery; + + /* + Sets rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): RegexpQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + The regexp value. + */ + value(p: string): RegexpQuery; + + } + + + /* + The Request object provides methods generating an elasticsearch request body. + */ + export class Request { + + /* + Provides methods for generating request bodies. + */ + constructor(conf: Object); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add an aggregation. This method can be called multiple times + in order to set multiple nested aggregations that will be executed + at the same time as the search request. Alias for the aggregation method. + */ + agg(agg: Aggregation): Request; + + /* + Add an aggregation. This method can be called multiple times + in order to set multiple nested aggregations that will be executed + at the same time as the search request. + */ + aggregation(agg: Aggregation): Request; + + /* + Enable/Disable explanation of score for each search result. + */ + explain(trueFalse: boolean): Request; + + /* + Allows you to set the specified facet on this request object. Multiple facets can + be set, all of which will be returned when the search is executed. + */ + facet(facet: Facet): Request; + + /* + By default, searches return full documents, meaning every property or field. + This method allows you to specify which fields you want returned. + + Pass a single field name and it is appended to the current list of + fields. Pass an array of fields and it replaces all existing + fields. + */ + fields(s: string | string[]): Request; + + /* + Allows you to set a specified filter on this request object. + */ + filter(filter: Object): Request; + + /* + A search result set could be very large (think Google). Setting the + from parameter allows you to page through the result set + by making multiple request. This parameters specifies the starting + result/document number point. Combine with size() to achieve paging. + */ + from(f: any[]): Request; + + /* + Performs highlighting based on the Highlight + settings. + */ + highlight(h: Highlight): Request; + + /* + Boosts hits in the specified index by the given boost value. + */ + indexBoost(index: string, boost: number): Request; + + /* + Filters out search results will scores less than the specified minimum score. + */ + minScore(min: number): Request; + + /* + Allows you to set the specified query on this search object. This is the + query that will be used when the search is executed. + */ + query(someQuery: Query): Request; + + /* + Once a query executes, you can use rescore to run a secondary, more + expensive query to re-order the results. + */ + rescore(r: Rescore): Request; + + /* + Computes a document property dynamically based on the supplied ScriptField. + */ + scriptField(oScriptField: ScriptField): Request; + + /* + Sets the number of results/documents to be returned. This is set on a per page basis. + */ + size(s: number): Request; + + /* + Sets the sorting for the query. This accepts many input formats. + + + sort() - The current sorting values are returned. + sort(fieldName) - Adds the field to the current list of sorting values. + sort(fieldName, order) - Adds the field to the current list of + sorting with the specified order. Order must be asc or desc. + sort(ejs.Sort) - Adds the Sort value to the current list of sorting values. + sort(array) - Replaces all current sorting values with values + from the array. The array must contain only strings and Sort objects. + + + Multi-level sorting is supported so the order in which sort fields + are added to the query requests is relevant. + + It is recommended to use Sort objects when possible. + */ + sort(fieldName: string): Request; + + /* + Allows to control how the _source field is returned with every hit. + By default operations return the contents of the _source field + unless you have used the fields parameter or if the _source field + is disabled. Set the includes parameter to false to completely + disable returning the source field. + */ + source(includes: string | boolean | string[], excludes: string | string[]): Request; + + /* + Allows you to set the specified suggester on this request object. + Multiple suggesters can be set, all of which will be returned when + the search is executed. Global suggestion text can be set by + passing in a string vs. a Suggest object. + */ + suggest(s: string | Suggest): Request; + + /* + A timeout, bounding the request to be executed within the + specified time value and bail when expired. Defaults to no timeout. + + This option is valid during the following operations: + search and delete by query + */ + timeout(t: number): Request; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Enables score computation and tracking during sorting. Be default, + when sorting scores are not computed. + */ + trackScores(trueFalse: boolean): Request; + + /* + Enable/Disable returning version number for each search result. + */ + version(trueFalse: boolean): Request; + + } + + + /* + A method that allows to rescore queries with a typically more expensive. + */ + export class Rescore { + + /* + Defines an operation that rescores a query with another query. + */ + //constructor(windowSize: Number, windowSize: Query); + constructor(windowSize: Number); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the weight assigned to the original query of the rescoring. + */ + queryWeight(weight: Number): Rescore; + + /* + Sets the query used by the rescoring. + */ + rescoreQuery(someQuery: Query): Rescore; + + /* + Sets the weight assigned to the query used to rescore the original query. + */ + rescoreQueryWeight(weight: Number): Rescore; + + /* + Sets the scoring mode. Valid values are: + + total - default mode, the scores combined + multiply - the scores multiplied + min - the lowest of the scores + max - the highest score + avg - the average of the scores + */ + scoreMode(s: string): Rescore; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the window_size parameter of the rescoring. + */ + windowSize(size: Number): Rescore; + + } + + export class ScoreFunctionMixin implements ScoreFunction { + + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Adds a filter whose matching documents will have the score function applied. + */ + filter(oFilter: Filter): ScoreFunctionMixin; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + ScriptField's allow you create dynamic fields on stored documents at query + time. For example, you might have a set of document thats containsthe fields + price and quantity. At query time, you could define a computed + property that dynamically creates a new field called totalin each document + based on the calculation price * quantity. + */ + export class ScriptField { + + /* + Computes dynamic document properties based on information from other fields. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + If execeptions thrown from the script should be ignored or not. + Default: false + */ + ignoreFailure(trueFalse: boolean): ScriptField; + + /* + The script language being used. Currently supported values are + javascript and mvel. + */ + lang(language: string): ScriptField; + + /* + Allows you to set script parameters to be used during the execution of the script. + */ + params(oParams: Object): ScriptField; + + /* + Sets the script/code that will be used to perform the calculation. + */ + script(expression: string): ScriptField; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A filter allowing to define scripts as filters + */ + export class ScriptFilter implements Filter { + + /* + A filter allowing to define scripts as filters. + */ + constructor(script: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): ScriptFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): ScriptFilter; + + /* + Sets the script language. + */ + lang(lang: string): ScriptFilter; + + /* + Sets the filter name. + */ + name(name: string): ScriptFilter; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): ScriptFilter; + + /* + Sets the script. + */ + script(s: string): ScriptFilter; + + /* + Returns the filter object. + */ + toJSON(): ScriptFilter; + + } + + + /* + The script_score function allows you to wrap another query and customize + the scoring of it optionally with a computation derived from other numeric + field values in the doc using a script expression. + */ + export class ScriptScoreFunction implements ScoreFunction { + + /* + Modify a documents score using a script. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Adds a filter whose matching documents will have the score function applied. + */ + filter(oFilter: Filter): ScriptScoreFunction; + + /* + The script language being used. + */ + lang(language: string): ScriptScoreFunction; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): ScriptScoreFunction; + + /* + Set the script that will modify the score. + */ + script(scriptCode: string): ScriptScoreFunction; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A Shape object that can be used in queries and filters that + take a Shape. Shape uses the GeoJSON format. + + See http://www.geojson.org/ + */ + export class Shape implements Geo { + + /* + Defines a shape + */ + constructor(type: string, coords: any[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the coordinates for the shape definition. Note, the coordinates + are not validated in this api. Please see GeoJSON and ElasticSearch + documentation for correct coordinate definitions. + */ + coordinates(c: any[]): Shape; + + /* + Sets the radius for parsing a circle Shape. + */ + radius(r: string): Shape; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the shape type. Can be set to one of: point, linestring, polygon, + multipoint, envelope, or multipolygon. + */ + type(t: string): Shape; + + } + + + /* + An aggregation that returns interesting or unusual occurrences of terms in + a set. + */ + export class SignificantTermsAggregation implements Aggregation { + + /* + An aggregation that returns interesting or unusual occurrences of terms in + a set. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): SignificantTermsAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): SignificantTermsAggregation; + + /* + Allows you to filter out unwanted facet entries using a regular + expression. You can also optionally pass in a set of flags to apply + to the regular expression. Valid flags are: CASE_INSENSITIVE, + MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, + COMMENTS, and UNICODE_CHAR_CLASS. Separate multiple flags with a | + character. + */ + exclude(exclude: string, flags: string): SignificantTermsAggregation; + + /* + Sets the execution hint determines how the aggregation is computed. + Supported values are: map and ordinals. + */ + executionHint(h: string): SignificantTermsAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): SignificantTermsAggregation; + + /* + Sets the format expression for the terms. Use for number or date + formatting. + */ + format(f: string): SignificantTermsAggregation; + + /* + Allows you to allow only specific entries using a regular + expression. You can also optionally pass in a set of flags to apply + to the regular expression. Valid flags are: CASE_INSENSITIVE, + MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, + COMMENTS, and UNICODE_CHAR_CLASS. Separate multiple flags with a | + character. + */ + include(include: string, flags: string): SignificantTermsAggregation; + + /* + Only return terms that match more than a configured number of hits. + */ + minDocCount(num: number): SignificantTermsAggregation; + + /* + Determines how many terms the coordinating node will request from + each shard. + */ + shardSize(shardSize: number): SignificantTermsAggregation; + + /* + Sets the number of aggregation entries that will be returned. + */ + size(size: number): SignificantTermsAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A Sort object that can be used in on the Request object to specify + various types of sorting. + + See http://www.elasticsearch.org/guide/reference/api/search/sort.html + */ + export class Sort { + + /* + Defines a sort value + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the sort order to ascending (asc). Same as calling + order('asc'). + */ + asc(): Sort; + + /* + Sets the sort order to descending (desc). Same as calling + order('desc'). + */ + desc(): Sort; + + /* + How to compute the distance. Can either be arc (better precision) + or plane (faster). Defaults to arc. + + Valid during sort types: geo distance + */ + distanceType(type: string): Sort; + + /* + Set's the field to sort on + */ + field(f: string): Sort; + + /* + Enables sorting based on a distance from a GeoPoint + */ + geoDistance(point: GeoPoint): Sort; + + /* + Sets if the sort should ignore unmapped fields vs throwing an error. + + Valid during sort types: field + */ + ignoreUnmapped(trueFalse: boolean): Sort; + + /* + Sets the script language. + + Valid during sort types: script + */ + lang(lang: string): Sort; + + /* + Sets the value to use for missing fields. Valid values are: + + _last - to put documents with the field missing last + _first - to put documents with the field missing first + {String} - any string value to use as the sort value. + + Valid during sort types: field + */ + missing(m: string): Sort; + + /* + Sets the sort mode. Valid values are: + + + min - sort by lowest value + max - sort by highest value + sum - sort by the sum of all values + avg - sort by the average of all values + + + Valid during sort types: field, geo distance + */ + mode(m: string): Sort; + + /* + Allows you to set a filter that nested objects must match + in order to be considered during sorting. + + Valid during sort types: field, geo distance + */ + nestedFilter(oFilter: Object): Sort; + + /* + Sets the path of the nested object. + + Valid during sort types: field, geo distance + */ + nestedPath(path: string): Sort; + + /* + If the lat/long points should be normalized to lie within their + respective normalized ranges. + + Normalized ranges are: + lon = -180 (exclusive) to 180 (inclusive) range + lat = -90 to 90 (both inclusive) range + + Valid during sort types: geo distance + */ + normalize(trueFalse: string): Sort; + + /* + Sets the sort order. Valid values are: + + asc - for ascending order + desc - for descending order + + Valid during sort types: field, geo distance, and script + */ + order(o: string): Sort; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + + Valid during sort types: script + */ + params(p: Object): Sort; + + /* + Sets the order with a boolean value. + + true = descending sort order + false = ascending sort order + + Valid during sort types: field, geo distance, and script + */ + reverse(trueFalse: boolean): Sort; + + /* + Enables sorting based on a script. + */ + script(scriptCode: string): Sort; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the script sort type. Valid values are: + + + string - script return value is sorted as a string + number - script return value is sorted as a number + + + Valid during sort types: script + */ + type(type: string): Sort; + + /* + Sets the distance unit. Valid values are "mi" for miles or "km" + for kilometers. Defaults to "km". + + Valid during sort types: geo distance + */ + unit(unit: Number): Sort; + + } + + + /* + Matches spans near the beginning of a field. The spanFirstQuery allows you to search + for Spans that start and end within the first n positions of the document. + The span first query maps to Lucene SpanFirstQuery. + */ + export class SpanFirstQuery implements Query { + + /* + Matches spans near the beginning of a field. + */ + constructor(spanQry: Query, end: number); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): SpanFirstQuery; + + /* + Sets the maximum end position permitted in a match. + */ + end(position: Number): SpanFirstQuery; + + /* + Sets the span query to match on. + */ + match(spanQuery: Object): SpanFirstQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Wraps lucene MultiTermQueries as a SpanQuery so it can be used in the + various Span* queries. Examples of valid MultiTermQueries are + Fuzzy, NumericRange, Prefix, Regex, Range, and Wildcard. + */ + export class SpanMultiTermQuery implements Query { + + /* + Use MultiTermQueries as a SpanQuery. + */ + constructor(qry: Query); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): SpanMultiTermQuery; + + /* + Sets the span query to match on. + */ + match(mtQuery: Object): SpanMultiTermQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A spanNearQuery will look to find a number of spanQuerys within a given + distance from each other. + */ + export class SpanNearQuery implements Query { + + /* + Matches spans which are near one another. + */ + constructor(clauses: Query | Query[], slop: number); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): SpanNearQuery; + + /* + Sets the clauses used. If passed a single SpanQuery, it is added + to the existing list of clauses. If passed an array of + SpanQueries, they replace any existing clauses. + */ + clauses(clauses: Query | Query[]): SpanNearQuery; + + /* + Sets whether or not payloads are being used. A payload is an arbitrary + byte array stored at a specific position (i.e. token/term). + */ + collectPayloads(trueFalse: boolean): SpanNearQuery; + + /* + Sets whether or not matches are required to be in-order. + */ + inOrder(trueFalse: boolean): SpanNearQuery; + + /* + Sets the maximum number of intervening unmatched positions. + */ + slop(distance: Number): SpanNearQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Removes matches which overlap with another span query. + The span not query maps to Lucene SpanNotQuery. + */ + export class SpanNotQuery implements Query { + + /* + Removes matches which overlap with another span query. + */ + constructor(includeQry: Query, excludeQry: Query); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): SpanNotQuery; + + /* + Sets the span query whose matches must not overlap those returned. + */ + exclude(spanQuery: Object): SpanNotQuery; + + /* + Set the span query whose matches are filtered. + */ + include(spanQuery: Object): SpanNotQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + The spanOrQuery takes an array of SpanQuerys and will match if any of the + underlying SpanQueries match. The span or query maps to Lucene SpanOrQuery. + */ + export class SpanOrQuery implements Query { + + /* + Matches the union of its span clauses. + */ + constructor(clauses: Object); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): SpanOrQuery; + + /* + Sets the clauses used. If passed a single SpanQuery, it is added + to the existing list of clauses. If passed an array of + SpanQueries, they replace any existing clauses. + */ + clauses(clauses: Query | Query[]): SpanOrQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A spanTermQuery is the basic unit of Lucene's Span Query which allows for nested, + positional restrictions when matching documents. The spanTermQuery simply matches + spans containing a term. It's essentially a termQuery with positional information asscoaited. + */ + export class SpanTermQuery implements Query { + + /* + Matches spans containing a term + */ + constructor(field: string, value: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): SpanTermQuery; + + /* + Sets the field to query against. + */ + field(f: string): SpanTermQuery; + + /* + Sets the term. + */ + term(t: string): SpanTermQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A statistical facet allows you to compute statistical data over a numeric fields. Statistical data includes + the count, total, sum of squares, mean (average), minimum, maximum, variance, and standard deviation. + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class StatisticalFacet implements Facet { + + /* + A facet which returns statistical information about a numeric field + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): StatisticalFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): StatisticalFacet; + + /* + Sets the field to be used to construct the this facet. + */ + field(fieldName: string): StatisticalFacet; + + /* + Aggregate statistical info across a set of fields. + */ + fields(aFieldName: any[]): StatisticalFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): StatisticalFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): StatisticalFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): StatisticalFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): StatisticalFacet; + + /* + Allows you to set script parameters to be used during the execution of the script. + */ + params(oParams: Object): StatisticalFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): StatisticalFacet; + + /* + Define a script to evaluate of which the result will be used to generate + the statistical information. + */ + script(code: string): StatisticalFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A multi-value metrics aggregation that computes stats over numeric values + extracted from the aggregated documents. These values can be extracted either + from specific numeric fields in the documents, or be generated by a provided + script. + + The stats that are returned consist of: min, max, sum, count and avg. + */ + export class StatsAggregation implements Aggregation { + + /* + Aggregation that computes stats over numeric values extracted from the + aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the field to operate on. + */ + field(field: string): StatsAggregation; + + /* + The script language being used. + */ + lang(language: string): StatsAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): StatsAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): StatsAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): StatsAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + export class SuggestContextMixin { + + + /* + Sets analyzer used to analyze the suggest text. + */ + analyzer(analyzer: string): SuggestContextMixin; + + /* + Sets the field used to generate suggestions from. + */ + field(field: string): SuggestContextMixin; + + /* + Sets the maximum number of suggestions to be retrieved from + each individual shard. + */ + shardSize(s: number): SuggestContextMixin; + + /* + Sets the number of suggestions returned for each token. + */ + size(s: number): SuggestContextMixin; + + } + + export class SuggesterMixin { + + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the text to get suggestions for. If not set, the global + suggestion text will be used. + */ + text(txt: string): SuggesterMixin; + + /* + Retrieves the internal suggest object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A single-value metrics aggregation that sums up numeric values that are + extracted from the aggregated documents. These values can be extracted either + from specific numeric fields in the documents, or be generated by a + provided script. + */ + export class SumAggregation implements Aggregation { + + /* + Aggregation that sums up numeric values that are extracted from the + aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the field to operate on. + */ + field(field: string): SumAggregation; + + /* + The script language being used. + */ + lang(language: string): SumAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): SumAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): SumAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): SumAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Constructs a filter for docs matching any of the terms added to this + object. Unlike a RangeFilter this can be used for filtering on multiple + terms that are not necessarily in a sequence. + */ + export class TermFilter implements Filter { + + /* + Constructs a filter for docs matching the term added to this object. + */ + constructor(fieldName: string, term: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): TermFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): TermFilter; + + /* + Provides access to the filter fieldName used to construct the + termFilter object. + */ + field(f: string): TermFilter; + + /* + Sets the filter name. + */ + name(name: string): TermFilter; + + /* + Provides access to the filter term used to construct the + termFilter object. + */ + term(): TermFilter; + + /* + Returns the filter object. + */ + toJSON(): TermFilter; + + } + + + /* + A TermQuery can be used to return documents containing a given + keyword or term. For instance, you might want to retieve all the + documents/objects that contain the term Javascript. Term filters + often serve as the basis for more complex queries such as Boolean queries. + */ + export class TermQuery implements Query { + + /* + A Query that matches documents containing a term. This may be + combined with other terms with a BooleanQuery. + */ + constructor(field: string, term: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: Number): TermQuery; + + /* + Sets the fields to query against. + */ + field(f: string): TermQuery; + + /* + Sets the term. + */ + term(t: string): TermQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A multi-bucket value source based aggregation where buckets are dynamically + built - one per unique value. + */ + export class TermsAggregation implements Aggregation { + + /* + Defines an aggregation of unique values/terms. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): TermsAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): TermsAggregation; + + /* + Allows you to filter out unwanted facet entries using a regular + expression. You can also optionally pass in a set of flags to apply + to the regular expression. Valid flags are: CASE_INSENSITIVE, + MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, + COMMENTS, and UNICODE_CHAR_CLASS. Separate multiple flags with a | + character. + */ + exclude(exclude: string, flags: string): TermsAggregation; + + /* + Sets the execution hint determines how the aggregation is computed. + Supported values are: map and ordinals. + */ + executionHint(h: string): TermsAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): TermsAggregation; + + /* + Sets the format expression for the terms. Use for number or date + formatting + */ + format(f: string): TermsAggregation; + + /* + Allows you to allow only specific entries using a regular + expression. You can also optionally pass in a set of flags to apply + to the regular expression. Valid flags are: CASE_INSENSITIVE, + MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, + COMMENTS, and UNICODE_CHAR_CLASS. Separate multiple flags with a | + character. + */ + include(include: string, flags: string): TermsAggregation; + + /* + The script language being used. + */ + lang(language: string): TermsAggregation; + + /* + Only return terms that match more than a configured number of hits. + */ + minDocCount(num: number): TermsAggregation; + + /* + Sets order for the aggregated values. + */ + order(order: string, direction: string): TermsAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): TermsAggregation; + + /* + Allows you generate or modify the terms using a script. + */ + script(scriptCode: string): TermsAggregation; + + /* + Set to true to assume script values are unique. + */ + scriptValuesUnique(trueFalse: boolean): TermsAggregation; + + /* + Determines how many terms the coordinating node will request from + each shard. + */ + shardSize(shardSize: number): TermsAggregation; + + /* + Sets the number of aggregation entries that will be returned. + */ + size(size: number): TermsAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the type of the field value for use in scripts. Current values are: + string, double, float, long, integer, short, and byte. + */ + valueType(v: string): TermsAggregation; + + } + + + /* + A facet which returns the N most frequent terms within a collection + or set of collections. Term facets are useful for building constructs + which allow users to refine search results by filtering on terms returned + by the facet. + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + For more information on faceted navigation, see this Wikipedia article on + Faceted Classification + */ + export class TermsFacet implements Facet { + + /* + A facet which returns the N most frequent terms within a collection + or set of collections. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Allows you to return all terms, even if the frequency count is 0. This should not be + used on fields that contain a large number of unique terms because it could cause + out-of-memory errors. + */ + allTerms(trueFalse: string): TermsFacet; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): TermsFacet; + + /* + Allows you to filter out unwanted facet entries. When passed + a single term, it is appended to the list of currently excluded + terms. If passed an array, it overwrites all existing values. + */ + exclude(exclude: string | string[]): TermsFacet; + + /* + Sets the execution hint determines how the facet is computed. + Currently only supported value is "map". + */ + executionHint(h: Object): TermsFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): TermsFacet; + + /* + Sets the field to be used to construct the this facet. Set to + _index to return a facet count of hits per _index the search was + executed on. + */ + field(fieldName: string): TermsFacet; + + /* + Aggregate statistical info across a set of fields. + */ + fields(aFieldName: any[]): TermsFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): TermsFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): TermsFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): TermsFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): TermsFacet; + + /* + Sets the type of ordering that will be performed on the date + buckets. Valid values are: + + count - default, sort by the number of items in the bucket + term - sort by term value. + reverse_count - reverse sort of the number of items in the bucket + reverse_term - reverse sort of the term value. + */ + order(o: string): TermsFacet; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): TermsFacet; + + /* + Allows you to only include facet entries matching a specified regular expression. + */ + regex(exp: string): TermsFacet; + + /* + Allows you to set the regular expression flags to be used + with the regex + */ + regexFlags(flags: string): TermsFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): TermsFacet; + + /* + Allows you modify the term using a script. The modified value + is then used in the facet collection. + */ + script(scriptCode: string): TermsFacet; + + /* + Sets a script that will provide the terms for a given document. + */ + scriptField(script: string): TermsFacet; + + /* + Determines how many terms the coordinating node will request from + each shard. + */ + shardSize(shardSize: number): TermsFacet; + + /* + Sets the number of facet entries that will be returned for this facet. For instance, you + might ask for only the top 5 authors although there might be hundreds of + unique authors. + */ + size(facetSize: number): TermsFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Filters documents that have fields that match any of the provided + terms (not analyzed) + */ + export class TermsFilter implements Filter { + + /* + A Filter that matches documents containing provided terms. + */ + constructor(field: string, terms: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): TermsFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): TermsFilter; + + /* + Enable or disable caching of the lookup + */ + cacheLookup(trueFalse: boolean): TermsFilter; + + /* + Sets the way terms filter executes is by iterating over the terms + provided and finding matches docs (loading into a bitset) and + caching it. Valid values are: plain, bool, bool_nocache, and, + and_nocache, or, or_nocache. Defaults to plain. + */ + execution(e: string): TermsFilter; + + /* + Sets the fields to filter against. + */ + field(f: string): TermsFilter; + + /* + Sets the document id of the document containing the terms to use + when performing a terms lookup. + */ + id(id: string): TermsFilter; + + /* + Sets the index the document containing the terms is in when + performing a terms lookup. Defaults to the index currently + being searched. + */ + index(idx: string): TermsFilter; + + /* + Sets the filter name. + */ + name(name: string): TermsFilter; + + /* + Sets the path/field name where the terms in the source document + are located when performing a terms lookup. + */ + path(path: string): TermsFilter; + + /* + Sets the routing value for the source document when performing a + terms lookup. + */ + routing(path: string): TermsFilter; + + /* + Sets the terms. If t is a String, it is added to the existing + list of terms. If t is an array, the list of terms replaces the + existing terms. + */ + terms(t: string | string[]): TermsFilter; + + /* + Returns the filter object. + */ + toJSON(): TermsFilter; + + /* + Sets the type the document containing the terms when performing a + terms lookup. + */ + type(type: string): TermsFilter; + + } + + + /* + A query that match on any (configurable) of the provided terms. This is + a simpler syntax query for using a bool query with several term queries + in the should clauses. + */ + export class TermsQuery implements Query { + + /* + A Query that matches documents containing provided terms. + */ + constructor(field: string, terms: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): TermsQuery; + + /* + Enables or disables similarity coordinate scoring of documents + matching the Query. Default: false. + */ + disableCoord(trueFalse: string): TermsQuery; + + /* + Sets the fields to query against. + */ + field(f: string): TermsQuery; + + /* + Sets the minimum number of terms that need to match in a document + before that document is returned in the results. + */ + minimumShouldMatch(min: number): TermsQuery; + + /* + Sets the terms. If you t is a String, it is added to the existing + list of terms. If t is an array, the list of terms replaces the + existing terms. + */ + terms(t: string | string[]): TermsQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + A termsStatsFacet allows you to compute statistics over an aggregate key (term). Essentially this + facet provides the functionality of what is often refered to as a pivot table. + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class TermStatsFacet implements Facet { + + /* + A facet which computes statistical data based on an aggregate key. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Allows you to return all terms, even if the frequency count is 0. This should not be + used on fields that contain a large number of unique terms because it could cause + out-of-memory errors. + */ + allTerms(trueFalse: string): TermStatsFacet; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): TermStatsFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): TermStatsFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): TermStatsFacet; + + /* + Sets the field which will be used to pivot on (group-by). + */ + keyField(fieldName: string): TermStatsFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): TermStatsFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): TermStatsFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): TermStatsFacet; + + /* + Sets the type of ordering that will be performed on the date + buckets. Valid values are: + + count - default, sort by the number of items in the bucket + term - sort by term value. + reverse_count - reverse sort of the number of items in the bucket + reverse_term - reverse sort of the term value. + total - sorts by the total value of the bucket contents + reverse_total - reverse sort of the total value of bucket contents + min - the minimum value in the bucket + reverse_min - the reverse sort of the minimum value + max - the maximum value in the bucket + reverse_max - the reverse sort of the maximum value + mean - the mean value of the bucket contents + reverse_mean - the reverse sort of the mean value of bucket contents. + */ + order(o: string): TermStatsFacet; + + /* + Allows you to set script parameters to be used during the execution of the script. + */ + params(oParams: Object): TermStatsFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): TermStatsFacet; + + /* + Sets a script that will provide the terms for a given document. + */ + scriptField(script: string): TermStatsFacet; + + /* + Sets the number of facet entries that will be returned for this facet. For instance, you + might ask for only the top 5 aggregate keys although there might be hundreds of + unique keys. Higher settings could cause memory strain. + */ + size(facetSize: number): TermStatsFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the field for which statistical information will be generated. + */ + valueField(fieldName: string): TermStatsFacet; + + /* + Define a script to evaluate of which the result will be used to generate + the statistical information. + */ + valueScript(code: string): TermStatsFacet; + + } + + + /* + TermSuggester suggests terms based on edit distance. The provided suggest + text is analyzed before terms are suggested. The suggested terms are + provided per analyzed suggest text token. This leaves the suggest-selection + to the API consumer. For a higher level suggester, please use the + PhraseSuggester. + */ + export class TermSuggester implements Suggest { + + /* + A suggester that suggests terms based on edit distance. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the accuracy. How similar the suggested terms at least + need to be compared to the original suggest text. + */ + accuracy(a: number): TermSuggester; + + /* + Sets analyzer used to analyze the suggest text. + */ + analyzer(analyzer: string): TermSuggester; + + /* + Sets the field used to generate suggestions from. + */ + field(field: string): TermSuggester; + + /* + Sets the maximum edit distance candidate suggestions can have + in order to be considered as a suggestion. + */ + maxEdits(max: number): TermSuggester; + + /* + The factor that is used to multiply with the size in order + to inspect more candidate suggestions. + */ + maxInspections(max: number): TermSuggester; + + /* + Sets a maximum threshold in number of documents a suggest text + token can exist in order to be corrected. + */ + maxTermFreq(max: number): TermSuggester; + + /* + Sets a minimal threshold of the number of documents a suggested + term should appear in. + */ + minDocFreq(min: number): TermSuggester; + + /* + Sets the minimum length a suggest text term must have in order + to be corrected. + */ + minWordLen(len: number): TermSuggester; + + /* + Sets the maximum number of suggestions to be retrieved from + each individual shard. + */ + shardSize(s: number): TermSuggester; + + /* + Sets the number of suggestions returned for each token. + */ + size(s: number): TermSuggester; + + /* + Sets the sort mode. Valid values are: + + + score - Sort by score first, then document frequency, and then the term itself + frequency - Sort by document frequency first, then simlarity score and then the term itself + + */ + sort(s: string): TermSuggester; + + /* + Sets what string distance implementation to use for comparing + how similar suggested terms are. Valid values are: + + + internal - based on damerau_levenshtein but but highly optimized for comparing string distance for terms inside the index + damerau_levenshtein - String distance algorithm based on Damerau-Levenshtein algorithm + levenstein - String distance algorithm based on Levenstein edit distance algorithm + jarowinkler - String distance algorithm based on Jaro-Winkler algorithm + ngram - String distance algorithm based on character n-grams + + */ + stringDistance(s: string): TermSuggester; + + /* + Sets the suggest mode. Valid values are: + + + missing - Only suggest terms in the suggest text that aren't in the index + popular - Only suggest suggestions that occur in more docs then the original suggest text term + always - Suggest any matching suggestions based on terms in the suggest text + + */ + suggestMode(m: string): TermSuggester; + + /* + Sets the text to get suggestions for. If not set, the global + suggestion text will be used. + */ + text(txt: string): TermSuggester; + + /* + Retrieves the internal suggest object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + TThe top_children query runs the child query with an estimated hits size, + and out of the hit docs, aggregates it into parent docs. If there aren’t + enough parent docs matching the requested from/size search request, then it + is run again with a wider (more hits) search. + + The top_children also provide scoring capabilities, with the ability to + specify max, sum or avg as the score type. + */ + export class TopChildrenQuery implements Query { + + /* + Returns child documents matching the query aggregated into the parent docs. + */ + constructor(qry: Object, type: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): TopChildrenQuery; + + /* + Sets the factor which is the number of hits that are asked for in + the child query. Defaults to 5. + */ + factor(f: number): TopChildrenQuery; + + /* + Sets the incremental factor. The incremental factor is used when not + enough child documents are returned so the factor is multiplied by + the incremental factor to fetch more results. Defaults to 52 + */ + incrementalFactor(f: number): TopChildrenQuery; + + /* + Sets the query + */ + query(q: Object): TopChildrenQuery; + + /* + Sets the scope of the query. A scope allows to run facets on the + same scope name that will work against the child documents. + */ + scope(s: string): TopChildrenQuery; + + /* + Sets the scoring type. Valid values are max, sum, or avg. If + another value is passed it we silently ignore the value. + */ + score(s: string): TopChildrenQuery; + + /* + Sets the scoring type. Valid values are max, sum, total, or avg. + If another value is passed it we silently ignore the value. + */ + scoreMode(s: string): TopChildrenQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the child document type to search against + */ + type(t: string): TopChildrenQuery; + + } + + + /* + A Filter that filters results by a specified index type. + */ + export class TypeFilter implements Filter { + + /* + Filter results by a specified index type. + */ + constructor(type: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): TypeFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): TypeFilter; + + /* + Sets the filter name. + */ + name(name: string): TypeFilter; + + /* + Returns the filter object. + */ + toJSON(): TypeFilter; + + /* + Sets the type + */ + type(type: string): TypeFilter; + + } + + + /* + A single-value metrics aggregation that counts the number of values that + are extracted from the aggregated documents. These values can be extracted + either from specific fields in the documents, or be generated by a provided + script. Typically, this aggregator will be used in conjunction with other + single-value aggregations. + */ + export class ValueCountAggregation implements Aggregation { + + /* + Aggregation that counts the number of values that are extracted from the + aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the field to operate on. + */ + field(field: string): ValueCountAggregation; + + /* + The script language being used. + */ + lang(language: string): ValueCountAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): ValueCountAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): ValueCountAggregation; + + /* + Set to true to assume script values are unique. + */ + scriptValuesUnique(trueFalse: boolean): ValueCountAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + } + + + /* + Matches documents that have fields matching a wildcard expression + (not analyzed). Supported wildcards are *, which matches any character + sequence (including the empty one), and ?, which matches any single + character. Note this query can be slow, as it needs to iterate over many + wildcards. In order to prevent extremely slow wildcard queries, a wildcard + wildcard should not start with one of the wildcards * or ?. The wildcard query + maps to Lucene WildcardQuery. + */ + export class WildcardQuery implements Query { + + /* + A Query that matches documents containing a wildcard. This may be + combined with other wildcards with a BooleanQuery. + */ + constructor(field: string, value: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): String; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: Number): WildcardQuery; + + /* + Sets the fields to query against. + */ + field(f: string): WildcardQuery; + + /* + Sets rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): WildcardQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): String; + + /* + Sets the wildcard query value. + */ + value(v: string): WildcardQuery; + + } + +} diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index d32b2a8845..b06c11f6bc 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -23,8 +23,8 @@ declare module Elasticsearch { ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; scroll(params: ScrollParams): PromiseLike; scroll(params: ScrollParams, callback: (error: any, response: any) => void): void; - search(params: SearchParams): PromiseLike; - search(params: SearchParams, callback: (error: any, response: any) => void): void; + search(params: SearchParams): PromiseLike>; + search(params: SearchParams, callback: (error: any, response: SearchResponse) => void): void; suggest(params: SuggestParams): PromiseLike; suggest(params: SuggestParams, callback: (error: any, response: any) => void): void; update(params: UpdateDocumentParams): PromiseLike; @@ -79,6 +79,12 @@ declare module Elasticsearch { createNodeAgent?: any; } + export interface Explanation { + value: number, + description: string, + details: Explanation[] + } + export interface GenericParams { requestTimeout?: number; maxRetries?: number; @@ -219,6 +225,34 @@ declare module Elasticsearch { timeout?: Date | number; } + export interface SearchResponse { + took: number, + timed_out: boolean, + _scroll_id?: string, + _shards: { + total: number, + successful: number, + failed: number + }, + hits: { + total: number, + max_score: number, + hits: { + _index: string, + _type: string, + _id: string, + _score: number, + _source: T, + _version: number, + _explanation?: Explanation, + fields?: any, + highlight?: any, + inner_hits?: any + }[] + }, + aggregations?: any + } + export interface MSearchParams extends GenericParams { index?: string | string[] | Boolean; type?: string | string[] | Boolean; diff --git a/ember/ember-tests.ts b/ember/ember-tests.ts index 5452bbf901..5924dbd0ae 100644 --- a/ember/ember-tests.ts +++ b/ember/ember-tests.ts @@ -149,8 +149,8 @@ people2.some((person: Em.Object) => { people2.everyProperty('isHappy', true); people2.someProperty('isHappy', true); -// Examples taken from http://emberjs.com/api/classes/Ember.RSVP.Promise.html -var promise = new Ember.RSVP.Promise(function(resolve: Function, reject: Function) { +// Examples taken from http://emberjs.com/api/classes/Em.RSVP.Promise.html +var promise = new Em.RSVP.Promise(function(resolve: Function, reject: Function) { // on success resolve('ok!'); diff --git a/ember/ember.d.ts b/ember/ember.d.ts index b50fdc536e..20328feef8 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Ember.js 2.0 +// Type definitions for Ember.js 2.7 // Project: http://emberjs.com/ // Definitions by: Jed Mao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -448,7 +448,6 @@ declare namespace Ember { static metaForProperty(key: string): {}; static isClass: boolean; static isMethod: boolean; - static initializer(args?: ApplicationInitializerArguments): void; /** Call advanceReadiness after any asynchronous setup logic has completed. Each call to deferReadiness must be matched by a call to advanceReadiness @@ -530,6 +529,7 @@ declare namespace Ember { Application's router. **/ Router: Router; + registry: Registry; } /** This module implements Observer-friendly Array-like behavior. This mixin is picked up by the @@ -697,7 +697,7 @@ declare namespace Ember { constructor(toPath: string, fromPath: string); connect(obj: any): Binding; copy(): Binding; - disconnect(obj: any): Binding; + disconnect(): Binding; from(path: string): Binding; to(path: string): Binding; to(pathTuple: any[]): Binding; @@ -790,8 +790,10 @@ declare namespace Ember { constructor(parent: Container); parent: Container; children: any[]; + owner: any; + ownerInjection(): any; resolver: Function; - registry: {}; + registry: Registry; cache: {}; typeInjections: {}; injections: {}; @@ -805,7 +807,7 @@ declare namespace Ember { describe(fullName: string): string; makeToString(factory: any, fullName: string): Function; lookup(fullName: string, options?: {}): any; - lookupFactory(fullName: string): any; + lookupFactory(fullName: string, options?: {}): any; destroy(): void; reset(): void; } @@ -1014,9 +1016,19 @@ declare namespace Ember { You generally won't need to create or subclass this directly. **/ class Descriptor { } - var EMPTY_META: {}; // TODO: define interface - var ENV: {}; - var EXTEND_PROTOTYPES: boolean; + namespace ENV { + export var EXTEND_PROTOTYPES: typeof Ember.EXTEND_PROTOTYPES; + export var LOG_BINDINGS: boolean; + export var LOG_STACKTRACE_ON_DEPRECATION: boolean; + export var LOG_VERSION: boolean; + export var MODEL_FACTORY_INJECTIONS: boolean; + export var RAISE_ON_DEPRECATION: boolean; + } + namespace EXTEND_PROTOTYPES { + export var Array: boolean; + export var Function: boolean; + export var String: boolean; + } /** This is the object instance returned when you get the @each property on an array. It uses the unknownProperty handler to automatically create EachArray instances for property names. @@ -1137,7 +1149,7 @@ declare namespace Ember { var GUID_KEY: string; namespace Handlebars { function compile(string: string): Function; - function precompile(string: string): void; + function precompile(string: string, options: any): void; class Compiler { } class JavaScriptCompiler { } function registerPartial(name: string, str: any): void; @@ -1581,6 +1593,10 @@ declare namespace Ember { isEmpty(): boolean; toArray(): any[]; } + class Registry { + constructor (options: any); + static set: typeof Ember.set; + } // FYI - RSVP source comes from https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/promise.js namespace RSVP { @@ -2193,25 +2209,11 @@ declare namespace Ember { resource(name: string, options?: {}, callback?: Function): void; resource(name: string, callback: Function): void; route(name: string, options?: {}): void; + explicitIndex: boolean; + router: Router; + options: any; } - var SHIM_ES5: boolean; var STRINGS: boolean; - class SelectOption extends Component { - static detect(obj: any): boolean; - static detectInstance(obj: any): boolean; - /** - Iterate over each computed property for the class, passing its name and any - associated metadata (see metaForProperty) to the callback. - **/ - static eachComputedProperty(callback: Function, binding: {}): void; - /** - Returns the original hash that was passed to meta(). - @param key property name - **/ - static metaForProperty(key: string): {}; - static isClass: boolean; - static isMethod: boolean; - } class State extends Object implements Evented { static detect(obj: any): boolean; static detectInstance(obj: any): boolean; @@ -2294,23 +2296,28 @@ declare namespace Ember { class TargetActionSupport { triggerAction(opts: {}): boolean; } - class Test { - click(selector: string): RSVP.Promise; - fillin(selector: string, text: string): RSVP.Promise; - find(selector: string): JQuery; - findWithAssert(selector: string): JQuery; - injectTestHelpers(): void; - keyEvent(selector: string, type: string, keyCode: number): RSVP.Promise; - static oninjectHelpers(callback: Function): void; - static promise(resolver: Function): RSVP.Promise; - static registerHelper(name: string, helperMethod: Function): void; - removeTestHelpers(): void; - setupForTesting(): void; - static unregisterHelper(name: string): void; - visit(url: string): RSVP.Promise; - wait(value: any): RSVP.Promise; - static adapter: Object; - testHelpers: {}; + namespace Test { + class Adapter extends Ember.Object { + constructor (); + } + class Promise extends Ember.RSVP.Promise { + constructor (); + } + function oninjectHelpers(callback: Function): void; + function promise(resolver: Function, label: string): Ember.Test.Promise; + function unregisterHelper(name: string): void; + function registerHelper(name: string, helperMethod: Function): void; + function registerAsyncHelper(name: string, helperMethod: Function): void; + + var adapter: Object; + var QUnitAdapter: Object; + + function registerWaiter(callback: Function): void; + function registerWaiter(context: any, callback: Function): void; + function unregisterWaiter(callback: Function): void; + function unregisterWaiter(context: any, callback: Function): void; + + function resolve(result: any): Ember.Test.Promise; } class TextArea extends Component implements TextSupport { static detect(obj: any): boolean; @@ -2390,7 +2397,6 @@ declare namespace Ember { **/ var alias: typeof deprecateFunc; function aliasMethod(methodName: string): Descriptor; - var anyUnprocessedMixins: boolean; function assert(desc: string, test: boolean): void; function beginPropertyChanges(): void; function bind(obj: any, to: string, from: string): Binding; @@ -2420,8 +2426,6 @@ declare namespace Ember { oneWay(dependentKey: string): ComputedProperty; or(...args: string[]): ComputedProperty; }; - // ReSharper disable DuplicatingLocalDeclaration - var config: {}; // ReSharper restore DuplicatingLocalDeclaration function controllerFor(container: Container, controllerName: string, lookupOptions?: {}): Controller; function copy(obj: any, deep: boolean): any; @@ -2441,10 +2445,7 @@ declare namespace Ember { // ReSharper disable once DuplicatingLocalDeclaration var empty: typeof deprecateFunc; function endPropertyChanges(): void; - // ReSharper disable once DuplicatingLocalDeclaration - var exports: {}; function finishChains(obj: any): void; - function flushPendingChains(): void; function generateController(container: Container, controllerName: string, context: any): Controller; function generateGuid(obj: any, prefix?: string): string; function get(obj: any, keyName: string): any; @@ -2458,7 +2459,6 @@ declare namespace Ember { function hasListeners(context: any, name: string): boolean; function hasOwnProperty(prop: string): boolean; function immediateObserver(func: Function, ...propertyNames: any[]): Function; - var imports: {}; function inspect(obj: any): string; function instrument(name: string, payload: any, callback: Function, binding: any): void; function isArray(obj: any): boolean; @@ -2477,13 +2477,12 @@ declare namespace Ember { var lookup: {}; // TODO: define interface function makeArray(obj: any): any[]; function merge(original: any, updates: any): any; - function meta(obj: any, writable?: boolean): {}; + function meta(obj: any): {}; function mixin(obj: any, ...args: any[]): any; /** Ember.none is deprecated. Please use Ember.isNone instead. **/ var none: typeof deprecateFunc; - function normalizeTuple(target: any, path: string): any[]; function observer(...args: any[]): Function; function observersFor(obj: any, path: string): any[]; function onLoad(name: string, callback: Function): void; @@ -2560,16 +2559,19 @@ declare namespace Ember { function watchPath(obj: any, keyPath: string): void; function watchedEvents(obj: {}): any[]; function wrap(func: Function, superFunc: Function): Function; + var _ContainerProxyMixin : Mixin; + var _RegistryProxyMixin: Mixin; + function getOwner(object: any): any; + function setOwner(object: any, owner: any): void; + var testing : boolean; + var MODEL_FACTORY_INJECTIONS : boolean; + function assign(original: any, ...sources: any[]): any; } -// ReSharper disable DuplicatingLocalDeclaration declare namespace Em { - /** - Alias for jQuery. - **/ var $: typeof Ember.$; var A: typeof Ember.A; - class ActionHandlerMixin extends Ember.ActionHandlerMixin { } + class ActionHandlerMixin extends Ember.ActionHandlerMixin { } class Application extends Ember.Application { } class Array extends Ember.Array { } class ArrayProxy extends Ember.ArrayProxy { } @@ -2583,13 +2585,12 @@ declare namespace Em { class Container extends Ember.Container { } class Controller extends Ember.Controller { } class ControllerMixin extends Ember.ControllerMixin { } - class Copyable extends Ember.Copyable { } + class Copyable extends Ember.Copyable {} class CoreObject extends Ember.CoreObject { } - class DAG extends Ember.DAG { } - var DEFAULT_GETTER_FUNCTION: typeof Ember.DEFAULT_GETTER_FUNCTION; - class DefaultResolver extends Ember.DefaultResolver { } + class DAG extends Ember.DAG {} + var DEFAULT_GETTER_FUNCTION : typeof Ember.DEFAULT_GETTER_FUNCTION; + class DefaultResolver extends Ember.DefaultResolver { } class Descriptor extends Ember.Descriptor { } - var EMPTY_META: typeof Ember.EMPTY_META; var ENV: typeof Ember.ENV; var EXTEND_PROTOTYPES: typeof Ember.EXTEND_PROTOTYPES; class EachProxy extends Ember.EachProxy { } @@ -2604,7 +2605,7 @@ declare namespace Em { var compile: typeof Ember.Handlebars.compile; var precompile: typeof Ember.Handlebars.precompile; class Compiler extends Ember.Handlebars.Compiler { } - class JavaScriptCompiler extends Ember.Handlebars.JavaScriptCompiler { } + class JavaScriptCompiler extends Ember.Handlebars.JavaScriptCompiler{ } var registerPartial: typeof Ember.Handlebars.registerPartial; var K: typeof Ember.Handlebars.K; var createFrame: typeof Ember.Handlebars.createFrame; @@ -2623,7 +2624,7 @@ declare namespace Em { var LOG_BINDINGS: typeof Ember.LOG_BINDINGS; var LOG_STACKTRACE_ON_DEPRECATION: typeof Ember.LOG_STACKTRACE_ON_DEPRECATION; var LOG_VERSION: typeof Ember.LOG_VERSION; - class Location extends Ember.Location { } + class Location extends Ember.Location {} var Logger: typeof Ember.Logger; var MANDATORY_SETTER_FUNCTION: typeof Ember.MANDATORY_SETTER_FUNCTION; var META_KEY: typeof Ember.META_KEY; @@ -2631,7 +2632,7 @@ declare namespace Em { class MapWithDefault extends Ember.MapWithDefault { } class Mixin extends Ember.Mixin { } class MutableArray extends Ember.MutableArray { } - class MutableEnumerable extends Ember.MutableEnumberable { } + class MutableEnumberable extends Ember.MutableEnumberable { } var NAME_KEY: typeof Ember.NAME_KEY; class Namespace extends Ember.Namespace { } class NativeArray extends Ember.NativeArray { } @@ -2641,35 +2642,36 @@ declare namespace Em { class ObjectProxy extends Ember.ObjectProxy { } class Observable extends Ember.Observable { } class OrderedSet extends Ember.OrderedSet { } + class Registry extends Ember.Registry { } namespace RSVP { interface PromiseResolve extends Ember.RSVP.PromiseResolve { } interface PromiseReject extends Ember.RSVP.PromiseReject { } interface PromiseResolverFunction extends Ember.RSVP.PromiseResolverFunction { } class Promise extends Ember.RSVP.Promise { } } - class Route extends Ember.Route { } + class Route extends Ember.Route {} class Router extends Ember.Router { } class RouterDSL extends Ember.RouterDSL { } - var SHIM_ES5: typeof Ember.SHIM_ES5; var STRINGS: typeof Ember.STRINGS; - class SelectOption extends Ember.SelectOption { } class State extends Ember.State { } class StateManager extends Ember.StateManager { } - namespace String { - var camelize: typeof Ember.String.camelize; - var capitalize: typeof Ember.String.capitalize; - var classify: typeof Ember.String.classify; - var dasherize: typeof Ember.String.dasherize; - var decamelize: typeof Ember.String.decamelize; - var fmt: typeof Ember.String.fmt; - var htmlSafe: typeof Ember.String.htmlSafe; - var loc: typeof Ember.String.loc; - var underscore: typeof Ember.String.underscore; - var w: typeof Ember.String.w; - } + var String : typeof Ember.String; var TEMPLATES: typeof Ember.TEMPLATES; - class TargetActionSupport extends Ember.TargetActionSupport { } - class Test extends Ember.Test { } + class TargetActionSupport extends Ember.TargetActionSupport {} + namespace Test { + class Adapter extends Ember.Test.Adapter { } + class Promise extends Ember.Test.Promise { } + var oninjectHelpers: typeof Ember.Test.oninjectHelpers; + var promise: typeof Ember.Test.promise; + var unregisterHelper: typeof Ember.Test.unregisterHelper; + var registerHelper: typeof Ember.Test.registerHelper; + var registerAsyncHelper: typeof Ember.Test.registerAsyncHelper; + var adapter: typeof Ember.Test.adapter; + var QUnitAdapter: typeof Ember.Test.QUnitAdapter; + var registerWaiter: typeof Ember.Test.registerWaiter; + var unregisterWaiter: typeof Ember.Test.unregisterWaiter + var resolve: typeof Ember.Test.resolve; + } class TextArea extends Ember.TextArea { } class TextField extends Ember.TextField { } class TextSupport extends Ember.TextSupport { } @@ -2680,7 +2682,6 @@ declare namespace Em { var addObserver: typeof Ember.addObserver; var alias: typeof Ember.alias; var aliasMethod: typeof Ember.aliasMethod; - var anyUnprocessedMixins: typeof Ember.anyUnprocessedMixins; var assert: typeof Ember.assert; var beginPropertyChanges: typeof Ember.beginPropertyChanges; var bind: typeof Ember.bind; @@ -2689,20 +2690,17 @@ declare namespace Em { var changeProperties: typeof Ember.changeProperties; var compare: typeof Ember.compare; var computed: typeof Ember.computed; - var config: typeof Ember.config; var controllerFor: typeof Ember.controllerFor; var copy: typeof Ember.copy; var create: typeof Ember.create; var debug: typeof Ember.debug; var defineProperty: typeof Ember.defineProperty; var deprecate: typeof Ember.deprecate; - var deprecateFunc: typeof Ember.deprecateFunc; + var deprecateFunc: typeof Ember.deprecateFunc var destroy: typeof Ember.destroy; - var empty: typeof deprecateFunc; + var empty: typeof Ember.empty; var endPropertyChanges: typeof Ember.endPropertyChanges; - var exports: typeof Ember.exports; var finishChains: typeof Ember.finishChains; - var flushPendingChains: typeof Ember.flushPendingChains; var generateController: typeof Ember.generateController; var generateGuid: typeof Ember.generateGuid; var get: typeof Ember.get; @@ -2713,7 +2711,6 @@ declare namespace Em { var hasListeners: typeof Ember.hasListeners; var hasOwnProperty: typeof Ember.hasOwnProperty; var immediateObserver: typeof Ember.immediateObserver; - var imports: typeof Ember.imports; var inspect: typeof Ember.inspect; var instrument: typeof Ember.instrument; var isArray: typeof Ember.isArray; @@ -2734,7 +2731,6 @@ declare namespace Em { var meta: typeof Ember.meta; var mixin: typeof Ember.mixin; var none: typeof Ember.none; - var normalizeTuple: typeof Ember.normalizeTuple; var observer: typeof Ember.observer; var observersFor: typeof Ember.observersFor; var onLoad: typeof Ember.onLoad; @@ -2774,6 +2770,13 @@ declare namespace Em { var watchPath: typeof Ember.watchPath; var watchedEvents: typeof Ember.watchedEvents; var wrap: typeof Ember.wrap; + var _ContainerProxyMixin : typeof Ember._ContainerProxyMixin; + var _RegistryProxyMixin: typeof Ember._RegistryProxyMixin; + var getOwner: typeof Ember.getOwner; + var setOwner: typeof Ember.setOwner; + var testing: typeof Ember.testing; + var MODEL_FACTORY_INJECTIONS: typeof Ember.MODEL_FACTORY_INJECTIONS; + var assign: typeof Ember.assign; } /** @@ -2781,212 +2784,5 @@ declare namespace Em { */ declare module "Ember" { - - var $: typeof Ember.$; - var A: typeof Ember.A; - class ActionHandlerMixin extends Ember.ActionHandlerMixin { } - class Application extends Ember.Application { } - class Array extends Ember.Array { } - class ArrayProxy extends Ember.ArrayProxy { } - var BOOTED: typeof Ember.BOOTED; - class Binding extends Ember.Binding { } - class Button extends Ember.Button { } - class Checkbox extends Ember.Checkbox { } - class Comparable extends Ember.Comparable { } - class Component extends Ember.Component { } - class ComputedProperty extends Ember.ComputedProperty { } - class Container extends Ember.Container { } - class Controller extends Ember.Controller { } - class ControllerMixin extends Ember.ControllerMixin { } - class Copyable extends Ember.Copyable { } - class CoreObject extends Ember.CoreObject { } - class DAG extends Ember.DAG { } - var DEFAULT_GETTER_FUNCTION: typeof Ember.DEFAULT_GETTER_FUNCTION; - class DefaultResolver extends Ember.DefaultResolver { } - class Descriptor extends Ember.Descriptor { } - var EMPTY_META: typeof Ember.EMPTY_META; - var ENV: typeof Ember.ENV; - var EXTEND_PROTOTYPES: typeof Ember.EXTEND_PROTOTYPES; - class EachProxy extends Ember.EachProxy { } - class Enumerable extends Ember.Enumerable { } - var Error: typeof Ember.Error; - class EventDispatcher extends Ember.EventDispatcher { } - class Evented extends Ember.Evented { } - var FROZEN_ERROR: typeof Ember.FROZEN_ERROR; - class Freezable extends Ember.Freezable { } - var GUID_KEY: typeof Ember.GUID_KEY; - namespace Handlebars { - var compile: typeof Ember.Handlebars.compile; - var precompile: typeof Ember.Handlebars.precompile; - class Compiler extends Ember.Handlebars.Compiler { } - class JavaScriptCompiler extends Ember.Handlebars.JavaScriptCompiler { } - var registerPartial: typeof Ember.Handlebars.registerPartial; - var K: typeof Ember.Handlebars.K; - var createFrame: typeof Ember.Handlebars.createFrame; - var Exception: typeof Ember.Handlebars.Exception; - class SafeString extends Ember.Handlebars.SafeString { } - var parse: typeof Ember.Handlebars.parse; - var print: typeof Ember.Handlebars.print; - var logger: typeof Ember.Handlebars.logger; - var log: typeof Ember.Handlebars.log; - } - class HashLocation extends Ember.HashLocation { } - class HistoryLocation extends Ember.HistoryLocation { } - var IS_BINDING: typeof Ember.IS_BINDING; - class Instrumentation extends Ember.Instrumentation { } - var K: typeof Ember.K; - var LOG_BINDINGS: typeof Ember.LOG_BINDINGS; - var LOG_STACKTRACE_ON_DEPRECATION: typeof Ember.LOG_STACKTRACE_ON_DEPRECATION; - var LOG_VERSION: typeof Ember.LOG_VERSION; - class Location extends Ember.Location { } - var Logger: typeof Ember.Logger; - var MANDATORY_SETTER_FUNCTION: typeof Ember.MANDATORY_SETTER_FUNCTION; - var META_KEY: typeof Ember.META_KEY; - class Map extends Ember.Map { } - class MapWithDefault extends Ember.MapWithDefault { } - class Mixin extends Ember.Mixin { } - class MutableArray extends Ember.MutableArray { } - class MutableEnumerable extends Ember.MutableEnumberable { } - var NAME_KEY: typeof Ember.NAME_KEY; - class Namespace extends Ember.Namespace { } - class NativeArray extends Ember.NativeArray { } - class NoneLocation extends Ember.NoneLocation { } - var ORDER_DEFINITION: typeof Ember.ORDER_DEFINITION; - class Object extends Ember.Object { } - class ObjectProxy extends Ember.ObjectProxy { } - class Observable extends Ember.Observable { } - class OrderedSet extends Ember.OrderedSet { } - namespace RSVP { - interface PromiseResolve extends Ember.RSVP.PromiseResolve { } - interface PromiseReject extends Ember.RSVP.PromiseReject { } - interface PromiseResolverFunction extends Ember.RSVP.PromiseResolverFunction { } - class Promise extends Ember.RSVP.Promise { } - } - class Route extends Ember.Route { } - class Router extends Ember.Router { } - class RouterDSL extends Ember.RouterDSL { } - var SHIM_ES5: typeof Ember.SHIM_ES5; - var STRINGS: typeof Ember.STRINGS; - class SelectOption extends Ember.SelectOption { } - class State extends Ember.State { } - class StateManager extends Ember.StateManager { } - namespace String { - var camelize: typeof Ember.String.camelize; - var capitalize: typeof Ember.String.capitalize; - var classify: typeof Ember.String.classify; - var dasherize: typeof Ember.String.dasherize; - var decamelize: typeof Ember.String.decamelize; - var fmt: typeof Ember.String.fmt; - var htmlSafe: typeof Ember.String.htmlSafe; - var loc: typeof Ember.String.loc; - var underscore: typeof Ember.String.underscore; - var w: typeof Ember.String.w; - } - var TEMPLATES: typeof Ember.TEMPLATES; - class TargetActionSupport extends Ember.TargetActionSupport { } - class Test extends Ember.Test { } - class TextArea extends Ember.TextArea { } - class TextField extends Ember.TextField { } - class TextSupport extends Ember.TextSupport { } - var VERSION: typeof Ember.VERSION; - class ViewTargetActionSupport extends Ember.ViewTargetActionSupport { } - var ViewUtils: typeof Ember.ViewUtils; - var addListener: typeof Ember.addListener; - var addObserver: typeof Ember.addObserver; - var alias: typeof Ember.alias; - var aliasMethod: typeof Ember.aliasMethod; - var anyUnprocessedMixins: typeof Ember.anyUnprocessedMixins; - var assert: typeof Ember.assert; - var beginPropertyChanges: typeof Ember.beginPropertyChanges; - var bind: typeof Ember.bind; - var cacheFor: typeof Ember.cacheFor; - var canInvoke: typeof Ember.canInvoke; - var changeProperties: typeof Ember.changeProperties; - var compare: typeof Ember.compare; - var computed: typeof Ember.computed; - var config: typeof Ember.config; - var controllerFor: typeof Ember.controllerFor; - var copy: typeof Ember.copy; - var create: typeof Ember.create; - var debug: typeof Ember.debug; - var defineProperty: typeof Ember.defineProperty; - var deprecate: typeof Ember.deprecate; - var deprecateFunc: typeof Ember.deprecateFunc; - var destroy: typeof Ember.destroy; - var empty: typeof Ember.deprecateFunc; - var endPropertyChanges: typeof Ember.endPropertyChanges; - var exports: typeof Ember.exports; - var finishChains: typeof Ember.finishChains; - var flushPendingChains: typeof Ember.flushPendingChains; - var generateController: typeof Ember.generateController; - var generateGuid: typeof Ember.generateGuid; - var get: typeof Ember.get; - var getPath: typeof Ember.getPath; - var getWithDefault: typeof Ember.getWithDefault; - var guidFor: typeof Ember.guidFor; - var handleErrors: typeof Ember.handleErrors; - var hasListeners: typeof Ember.hasListeners; - var hasOwnProperty: typeof Ember.hasOwnProperty; - var immediateObserver: typeof Ember.immediateObserver; - var imports: typeof Ember.imports; - var inspect: typeof Ember.inspect; - var instrument: typeof Ember.instrument; - var isArray: typeof Ember.isArray; - var isEmpty: typeof Ember.isEmpty; - var isEqual: typeof Ember.isEqual; - var isGlobalPath: typeof Ember.isGlobalPath; - var isNamespace: typeof Ember.isNamespace; - var isNone: typeof Ember.isNone; - var isPrototypeOf: typeof Ember.isPrototypeOf; - var isWatching: typeof Ember.isWatching; - var keys: typeof Ember.keys; - var listenersDiff: typeof Ember.listenersDiff; - var listenersFor: typeof Ember.listenersFor; - var listenersUnion: typeof Ember.listenersUnion; - var lookup: typeof Ember.lookup; - var makeArray: typeof Ember.makeArray; - var merge: typeof Ember.merge; - var meta: typeof Ember.meta; - var mixin: typeof Ember.mixin; - var none: typeof Ember.none; - var normalizeTuple: typeof Ember.normalizeTuple; - var observer: typeof Ember.observer; - var observersFor: typeof Ember.observersFor; - var onLoad: typeof Ember.onLoad; - var onError: typeof Ember.onError; - var overrideChains: typeof Ember.overrideChains; - var platform: typeof Ember.platform; - var propertyDidChange: typeof Ember.propertyDidChange; - var propertyIsEnumerable: typeof Ember.propertyIsEnumerable; - var propertyWillChange: typeof Ember.propertyWillChange; - var removeChainWatcher: typeof Ember.removeChainWatcher; - var removeListener: typeof Ember.removeListener; - var removeObserver: typeof Ember.removeObserver; - var required: typeof Ember.required; - var rewatch: typeof Ember.rewatch; - var run: typeof Ember.run; - var runLoadHooks: typeof Ember.runLoadHooks; - var sendEvent: typeof Ember.sendEvent; - var set: typeof Ember.set; - var setPath: typeof Ember.setPath; - var setProperties: typeof Ember.setProperties; - var subscribe: typeof Ember.subscribe; - var toLocaleString: typeof Ember.toLocaleString; - var toString: typeof Ember.toString; - var tryCatchFinally: typeof Ember.tryCatchFinally; - var tryInvoke: typeof Ember.tryInvoke; - var trySet: typeof Ember.trySet; - var trySetPath: typeof Ember.trySetPath; - var typeOf: typeof Ember.typeOf; - var unwatch: typeof Ember.unwatch; - var unwatchKey: typeof Ember.unwatchKey; - var unwatchPath: typeof Ember.unwatchPath; - var uuid: typeof Ember.uuid; - var valueOf: typeof Ember.valueOf; - var warn: typeof Ember.warn; - var watch: typeof Ember.watch; - var watchKey: typeof Ember.watchKey; - var watchPath: typeof Ember.watchPath; - var watchedEvents: typeof Ember.watchedEvents; - var wrap: typeof Ember.wrap; + export = Ember; } diff --git a/express-brute/express-brute.d.ts b/express-brute/express-brute.d.ts index 37df68af64..c194f5b69a 100644 --- a/express-brute/express-brute.d.ts +++ b/express-brute/express-brute.d.ts @@ -49,15 +49,15 @@ declare module "express-brute" { * @interface */ interface ExpressBruteOptions { - freeRetries: number; - proxyDepth: number; - attachResetToRequest: boolean; - refreshTimeoutOnRequest: boolean; - minWait: number; - maxWait: number; - lifetime: number; - failCallback: (req: express.Request, res: express.Response, next: Function, nextValidRequestDate: any) => void; - handleStoreError: any; + freeRetries?: number; + proxyDepth?: number; + attachResetToRequest?: boolean; + refreshTimeoutOnRequest?: boolean; + minWait?: number; + maxWait?: number; + lifetime?: number; + failCallback?: (req: express.Request, res: express.Response, next: Function, nextValidRequestDate: any) => void; + handleStoreError?: any; } /** @@ -70,7 +70,7 @@ class ExpressBrute { * @constructor * @param {any} store The store. */ - constructor(store: any); + constructor(store: any, options?: ExpressBruteOptions); /** * @summary Generates middleware that will bounce requests with the same key and IP address that happen faster than the current wait time by calling failCallback. diff --git a/fast-json-patch/fast-json-patch-tests.ts b/fast-json-patch/fast-json-patch-tests.ts new file mode 100644 index 0000000000..e7ecc249ac --- /dev/null +++ b/fast-json-patch/fast-json-patch-tests.ts @@ -0,0 +1,43 @@ +/// +import * as jsonpatch from 'fast-json-patch' + +var myobj:{ + firstName:string, + contactDetails: { + phoneNumbers:string[] + } +} = { firstName:"Albert", contactDetails: { phoneNumbers: [ ] } }; +var patches = [ + {op:"replace", path:"/firstName", value:"Joachim" }, + {op:"add", path:"/lastName", value:"Wester" }, + {op:"add", path:"/contactDetails/phoneNumbers/0", value:{ number:"555-123" } } + ]; +jsonpatch.apply( myobj, patches ); + +var myobj2 = { firstName:"Joachim", lastName:"Wester", contactDetails: { phoneNumbers: [ { number:"555-123" }] } }; +var observer = jsonpatch.observe( myobj2 ); +myobj2.firstName = "Albert"; +myobj2.contactDetails.phoneNumbers[0].number = "123"; +myobj2.contactDetails.phoneNumbers.push({number:"456"}); +var patches2 = jsonpatch.generate(observer); + +var objA = {user: {firstName: "Albert", lastName: "Einstein"}}; +var objB = {user: {firstName: "Albert", lastName: "Collins"}}; +var diff = jsonpatch.compare(objA, objB); + +var obj = {user: {firstName: "Albert"}}; +var patches3 = [{op: "replace", path: "/user/firstName", value: "Albert"}, {op: "replace", path: "/user/lastName", value: "Einstein"}]; +var errors = jsonpatch.validate(patches, obj); +if (errors.length == 0) { + //there are no errors! +} +else { + for (var i=0; i < errors.length; i++) { + if (!errors[i]) { + console.log("Valid patch at index", i, patches[i]); + } + else { + console.error("Invalid patch at index", i, errors[i], patches[i]); + } + } +} diff --git a/fast-json-patch/fast-json-patch.d.ts b/fast-json-patch/fast-json-patch.d.ts new file mode 100644 index 0000000000..9a4496b00c --- /dev/null +++ b/fast-json-patch/fast-json-patch.d.ts @@ -0,0 +1,67 @@ +// Type definitions for JSON-Patch v1.0.0 +// Project: https://github.com/Starcounter-Jack/JSON-Patch/releases +// Definitions by: Francis OBrien +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace fastjsonpatch { + + + interface JsonPatch { + /** + * Applies an array of patch instructions to an object + */ + apply(object:any, patches:Patch[], validate?:boolean):boolean + + /** + * Observes changes made to an object, which can then be retieved using generate + */ + observe(object:T, callback?:()=>void):Observer + + /** + * Detach an observer from an object + */ + unobserve(object:T, observer:Observer):void + + /** + * Generate an array of patches from an observer + */ + generate(observer:Observer):Patch[] + + /** + * Create an array of patches from the differences in two objects + */ + compare(object1:any, object2:any):Patch[] + + /** + * Ensure a set of patch instructions is valid + */ + validate(patches:Patch[], tree?:any):JsonPatchError[] + } + + interface Observer { + object:T + patches:Patch[] + unobserve():void + } + + interface Patch { + op:string + path:string + value?:any + from?:string + } + + interface JsonPatchError { + name:string + message:string + index:number + operation:any + tree:any + } +} + +declare var jsonpatch: fastjsonpatch.JsonPatch; + +declare module "fast-json-patch" { + export = jsonpatch +} \ No newline at end of file diff --git a/fbsdk/fbsdk.d.ts b/fbsdk/fbsdk.d.ts index 79c710f8f7..286eb86b8e 100644 --- a/fbsdk/fbsdk.d.ts +++ b/fbsdk/fbsdk.d.ts @@ -67,11 +67,28 @@ interface PayDialogParams { test_currency?: string; } +interface FeedDialogParams { + method: string; // "feed" + app_id: string; + redirect_uri?: string; + display?: string; + from?: string; + to?: string; + link?: string; + picture?: string; + source?: string; + name: string; + caption?: string; + description?: string; + ref?: any; +} + declare type FBUIParams = ShareDialogParams | PageTabDialogParams | RequestsDialogParams | SendDialogParams - | PayDialogParams; + | PayDialogParams + | FeedDialogParams; interface FBLoginOptions{ auth_type?: string; diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index 9f79e6590f..0392702e6a 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -137,7 +137,7 @@ app.on('ready', () => { mainWindow.webContents.capturePage(image => { console.log(image.toDataURL()); }); - mainWindow.webContents.capturePage({width: 100, height: 200}, image => { + mainWindow.webContents.capturePage({x: 0, y: 0, width: 100, height: 200}, image => { console.log(image.toPNG()); }); }); @@ -284,7 +284,6 @@ app.on('ready', () => { app.commandLine.appendSwitch('remote-debugging-port', '8315'); app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'); -app.commandLine.appendSwitch('v', -1); app.commandLine.appendSwitch('vmodule', 'console=0'); // systemPreferences @@ -578,6 +577,42 @@ var template = [ focusedWindow.webContents.toggleDevTools(); } } + }, + { + type: 'separator' + }, + { + label: 'Actual Size', + accelerator: 'CmdOrCtrl+0', + click: (item, focusedWindow) => { + if (focusedWindow) { + focusedWindow.webContents.setZoomLevel(0) + } + } + }, + { + label: 'Zoom In', + accelerator: 'CmdOrCtrl+Plus', + click: (item, focusedWindow) => { + if (focusedWindow) { + const { webContents } = focusedWindow; + webContents.getZoomLevel((zoomLevel) => { + webContents.setZoomLevel(zoomLevel + 0.5) + }); + } + } + }, + { + label: 'Zoom Out', + accelerator: 'CmdOrCtrl+-', + click: (item, focusedWindow) => { + if (focusedWindow) { + const { webContents } = focusedWindow; + webContents.getZoomLevel((zoomLevel) => { + webContents.setZoomLevel(zoomLevel - 0.5) + }); + } + } } ] }, @@ -766,6 +801,8 @@ let image2 = nativeImage.createFromPath('/Users/somebody/images/icon.png'); // process // https://github.com/electron/electron/blob/master/docs/api/process.md +console.log(process.versions.electron); +console.log(process.versions.chrome); console.log(process.type); console.log(process.resourcesPath); console.log(process.mas); @@ -826,6 +863,8 @@ shell.openExternal('https://github.com', { shell.beep(); +shell.writeShortcutLink('/home/user/Desktop/shortcut.lnk', 'update', shell.readShortcutLink('/home/user/Desktop/shortcut.lnk')); + // session // https://github.com/atom/electron/blob/master/docs/api/session.md @@ -859,6 +898,7 @@ session.defaultSession.cookies.set(cookie, (error) => { session.defaultSession.on('will-download', (event, item, webContents) => { // Set the save path, making Electron not to prompt a save dialog. item.setSavePath('/tmp/save.pdf'); + console.log(item.getSavePath()); console.log(item.getMimeType()); console.log(item.getFilename()); console.log(item.getTotalBytes()); diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 217e230d9c..0961eb03cf 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.2.8 +// Type definitions for Electron v1.3.2 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -25,6 +25,23 @@ declare namespace Electron { sender: EventEmitter; } + type Point = { + x: number; + y: number; + } + + type Size = { + width: number; + height: number; + } + + type Rectangle = { + x: number; + y: number; + width: number; + height: number; + } + // https://github.com/electron/electron/blob/master/docs/api/app.md /** @@ -401,7 +418,7 @@ declare namespace Electron { * Note: This will not affect process.argv, and is mainly used by developers * to control some low-level Chromium behaviors. */ - appendSwitch(_switch: string, value?: string|number): void; + appendSwitch(_switch: string, value?: string): void; /** * Append an argument to Chromium's command line. The argument will quoted properly. * @@ -473,6 +490,13 @@ declare namespace Electron { * Note: This API is only available on macOS. */ show(): void; + /** + * @returns Whether the dock icon is visible. + * The app.dock.show() call is asynchronous so this method might not return true immediately after that call. + * + * Note: This API is only available on macOS. + */ + isVisible(): boolean; /** * Sets the application dock menu. * @@ -844,7 +868,7 @@ declare namespace Electron { * * Note: This API is available only on macOS. */ - setAspectRatio(aspectRatio: number, extraSize?: Dimension): void; + setAspectRatio(aspectRatio: number, extraSize?: Size): void; /** * Resizes and moves the window to width, height, x, y. */ @@ -1112,7 +1136,7 @@ declare namespace Electron { * * Note: This API is available only on Windows. */ - setThumbnailClip(region: Bounds): void; + setThumbnailClip(region: Rectangle): void; /** * Same as webContents.showDefinitionForSelection(). * Note: This API is available only on macOS. @@ -1360,7 +1384,7 @@ declare namespace Electron { backgroundThrottling?: boolean; } - interface BrowserWindowOptions extends Rectangle { + interface BrowserWindowOptions { /** * Window’s width in pixels. * Default: 800. @@ -1570,13 +1594,6 @@ declare namespace Electron { type BrowserWindowTypeMac = 'desktop' | 'textured'; type BrowserWindowTypeWindows = 'toolbar'; - interface Rectangle { - x?: number; - y?: number; - width?: number; - height?: number; - } - // https://github.com/electron/electron/blob/master/docs/api/clipboard.md /** @@ -1853,7 +1870,7 @@ declare namespace Electron { * The suggested size that thumbnail should be scaled. * Default: {width: 150, height: 150} */ - thumbnailSize?: Dimension; + thumbnailSize?: Size; } interface DesktopCapturerSource { @@ -2039,6 +2056,11 @@ declare namespace Electron { * routine to determine the save path (Usually prompts a save dialog). */ setSavePath(path: string): void; + /** + * @returns The save path of the download item. + * This will be either the path set via downloadItem.setSavePath(path) or the path selected from the shown save dialog. + */ + getSavePath(): string; /** * Pauses the download. */ @@ -2428,13 +2450,17 @@ declare namespace Electron { */ static createFromDataURL(dataURL: string): NativeImage; /** - * @returns Buffer Contains the image's PNG encoded data. + * @returns Buffer that contains the image's PNG encoded data. */ toPNG(): Buffer; /** - * @returns Buffer Contains the image's JPEG encoded data. + * @returns Buffer that contains the image's JPEG encoded data. */ toJPEG(quality: number): Buffer; + /** + * @returns Buffer that contains the image's raw pixel data. + */ + toBitmap(): Buffer; /** * @returns string The data URL of the image. */ @@ -2452,7 +2478,7 @@ declare namespace Electron { /** * @returns {} The size of the image. */ - getSize(): Dimension; + getSize(): Size; /** * Marks the image as template image. */ @@ -2675,10 +2701,10 @@ declare namespace Electron { * Unique identifier associated with the display. */ id: number; - bounds: Bounds; - workArea: Bounds; - size: Dimension; - workAreaSize: Dimension; + bounds: Rectangle; + workArea: Rectangle; + size: Size; + workAreaSize: Size; /** * Output device’s pixel scale factor. */ @@ -2690,23 +2716,6 @@ declare namespace Electron { touchSupport: 'available' | 'unavailable' | 'unknown'; } - type Bounds = { - x: number; - y: number; - width: number; - height: number; - } - - type Dimension = { - width: number; - height: number; - } - - type Point = { - x: number; - y: number; - } - type DisplayMetrics = 'bounds' | 'workArea' | 'scaleFactor' | 'rotation'; /** @@ -2746,7 +2755,7 @@ declare namespace Electron { /** * @returns The display that most closely intersects the provided bounds. */ - getDisplayMatching(rect: Bounds): Display; + getDisplayMatching(rect: Rectangle): Display; } // https://github.com/electron/electron/blob/master/docs/api/session.md @@ -2799,7 +2808,7 @@ declare namespace Electron { /** * Sets the proxy settings. */ - setProxy(config: string, callback: Function): void; + setProxy(config: ProxyConfig, callback: Function): void; /** * Resolves the proxy information for url. */ @@ -2882,6 +2891,21 @@ declare namespace Electron { quotas?: ('temporary' | 'persistent' | 'syncable')[]; } + interface ProxyConfig { + /** + * The URL associated with the PAC file. + */ + pacScript: string; + /** + * Rules indicating which proxies to use. + */ + proxyRules: string; + /** + * Rules indicating which URLs should bypass the proxy settings. + */ + proxyBypassRules: string; + } + interface NetworkEmulationOptions { /** * Whether to emulate network outage. @@ -3242,6 +3266,62 @@ declare namespace Electron { * Play the beep sound. */ beep(): void; + /** + * Creates or updates a shortcut link at shortcutPath. + * + * Note: This API is available only on Windows. + */ + writeShortcutLink(shortcutPath: string, options: ShortcutLinkOptions): boolean; + /** + * Creates or updates a shortcut link at shortcutPath. + * + * Note: This API is available only on Windows. + */ + writeShortcutLink(shortcutPath: string, operation: 'create' | 'update' | 'replace', options: ShortcutLinkOptions): boolean; + /** + * Resolves the shortcut link at shortcutPath. + * An exception will be thrown when any error happens. + * + * Note: This API is available only on Windows. + */ + readShortcutLink(shortcutPath: string): ShortcutLinkOptions; + } + + interface ShortcutLinkOptions { + /** + * The target to launch from this shortcut. + */ + target: string; + /** + * The working directory. + * Default: empty. + */ + cwd?: string; + /** + * The arguments to be applied to target when launching from this shortcut. + * Default: empty. + */ + args?: string; + /** + * The description of the shortcut. + * Default: empty. + */ + description?: string; + /** + * The path to the icon, can be a DLL or EXE. icon and iconIndex have to be set together. + * Default: empty, which uses the target's icon. + */ + icon?: string; + /** + * The resource ID of icon when icon is a DLL or EXE. + * Default: 0. + */ + iconIndex?: number; + /** + * The Application User Model ID. + * Default: empty. + */ + appUserModelId?: string; } // https://github.com/electron/electron/blob/master/docs/api/system-preferences.md @@ -3303,17 +3383,17 @@ declare namespace Electron { * Emitted when the tray icon is clicked. * Note: The bounds payload is only implemented on macOS and Windows. */ - on(event: 'click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this; + on(event: 'click', listener: (modifiers: Modifiers, bounds: Rectangle) => void): this; /** * Emitted when the tray icon is right clicked. * Note: This is only implemented on macOS and Windows. */ - on(event: 'right-click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this; + on(event: 'right-click', listener: (modifiers: Modifiers, bounds: Rectangle) => void): this; /** * Emitted when the tray icon is double clicked. * Note: This is only implemented on macOS and Windows. */ - on(event: 'double-click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this; + on(event: 'double-click', listener: (modifiers: Modifiers, bounds: Rectangle) => void): this; /** * Emitted when the tray balloon shows. * Note: This is only implemented on Windows. @@ -3386,10 +3466,10 @@ declare namespace Electron { */ setTitle(title: string): void; /** - * Sets whether the tray icon is highlighted when it is clicked. + * Sets when the tray's icon background becomes highlighted. * Note: This is only implemented on macOS. */ - setHighlightMode(highlight: boolean): void; + setHighlightMode(mode: 'selection' | 'always' | 'never'): void; /** * Displays a tray balloon. * Note: This is only implemented on Windows. @@ -3413,7 +3493,7 @@ declare namespace Electron { /** * @returns The bounds of this tray icon. */ - getBounds(): Bounds; + getBounds(): Rectangle; } interface Modifiers { @@ -3626,9 +3706,9 @@ declare namespace Electron { /** * Emitted when the cursor’s type changes. * If the type parameter is custom, the image parameter will hold the custom cursor image - * in a NativeImage, and the scale will hold scaling information for the image. + * in a NativeImage, and scale, size and hotspot will hold additional information about the custom cursor. */ - on(event: 'cursor-changed', listener: (event: Event, type: CursorType, image?: NativeImage, scale?: number) => void): this; + on(event: 'cursor-changed', listener: (event: Event, type: CursorType, image?: NativeImage, scale?: number, size?: Size, hotspot?: Point) => void): this; /** * Emitted when there is a new context menu that needs to be handled. */ @@ -3641,6 +3721,10 @@ declare namespace Electron { * passing empty string to callback will cancel the request. */ on(event: 'select-bluetooth-device', listener: (event: Event, deviceList: BluetoothDevice[], callback: (deviceId: string) => void) => void): this; + /** + * Emitted when a page's view is repainted. + */ + on(event: 'view-painted', listener: Function): this; on(event: string, listener: Function): this; /** * Loads the url in the window. @@ -3751,47 +3835,74 @@ declare namespace Electron { */ isAudioMuted(): boolean; /** - * Executes Edit -> Undo command in page. + * Changes the zoom factor to the specified factor. + * Zoom factor is zoom percent divided by 100, so 300% = 3.0. + */ + setZoomFactor(factor: number): void; + /** + * Sends a request to get current zoom factor. + */ + getZoomFactor(callback: (zoomFactor: number) => void): void; + /** + * Changes the zoom level to the specified level. + * The original size is 0 and each increment above or below represents + * zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number): void; + /** + * Sends a request to get current zoom level. + */ + getZoomLevel(callback: (zoomLevel: number) => void): void; + /** + * Sets the maximum and minimum zoom level. + */ + setZoomLevelLimits(minimumLevel: number, maximumLevel: number): void; + /** + * Executes the editing command undo in web page. */ undo(): void; /** - * Executes Edit -> Redo command in page. + * Executes the editing command redo in web page. */ redo(): void; /** - * Executes Edit -> Cut command in page. + * Executes the editing command cut in web page. */ cut(): void; /** - * Executes Edit -> Copy command in page. + * Executes the editing command copy in web page. */ copy(): void; /** - * Executes Edit -> Paste command in page. + * Copy the image at the given position to the clipboard. + */ + copyImageAt(x: number, y: number): void; + /** + * Executes the editing command paste in web page. */ paste(): void; /** - * Executes Edit -> Paste and Match Style in page. + * Executes the editing command pasteAndMatchStyle in web page. */ pasteAndMatchStyle(): void; /** - * Executes Edit -> Delete command in page. + * Executes the editing command delete in web page. */ delete(): void; /** - * Executes Edit -> Select All command in page. + * Executes the editing command selectAll in web page. */ selectAll(): void; /** - * Executes Edit -> Unselect command in page. + * Executes the editing command unselect in web page. */ unselect(): void; /** - * Executes Edit -> Replace command in page. + * Executes the editing command replace in web page. */ replace(text: string): void; /** - * Executes Edit -> Replace Misspelling command in page. + * Executes the editing command replaceMisspelling in web page. */ replaceMisspelling(text: string): void; /** @@ -3962,7 +4073,7 @@ declare namespace Electron { * The dirtyRect is an object with x, y, width, height properties that describes which part of the page was repainted. * If onlyDirty is set to true, frameBuffer will only contain the repainted area. onlyDirty defaults to false. */ - dirtyRect?: Bounds + dirtyRect?: Rectangle ): void } @@ -4166,7 +4277,7 @@ declare namespace Electron { * Specify page size of the generated PDF. * Default: A4. */ - pageSize?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid' | Dimension; + pageSize?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid' | Size; /** * Whether to print CSS backgrounds. * Default: false. @@ -4271,7 +4382,7 @@ declare namespace Electron { /** * Coordinates of first match region. */ - selectionArea?: Bounds; + selectionArea?: Rectangle; } interface DeviceEmulationParameters { @@ -4283,7 +4394,7 @@ declare namespace Electron { /** * Set the emulated screen size (screenPosition == mobile) */ - screenSize?: Dimension; + screenSize?: Size; /** * Position the view on the screen (screenPosition == mobile) * Default: {x: 0, y: 0} @@ -4297,7 +4408,7 @@ declare namespace Electron { /** * Set the emulated view size (empty means no override). */ - viewSize?: Dimension; + viewSize?: Size; /** * Whether emulated view should be scaled down if necessary to fit into available space * Default: false @@ -4342,7 +4453,7 @@ declare namespace Electron { wheelTicksY?: number; accelerationRatioX?: number; accelerationRatioY?: number; - hasPreciseScrollingDeltas?: number; + hasPreciseScrollingDeltas?: boolean; canScroll?: boolean; } @@ -4619,7 +4730,7 @@ declare namespace Electron { /** * Navigates to the specified offset from the "current entry". */ - goToOffset(offset: boolean): void; + goToOffset(offset: number): void; /** * @returns Whether the renderer process has crashed. */ @@ -5107,6 +5218,18 @@ interface File { // https://github.com/electron/electron/blob/master/docs/api/process.md declare namespace NodeJS { + + interface ProcessVersions { + /** + * Electron's version string. + */ + electron: string; + /** + * Chrome's version string. + */ + chrome: string; + } + interface Process { /** * Setting this to true can disable the support for asar archives in Node's built-in modules. diff --git a/gl-matrix/gl-matrix-typed-tests.ts b/gl-matrix/gl-matrix-typed-tests.ts new file mode 100644 index 0000000000..7364ec0a83 --- /dev/null +++ b/gl-matrix/gl-matrix-typed-tests.ts @@ -0,0 +1,346 @@ +/// + +// common +import {vec2, mat2, mat3, mat4, vec3, vec4, glMatrix, mat2d, quat} from "./gl-matrix-typed"; +var result: number = glMatrix.toRadian(180); + +var outVal: number; +var outBool: boolean; +var outStr: string; + +let vecArray = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + +let vec2A = vec2.fromValues(1, 2); +let vec2B = vec2.fromValues(3, 4); +let vec3A = vec3.fromValues(1, 2, 3); +let vec3B = vec3.fromValues(3, 4, 5); +let vec4A = vec4.fromValues(1, 2, 3, 4); +let vec4B = vec4.fromValues(3, 4, 5, 6); +let mat2A = mat2.fromValues(1, 2, 3, 4); +let mat2B = mat2.fromValues(1, 2, 3, 4); +let mat2dA = mat2d.fromValues(1, 2, 3, 4, 5, 6); +let mat2dB = mat2d.fromValues(1, 2, 3, 4, 5, 6); +let mat3A = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +let mat3B = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +let mat4A = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +let mat4B = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +let quatA = quat.fromValues(1, 2, 3, 4); +let quatB = quat.fromValues(5, 6, 7, 8); + +let outVec2 = vec2.create(); +let outVec3 = vec3.create(); +let outVec4 = vec4.create(); +let outMat2 = mat2.create(); +let outMat2d = mat2d.create(); +let outMat3 = mat3.create(); +let outMat4 = mat4.create(); +let outQuat = quat.create(); + +// vec2 +outVec2 = vec2.create(); +outVec2 = vec2.clone(vec2A); +outVec2 = vec2.fromValues(1, 2); +outVec2 = vec2.copy(outVec2, vec2A); +outVec2 = vec2.set(outVec2, 1, 2); +outVec2 = vec2.add(outVec2, vec2A, vec2B); +outVec2 = vec2.subtract(outVec2, vec2A, vec2B); +outVec2 = vec2.sub(outVec2, vec2A, vec2B); +outVec2 = vec2.multiply(outVec2, vec2A, vec2B); +outVec2 = vec2.mul(outVec2, vec2A, vec2B); +outVec2 = vec2.divide(outVec2, vec2A, vec2B); +outVec2 = vec2.div(outVec2, vec2A, vec2B); +outVec2 = vec2.ceil(outVec2, vec2A); +outVec2 = vec2.floor(outVec2, vec2A); +outVec2 = vec2.min(outVec2, vec2A, vec2B); +outVec2 = vec2.max(outVec2, vec2A, vec2B); +outVec2 = vec2.round(outVec2, vec2A); +outVec2 = vec2.scale(outVec2, vec2A, 2); +outVec2 = vec2.scaleAndAdd(outVec2, vec2A, vec2B, 0.5); +outVal = vec2.distance(vec2A, vec2B); +outVal = vec2.dist(vec2A, vec2B); +outVal = vec2.squaredDistance(vec2A, vec2B); +outVal = vec2.sqrDist(vec2A, vec2B); +outVal = vec2.length(vec2A); +outVal = vec2.len(vec2A); +outVal = vec2.squaredLength(vec2A); +outVal = vec2.sqrLen(vec2A); +outVec2 = vec2.negate(outVec2, vec2A); +outVec2 = vec2.inverse(outVec2, vec2A); +outVec2 = vec2.normalize(outVec2, vec2A); +outVal = vec2.dot(vec2A, vec2B); +outVec2 = vec2.cross(outVec2, vec2A, vec2B); +outVec2 = vec2.lerp(outVec2, vec2A, vec2B, 0.5); +outVec2 = vec2.random(outVec2); +outVec2 = vec2.random(outVec2, 5.0); +outVec2 = vec2.transformMat2(outVec2, vec2A, mat2A); +outVec2 = vec2.transformMat2d(outVec2, vec2A, mat2dA); +outVec2 = vec2.transformMat3(outVec2, vec2A, mat3A); +outVec2 = vec2.transformMat4(outVec2, vec2A, mat4A); +vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); +outStr = vec2.str(vec2A); +outBool = vec2.exactEquals(vec2A, vec2B); +outBool = vec2.equals(vec2A, vec2B); + +// vec3 +outVec3 = vec3.create(); +outVec3 = vec3.clone(vec3A); +outVec3 = vec3.fromValues(1, 2, 3); +outVec3 = vec3.copy(outVec3, vec3A); +outVec3 = vec3.set(outVec3, 1, 2, 3); +outVec3 = vec3.add(outVec3, vec3A, vec3B); +outVec3 = vec3.subtract(outVec3, vec3A, vec3B); +outVec3 = vec3.sub(outVec3, vec3A, vec3B); +outVec3 = vec3.multiply(outVec3, vec3A, vec3B); +outVec3 = vec3.mul(outVec3, vec3A, vec3B); +outVec3 = vec3.divide(outVec3, vec3A, vec3B); +outVec3 = vec3.div(outVec3, vec3A, vec3B); +outVec3 = vec3.ceil(outVec3, vec3A); +outVec3 = vec3.floor(outVec3, vec3A); +outVec3 = vec3.min(outVec3, vec3A, vec3B); +outVec3 = vec3.max(outVec3, vec3A, vec3B); +outVec3 = vec3.round(outVec3, vec3A); +outVec3 = vec3.scale(outVec3, vec3A, 2); +outVec3 = vec3.scaleAndAdd(outVec3, vec3A, vec3B, 0.5); +outVal = vec3.distance(vec3A, vec3B); +outVal = vec3.dist(vec3A, vec3B); +outVal = vec3.squaredDistance(vec3A, vec3B); +outVal = vec3.sqrDist(vec3A, vec3B); +outVal = vec3.length(vec3A); +outVal = vec3.len(vec3A); +outVal = vec3.squaredLength(vec3A); +outVal = vec3.sqrLen(vec3A); +outVec3 = vec3.negate(outVec3, vec3A); +outVec3 = vec3.inverse(outVec3, vec3A); +outVec3 = vec3.normalize(outVec3, vec3A); +outVal = vec3.dot(vec3A, vec3B); +outVec3 = vec3.cross(outVec3, vec3A, vec3B); +outVec3 = vec3.lerp(outVec3, vec3A, vec3B, 0.5); +outVec3 = vec3.hermite(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = vec3.bezier(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = vec3.random(outVec3); +outVec3 = vec3.random(outVec3, 5.0); +outVec3 = vec3.transformMat3(outVec3, vec3A, mat3A); +outVec3 = vec3.transformMat4(outVec3, vec3A, mat4A); +outVec3 = vec3.transformQuat(outVec3, vec3A, quatA); +outVec3 = vec3.rotateX(outVec3, vec3A, vec3B, Math.PI); +outVec3 = vec3.rotateY(outVec3, vec3A, vec3B, Math.PI); +outVec3 = vec3.rotateZ(outVec3, vec3A, vec3B, Math.PI); +vecArray = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); +outVal = vec3.angle(vec3A, vec3B); +outStr = vec3.str(vec3A); +outBool = vec3.exactEquals(vec3A, vec3B); +outBool = vec3.equals(vec3A, vec3B); + +// vec4 +outVec4 = vec4.create(); +outVec4 = vec4.clone(vec4A); +outVec4 = vec4.fromValues(1, 2, 3, 4); +outVec4 = vec4.copy(outVec4, vec4A); +outVec4 = vec4.set(outVec4, 1, 2, 3, 4); +outVec4 = vec4.add(outVec4, vec4A, vec4B); +outVec4 = vec4.subtract(outVec4, vec4A, vec4B); +outVec4 = vec4.sub(outVec4, vec4A, vec4B); +outVec4 = vec4.multiply(outVec4, vec4A, vec4B); +outVec4 = vec4.mul(outVec4, vec4A, vec4B); +outVec4 = vec4.divide(outVec4, vec4A, vec4B); +outVec4 = vec4.div(outVec4, vec4A, vec4B); +outVec4 = vec4.ceil(outVec4, vec4A); +outVec4 = vec4.floor(outVec4, vec4A); +outVec4 = vec4.min(outVec4, vec4A, vec4B); +outVec4 = vec4.max(outVec4, vec4A, vec4B); +outVec4 = vec4.scale(outVec4, vec4A, 2); +outVec4 = vec4.scaleAndAdd(outVec4, vec4A, vec4B, 0.5); +outVal = vec4.distance(vec4A, vec4B); +outVal = vec4.dist(vec4A, vec4B); +outVal = vec4.squaredDistance(vec4A, vec4B); +outVal = vec4.sqrDist(vec4A, vec4B); +outVal = vec4.length(vec4A); +outVal = vec4.len(vec4A); +outVal = vec4.squaredLength(vec4A); +outVal = vec4.sqrLen(vec4A); +outVec4 = vec4.negate(outVec4, vec4A); +outVec4 = vec4.inverse(outVec4, vec4A); +outVec4 = vec4.normalize(outVec4, vec4A); +outVal = vec4.dot(vec4A, vec4B); +outVec4 = vec4.lerp(outVec4, vec4A, vec4B, 0.5); +outVec4 = vec4.random(outVec4); +outVec4 = vec4.random(outVec4, 5.0); +outVec4 = vec4.transformMat4(outVec4, vec4A, mat4A); +outVec4 = vec4.transformQuat(outVec4, vec4A, quatA); +vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); +outStr = vec4.str(vec4A); +outBool = vec4.exactEquals(vec4A, vec4B); +outBool = vec4.equals(vec4A, vec4B); + +// mat2 +outMat2 = mat2.create(); +outMat2 = mat2.clone(mat2A); +outMat2 = mat2.copy(outMat2, mat2A); +outMat2 = mat2.identity(outMat2); +outMat2 = mat2.fromValues(1, 2, 3, 4); +outMat2 = mat2.set(outMat2, 1, 2, 3, 4); +outMat2 = mat2.transpose(outMat2, mat2A); +outMat2 = mat2.invert(outMat2, mat2A); +outMat2 = mat2.adjoint(outMat2, mat2A); +outVal = mat2.determinant(mat2A); +outMat2 = mat2.multiply(outMat2, mat2A, mat2B); +outMat2 = mat2.mul(outMat2, mat2A, mat2B); +outMat2 = mat2.rotate(outMat2, mat2A, Math.PI * 0.5); +outMat2 = mat2.scale(outMat2, mat2A, vec2A); +outMat2 = mat2.fromRotation(outMat2, 0.5); +outMat2 = mat2.fromScaling(outMat2, vec2A); +outStr = mat2.str(mat2A); +outVal = mat2.frob(mat2A); +var L = mat2.create(); +var D = mat2.create(); +var U = mat2.create(); +outMat2 = mat2.LDU(L, D, U, mat2A); +outMat2 = mat2.add(outMat2, mat2A, mat2B); +outMat2 = mat2.subtract(outMat2, mat2A, mat2B); +outMat2 = mat2.sub(outMat2, mat2A, mat2B); +outBool = mat2.exactEquals(mat2A, mat2B); +outBool = mat2.equals(mat2A, mat2B); +outMat2 = mat2.multiplyScalar (outMat2, mat2A, 2); +outMat2 = mat2.multiplyScalarAndAdd (outMat2, mat2A, mat2B, 2); + +// mat2d +outMat2d = mat2d.create(); +outMat2d = mat2d.clone(mat2dA); +outMat2d = mat2d.copy(outMat2d, mat2dA); +outMat2d = mat2d.identity(outMat2d); +outMat2d = mat2d.fromValues(1, 2, 3, 4, 5, 6); +outMat2d = mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6); +outMat2d = mat2d.invert(outMat2d, mat2dA); +outVal = mat2d.determinant(mat2dA); +outMat2d = mat2d.multiply(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.mul(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.rotate(outMat2d, mat2dA, Math.PI * 0.5); +outMat2d = mat2d.scale(outMat2d, mat2dA, vec2A); +outMat2d = mat2d.translate(outMat2d, mat2dA, vec2A); +outMat2d = mat2d.fromRotation(outMat2d, 0.5); +outMat2d = mat2d.fromScaling(outMat2d, vec2A); +outMat2d = mat2d.fromTranslation(outMat2d, vec2A); +outStr = mat2d.str(mat2dA); +outVal = mat2d.frob(mat2dA); +outMat2d = mat2d.add(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.subtract(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.sub(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.multiplyScalar (outMat2d, mat2dA, 2); +outMat2d = mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2); +outBool = mat2d.exactEquals(mat2dA, mat2dB); +outBool = mat2d.equals(mat2dA, mat2dB); + + +// mat3 +outMat3 = mat3.create(); +outMat3 = mat3.fromMat4(outMat3, mat4A); +outMat3 = mat3.clone(mat3A); +outMat3 = mat3.copy(outMat3, mat3A); +outMat3 = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = mat3.identity(outMat3); +outMat3 = mat3.transpose(outMat3, mat3A); +outMat3 = mat3.invert(outMat3, mat3A); +outMat3 = mat3.adjoint(outMat3, mat3A); +outVal = mat3.determinant(mat3A); +outMat3 = mat3.multiply(outMat3, mat3A, mat3B); +outMat3 = mat3.mul(outMat3, mat3A, mat3B); +outMat3 = mat3.translate(outMat3, mat3A, vec3A); +outMat3 = mat3.rotate(outMat3, mat3A, Math.PI/2); +outMat3 = mat3.scale(outMat3, mat3A, vec2A); +outMat3 = mat3.fromTranslation(outMat3, vec2A); +outMat3 = mat3.fromRotation(outMat3, Math.PI); +outMat3 = mat3.fromScaling(outMat3, vec2A); +outMat3 = mat3.fromMat2d(outMat3, mat2dA); +outMat3 = mat3.fromQuat(outMat3, quatA); +outMat3 = mat3.normalFromMat4(outMat3, mat4A); +outStr = mat3.str(mat3A); +outVal = mat3.frob(mat3A); +outMat3 = mat3.add(outMat3, mat3A, mat3B); +outMat3 = mat3.subtract(outMat3, mat3A, mat3B); +outMat3 = mat3.sub(outMat3, mat3A, mat3B); +outMat3 = mat3.multiplyScalar (outMat3, mat3A, 2); +outMat3 = mat3.multiplyScalarAndAdd (outMat3, mat3A, mat3B, 2); +outBool = mat3.exactEquals(mat3A, mat3B); +outBool = mat3.equals(mat3A, mat3B); + +//mat4 +outMat4 = mat4.create(); +outMat4 = mat4.clone(mat4A); +outMat4 = mat4.copy(outMat4, mat4A); +outMat4 = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = mat4.identity(outMat4); +outMat4 = mat4.transpose(outMat4, mat4A); +outMat4 = mat4.invert(outMat4, mat4A); +outMat4 = mat4.adjoint(outMat4, mat4A); +outVal = mat4.determinant(mat4A); +outMat4 = mat4.multiply(outMat4, mat4A, mat4B); +outMat4 = mat4.mul(outMat4, mat4A, mat4B); +outMat4 = mat4.translate(outMat4, mat4A, vec3A); +outMat4 = mat4.scale(outMat4, mat4A, vec3A); +outMat4 = mat4.rotate(outMat4, mat4A, Math.PI, vec3A); +outMat4 = mat4.rotateX(outMat4, mat4A, Math.PI); +outMat4 = mat4.rotateY(outMat4, mat4A, Math.PI); +outMat4 = mat4.rotateZ(outMat4, mat4A, Math.PI); +outMat4 = mat4.fromTranslation(outMat4, vec3A); +outMat4 = mat4.fromRotation(outMat4, Math.PI, vec3A); +outMat4 = mat4.fromScaling(outMat4, vec3A); +outMat4 = mat4.fromXRotation(outMat4, Math.PI); +outMat4 = mat4.fromYRotation(outMat4, Math.PI); +outMat4 = mat4.fromZRotation(outMat4, Math.PI); +outMat4 = mat4.fromRotationTranslation(outMat4, quatA, vec3A); +outVec3 = mat4.getTranslation(outVec3, mat4A) +outQuat = mat4.getRotation(outQuat, mat4A) +outMat4 = mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B); +outMat4 = mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A); +outMat4 = mat4.fromQuat(outMat4, quatB); +outMat4 = mat4.frustum(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = mat4.perspective(outMat4, Math.PI, 1, 0, 1); +outMat4 = mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0); +outMat4 = mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = mat4.lookAt(outMat4, vec3A, vec3B, vec3A); +outStr = mat4.str(mat4A); +outVal = mat4.frob(mat4A); +outMat4 = mat4.add(outMat4, mat4A, mat4B); +outMat4 = mat4.subtract(outMat4, mat4A, mat4B); +outMat4 = mat4.sub(outMat4, mat4A, mat4B); +outMat4 = mat4.multiplyScalar (outMat4, mat4A, 2); +outMat4 = mat4.multiplyScalarAndAdd (outMat4, mat4A, mat4B, 2); +outBool = mat4.exactEquals(mat4A, mat4B); +outBool = mat4.equals(mat4A, mat4B); + +// quat +var deg90 = Math.PI / 2; +outQuat = quat.create(); +outQuat = quat.clone(quatA); +outQuat = quat.fromValues(1, 2, 3, 4); +outQuat = quat.copy(outQuat, quatA); +outQuat = quat.set(outQuat, 1, 2, 3, 4); +outQuat = quat.identity(outQuat); +outQuat = quat.rotationTo(outQuat, vec3A, vec3B); +outQuat = quat.setAxes(outQuat, vec3A, vec3B, vec3A); +outQuat = quat.setAxisAngle(outQuat, vec3A, Math.PI * 0.5); +outVal = quat.getAxisAngle (outVec3, quatA); +outQuat = quat.add(outQuat, quatA, quatB); +outQuat = quat.multiply(outQuat, quatA, quatB); +outQuat = quat.mul(outQuat, quatA, quatB); +outQuat = quat.scale(outQuat, quatA, 2); +outVal = quat.length(quatA); +outVal = quat.len(quatA); +outVal = quat.squaredLength(quatA); +outVal = quat.sqrLen(quatA); +outQuat = quat.normalize(outQuat, quatA); +outVal = quat.dot(quatA, quatB); +outQuat = quat.lerp(outQuat, quatA, quatB, 0.5); +outQuat = quat.slerp(outQuat, quatA, quatB, 0.5); +outQuat = quat.invert(outQuat, quatA); +outQuat = quat.conjugate(outQuat, quatA); +outStr = quat.str(quatA); +outQuat = quat.rotateX(outQuat, quatA, deg90); +outQuat = quat.rotateY(outQuat, quatA, deg90); +outQuat = quat.rotateZ(outQuat, quatA, deg90); +outQuat = quat.fromMat3(outQuat, mat3A); +outQuat = quat.calculateW(outQuat, quatA); +outBool = quat.exactEquals(quatA, quatB); +outBool = quat.equals(quatA, quatB); \ No newline at end of file diff --git a/gl-matrix/gl-matrix-typed.d.ts b/gl-matrix/gl-matrix-typed.d.ts new file mode 100644 index 0000000000..e172074fec --- /dev/null +++ b/gl-matrix/gl-matrix-typed.d.ts @@ -0,0 +1,3054 @@ +// Type definitions for gl-matrix 2.2.2 +// Project: https://github.com/toji/gl-matrix +// Definitions by: Mattijs Kneppers , based on definitions by Tat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Common +export class glMatrix { + /** + * Convert Degree To Radian + * + * @param a Angle in Degrees + */ + public static toRadian(a: number): number; +} + +// vec2 +export class vec2 extends Float32Array { + private typeVec2:number; + + /** + * Creates a new, empty vec2 + * + * @returns a new 2D vector + */ + public static create(): vec2; + + /** + * Creates a new vec2 initialized with values from an existing vector + * + * @param a a vector to clone + * @returns a new 2D vector + */ + public static clone(a: vec2): vec2; + + /** + * Creates a new vec2 initialized with the given values + * + * @param x X component + * @param y Y component + * @returns a new 2D vector + */ + public static fromValues(x: number, y: number): vec2; + + /** + * Copy the values from one vec2 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + public static copy(out: vec2, a: vec2): vec2; + + /** + * Set the components of a vec2 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @returns out + */ + public static set(out: vec2, x: number, y: number): vec2; + + /** + * Adds two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static add(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static subtract(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static sub(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static divide(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static div(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Math.ceil the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to ceil + * @returns {vec2} out + */ + public static ceil(out:vec2, a:vec2):vec2; + + /** + * Math.floor the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to floor + * @returns {vec2} out + */ + public static floor (out:vec2, a:vec2):vec2; + + /** + * Returns the minimum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static min(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Returns the maximum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static max(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Math.round the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to round + * @returns {vec2} out + */ + public static round(out:vec2, a:vec2):vec2; + + + /** + * Scales a vec2 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + public static scale(out: vec2, a: vec2, b: number): vec2; + + /** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + public static scaleAndAdd(out: vec2, a: vec2, b: vec2, scale: number): vec2; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static distance(a: vec2, b: vec2): number; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static dist(a: vec2, b: vec2): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static squaredDistance(a: vec2, b: vec2): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static sqrDist(a: vec2, b: vec2): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static length(a: vec2): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static len(a: vec2): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static squaredLength(a: vec2): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static sqrLen(a: vec2): number; + + /** + * Negates the components of a vec2 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + public static negate(out: vec2, a: vec2): vec2; + + /** + * Returns the inverse of the components of a vec2 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + public static inverse(out: vec2, a: vec2): vec2; + + /** + * Normalize a vec2 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + public static normalize(out: vec2, a: vec2): vec2; + + /** + * Calculates the dot product of two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + public static dot(a: vec2, b: vec2): number; + + /** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static cross(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Performs a linear interpolation between two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static lerp(out: vec2, a: vec2, b: vec2, t: number): vec2; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + public static random(out: vec2): vec2; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + public static random(out: vec2, scale: number): vec2; + + /** + * Transforms the vec2 with a mat2 + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat2(out: vec2, a: vec2, m: mat2): vec2; + + /** + * Transforms the vec2 with a mat2d + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat2d(out: vec2, a: vec2, m: mat2d): vec2; + + /** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat3(out: vec2, a: vec2, m: mat3): vec2; + + /** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat4(out: vec2, a: vec2, m: mat4): vec2; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2, b: vec2, arg: any) => void, arg: any): Float32Array; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2, b: vec2) => void): Float32Array; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + public static str(a: vec2): string; + + /** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a:vec2, b:vec2): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a:vec2, b:vec2) : boolean; +} + +// vec3 +export class vec3 extends Float32Array { + private typeVec3:number; + + /** + * Creates a new, empty vec3 + * + * @returns a new 3D vector + */ + public static create(): vec3; + + /** + * Creates a new vec3 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 3D vector + */ + public static clone(a: vec3): vec3; + + /** + * Creates a new vec3 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @returns a new 3D vector + */ + public static fromValues(x: number, y: number, z: number): vec3; + + /** + * Copy the values from one vec3 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + public static copy(out: vec3, a: vec3): vec3; + + /** + * Set the components of a vec3 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @returns out + */ + public static set(out: vec3, x: number, y: number, z: number): vec3; + + /** + * Adds two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static add(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static subtract(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static sub(out: vec3, a: vec3, b: vec3): vec3 + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static divide(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static div(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Math.ceil the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to ceil + * @returns {vec3} out + */ + public static ceil (out:vec3, a:vec3) : vec3; + + /** + * Math.floor the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to floor + * @returns {vec3} out + */ + public static floor (out:vec3, a:vec3) :vec3; + + /** + * Returns the minimum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static min(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Returns the maximum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static max(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Math.round the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to round + * @returns {vec3} out + */ + public static round (out:vec3, a:vec3) : vec3 + + /** + * Scales a vec3 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + public static scale(out: vec3, a: vec3, b: number): vec3; + + /** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + public static scaleAndAdd(out: vec3, a: vec3, b: vec3, scale: number): vec3; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static distance(a: vec3, b: vec3): number; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static dist(a: vec3, b: vec3): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static squaredDistance(a: vec3, b: vec3): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static sqrDist(a: vec3, b: vec3): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static length(a: vec3): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static len(a: vec3): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static squaredLength(a: vec3): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static sqrLen(a: vec3): number; + + /** + * Negates the components of a vec3 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + public static negate(out: vec3, a: vec3): vec3; + + /** + * Returns the inverse of the components of a vec3 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + public static inverse(out: vec3, a: vec3): vec3; + + /** + * Normalize a vec3 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + public static normalize(out: vec3, a: vec3): vec3; + + /** + * Calculates the dot product of two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + public static dot(a: vec3, b: vec3): number; + + /** + * Computes the cross product of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static cross(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Performs a linear interpolation between two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static lerp(out: vec3, a: vec3, b: vec3, t: number): vec3; + + /** + * Performs a hermite interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static hermite (out:vec3, a:vec3, b:vec3, c:vec3, d:vec3, t:number) : vec3; + + /** + * Performs a bezier interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static bezier (out:vec3, a:vec3, b:vec3, c:vec3, d:vec3, t:number) :vec3; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + public static random(out: vec3): vec3; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned + * @returns out + */ + public static random(out: vec3, scale: number): vec3; + + /** + * Transforms the vec3 with a mat3. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m the 3x3 matrix to transform with + * @returns out + */ + public static transformMat3(out: vec3, a: vec3, m: mat3): vec3; + + /** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat4(out: vec3, a: vec3, m: mat4): vec3; + + /** + * Transforms the vec3 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + public static transformQuat(out: vec3, a: vec3, q: quat): vec3; + + + /** + * Rotate a 3D vector around the x-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateX(out: vec3, a: vec3, b: vec3, c: number): vec3; + + /** + * Rotate a 3D vector around the y-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateY(out: vec3, a: vec3, b: vec3, c: number): vec3; + + /** + * Rotate a 3D vector around the z-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateZ(out: vec3, a: vec3, b: vec3, c: number): vec3; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3, b: vec3, arg: any) => void, arg: any): Float32Array; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3, b: vec3) => void): Float32Array; + + /** + * Get the angle between two 3D vectors + * @param a The first operand + * @param b The second operand + * @returns The angle in radians + */ + public static angle(a: vec3, b: vec3): number; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + public static str(a: vec3): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a:vec3, b:vec3): boolean + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a:vec3, b:vec3) : boolean +} + +// vec4 +export class vec4 extends Float32Array { + private typeVec3:number; + + /** + * Creates a new, empty vec4 + * + * @returns a new 4D vector + */ + public static create(): vec4; + + /** + * Creates a new vec4 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 4D vector + */ + public static clone(a: vec4): vec4; + + /** + * Creates a new vec4 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new 4D vector + */ + public static fromValues(x: number, y: number, z: number, w: number): vec4; + + /** + * Copy the values from one vec4 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + public static copy(out: vec4, a: vec4): vec4; + + /** + * Set the components of a vec4 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + */ + public static set(out: vec4, x: number, y: number, z: number, w: number): vec4; + + /** + * Adds two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static add(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static subtract(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static sub(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static divide(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static div(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Math.ceil the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to ceil + * @returns {vec4} out + */ + public static ceil (out:vec4, a:vec4) : vec4; + + /** + * Math.floor the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to floor + * @returns {vec4} out + */ + public static floor (out:vec4, a:vec4) : vec4; + + /** + * Returns the minimum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static min(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Returns the maximum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static max(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Math.round the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to round + * @returns {vec4} out + */ + public static round (out:vec4, a:vec4): vec4; + + /** + * Scales a vec4 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + public static scale(out: vec4, a: vec4, b: number): vec4; + + /** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + public static scaleAndAdd(out: vec4, a: vec4, b: vec4, scale: number): vec4; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static distance(a: vec4, b: vec4): number; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static dist(a: vec4, b: vec4): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static squaredDistance(a: vec4, b: vec4): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static sqrDist(a: vec4, b: vec4): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static length(a: vec4): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static len(a: vec4): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static squaredLength(a: vec4): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static sqrLen(a: vec4): number; + + /** + * Negates the components of a vec4 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + public static negate(out: vec4, a: vec4): vec4; + + /** + * Returns the inverse of the components of a vec4 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + public static inverse(out: vec4, a: vec4): vec4; + + /** + * Normalize a vec4 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + public static normalize(out: vec4, a: vec4): vec4; + + /** + * Calculates the dot product of two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + public static dot(a: vec4, b: vec4): number; + + /** + * Performs a linear interpolation between two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static lerp(out: vec4, a: vec4, b: vec4, t: number): vec4; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + public static random(out: vec4): vec4; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + public static random(out: vec4, scale: number): vec4; + + /** + * Transforms the vec4 with a mat4. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat4(out: vec4, a: vec4, m: mat4): vec4; + + /** + * Transforms the vec4 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + + public static transformQuat(out: vec4, a: vec4, q: quat): vec4; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4, b: vec4, arg: any) => void, arg: any): Float32Array; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4, b: vec4) => void): Float32Array; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + public static str(a: vec4): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a:vec4, b:vec4) : boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a:vec4, b:vec4) : boolean; +} + +// mat2 +export class mat2 extends Float32Array { + private typeMat2:number; + + /** + * Creates a new identity mat2 + * + * @returns a new 2x2 matrix + */ + public static create():mat2; + + /** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x2 matrix + */ + public static clone(a:mat2):mat2; + + /** + * Copy the values from one mat2 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out:mat2, a:mat2):mat2; + + /** + * Set a mat2 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out:mat2):mat2; + + /** + * Create a new mat2 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out A new 2x2 matrix + */ + public static fromValues(m00:number, m01:number, m10:number, m11:number):mat2; + + /** + * Set the components of a mat2 to the given values + * + * @param {mat2} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out + */ + public static set(out:mat2, m00:number, m01:number, m10:number, m11:number):mat2; + + /** + * Transpose the values of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static transpose(out:mat2, a:mat2):mat2; + + /** + * Inverts a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out:mat2, a:mat2):mat2; + + /** + * Calculates the adjugate of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static adjoint(out:mat2, a:mat2):mat2; + + /** + * Calculates the determinant of a mat2 + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a:mat2):number; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out:mat2, a:mat2, b:mat2):mat2; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out:mat2, a:mat2, b:mat2):mat2; + + /** + * Rotates a mat2 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotate(out:mat2, a:mat2, rad:number):mat2; + + /** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out:mat2, a:mat2, v:vec2):mat2; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.rotate(dest, dest, rad); + * + * @param {mat2} out mat2 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + public static fromRotation(out:mat2, rad:number):mat2; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.scale(dest, dest, vec); + * + * @param {mat2} out mat2 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2} out + */ + public static fromScaling(out:mat2, v:vec2):mat2; + + /** + * Returns a string representation of a mat2 + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(a:mat2):string; + + /** + * Returns Frobenius norm of a mat2 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a:mat2):number; + + /** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param L the lower triangular matrix + * @param D the diagonal matrix + * @param U the upper triangular matrix + * @param a the input matrix to factorize + */ + public static LDU(L:mat2, D:mat2, U:mat2, a:mat2):mat2; + + /** + * Adds two mat2's + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static add(out:mat2, a:mat2, b:mat2):mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static subtract (out:mat2, a:mat2, b:mat2):mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static sub (out:mat2, a:mat2, b:mat2):mat2; + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a:mat2, b:mat2):boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a:mat2, b:mat2) :boolean; + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2} out + */ + public static multiplyScalar (out:mat2, a:mat2, b:number) :mat2 + + /** + * Adds two mat2's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2} out the receiving vector + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2} out + */ + public static multiplyScalarAndAdd (out:mat2, a:mat2, b:mat2, scale:number): mat2 + + + +} + +// mat2d +export class mat2d extends Float32Array { + private typeMat2d:number; + + /** + * Creates a new identity mat2d + * + * @returns a new 2x3 matrix + */ + public static create(): mat2d; + + /** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x3 matrix + */ + public static clone(a: mat2d): mat2d; + + /** + * Copy the values from one mat2d to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out: mat2d, a: mat2d): mat2d; + + /** + * Set a mat2d to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out: mat2d): mat2d; + + /** + * Create a new mat2d with the given values + * + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} A new mat2d + */ + public static fromValues (a:number, b:number, c:number, d:number, tx:number, ty:number) : mat2d + + + /** + * Set the components of a mat2d to the given values + * + * @param {mat2d} out the receiving matrix + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} out + */ + public static set (out:mat2d, a:number, b:number, c:number, d:number, tx:number, ty:number) :mat2d + + /** + * Inverts a mat2d + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out: mat2d, a: mat2d): mat2d; + + /** + * Calculates the determinant of a mat2d + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a: mat2d): number; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: mat2d, a: mat2d, b: mat2d): mat2d; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: mat2d, a: mat2d, b: mat2d): mat2d; + + /** + * Rotates a mat2d by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotate(out: mat2d, a: mat2d, rad: number): mat2d; + + /** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out: mat2d, a: mat2d, v: vec2): mat2d; + + /** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to translate the matrix by + * @returns out + **/ + public static translate(out: mat2d, a: mat2d, v: vec2): mat2d; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.rotate(dest, dest, rad); + * + * @param {mat2d} out mat2d receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + public static fromRotation (out:mat2d, rad:number): mat2d; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.scale(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2d} out + */ + public static fromScaling (out:mat2d, v:vec2):mat2d; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.translate(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Translation vector + * @returns {mat2d} out + */ + public static fromTranslation (out:mat2d, v:vec2):mat2d + + /** + * Returns a string representation of a mat2d + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(a: mat2d): string; + + /** + * Returns Frobenius norm of a mat2d + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat2d): number; + + /** + * Adds two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static add (out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static subtract(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static sub(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2d} out + */ + public static multiplyScalar (out: mat2d, a: mat2d, b: number): mat2d; + + /** + * Adds two mat2d's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2d} out the receiving vector + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2d} out + */ + public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale:number) : mat2d + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat2d, b: mat2d): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat2d, b: mat2d): boolean +} + +// mat3 +export class mat3 extends Float32Array { + private typeMat3:number; + + /** + * Creates a new identity mat3 + * + * @returns a new 3x3 matrix + */ + public static create():mat3; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {mat4} a the source 4x4 matrix + * @returns {mat3} out + */ + public static fromMat4(out:mat3, a:mat4):mat3 + + /** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 3x3 matrix + */ + public static clone(a:mat3):mat3; + + /** + * Copy the values from one mat3 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out:mat3, a:mat3):mat3; + + /** + * Create a new mat3 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} A new mat3 + */ + public static fromValues(m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number):mat3; + + + /** + * Set the components of a mat3 to the given values + * + * @param {mat3} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} out + */ + public static set(out:mat3, m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number):mat3 + + /** + * Set a mat3 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out:mat3):mat3; + + /** + * Transpose the values of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static transpose(out:mat3, a:mat3):mat3; + + /** + * Inverts a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out:mat3, a:mat3):mat3; + + /** + * Calculates the adjugate of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static adjoint(out:mat3, a:mat3):mat3; + + /** + * Calculates the determinant of a mat3 + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a:mat3):number; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out:mat3, a:mat3, b:mat3):mat3; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out:mat3, a:mat3, b:mat3):mat3; + + + /** + * Translate a mat3 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + public static translate(out:mat3, a:mat3, v:vec3):mat3; + + /** + * Rotates a mat3 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotate(out:mat3, a:mat3, rad:number):mat3; + + /** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out:mat3, a:mat3, v:vec2):mat3; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.translate(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Translation vector + * @returns {mat3} out + */ + public static fromTranslation(out:mat3, v:vec2):mat3 + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + public static fromRotation(out:mat3, rad:number):mat3 + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.scale(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat3} out + */ + public static fromScaling(out:mat3, v:vec2):mat3 + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + **/ + public static fromMat2d(out:mat3, a:mat2d):mat3; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + public static fromQuat(out:mat3, q:quat):mat3; + + /** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param out mat3 receiving operation result + * @param a Mat4 to derive the normal matrix from + * + * @returns out + */ + public static normalFromMat4(out:mat3, a:mat4):mat3; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat:mat3):string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a:mat3):number; + + /** + * Adds two mat3's + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static add(out:mat3, a:mat3, b:mat3):mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static subtract(out:mat3, a:mat3, b:mat3):mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static sub(out:mat3, a:mat3, b:mat3):mat3 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat3} out + */ + public static multiplyScalar(out:mat3, a:mat3, b:number):mat3 + + /** + * Adds two mat3's after multiplying each element of the second operand by a scalar value. + * + * @param {mat3} out the receiving vector + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat3} out + */ + public static multiplyScalarAndAdd(out:mat3, a:mat3, b:mat3, scale:number):mat3 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals(a:mat3, b:mat3):boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals(a:mat3, b:mat3):boolean +} + +// mat4 +export class mat4 extends Float32Array { + private typeMat4:number; + + /** + * Creates a new identity mat4 + * + * @returns a new 4x4 matrix + */ + public static create():mat4; + + /** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 4x4 matrix + */ + public static clone(a:mat4):mat4; + + /** + * Copy the values from one mat4 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out:mat4, a:mat4):mat4; + + + /** + * Create a new mat4 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} A new mat4 + */ + public static fromValues(m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number):mat4; + + /** + * Set the components of a mat4 to the given values + * + * @param {mat4} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} out + */ + public static set(out:mat4, m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number):mat4; + + /** + * Set a mat4 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out:mat4):mat4; + + /** + * Transpose the values of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static transpose(out:mat4, a:mat4):mat4; + + /** + * Inverts a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out:mat4, a:mat4):mat4; + + /** + * Calculates the adjugate of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static adjoint(out:mat4, a:mat4):mat4; + + /** + * Calculates the determinant of a mat4 + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a:mat4):number; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out:mat4, a:mat4, b:mat4):mat4; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out:mat4, a:mat4, b:mat4):mat4; + + /** + * Translate a mat4 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + public static translate(out:mat4, a:mat4, v:vec3):mat4; + + /** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param out the receiving matrix + * @param a the matrix to scale + * @param v the vec3 to scale the matrix by + * @returns out + **/ + public static scale(out:mat4, a:mat4, v:vec3):mat4; + + /** + * Rotates a mat4 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @param axis the axis to rotate around + * @returns out + */ + public static rotate(out:mat4, a:mat4, rad:number, axis:vec3):mat4; + + /** + * Rotates a matrix by the given angle around the X axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotateX(out:mat4, a:mat4, rad:number):mat4; + + /** + * Rotates a matrix by the given angle around the Y axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotateY(out:mat4, a:mat4, rad:number):mat4; + + /** + * Rotates a matrix by the given angle around the Z axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotateZ(out:mat4, a:mat4, rad:number):mat4; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Translation vector + * @returns {mat4} out + */ + public static fromTranslation(out:mat4, v:vec3):mat4 + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Scaling vector + * @returns {mat4} out + */ + public static fromScaling(out:mat4, v:vec3):mat4 + + /** + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotate(dest, dest, rad, axis); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out + */ + public static fromRotation(out:mat4, rad:number, axis:vec3):mat4 + + /** + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateX(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + public static fromXRotation(out:mat4, rad:number):mat4 + + /** + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateY(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + public static fromYRotation(out:mat4, rad:number):mat4 + + + /** + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateZ(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + public static fromZRotation(out:mat4, rad:number):mat4 + + /** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @returns out + */ + public static fromRotationTranslation(out:mat4, q:quat, v:vec3):mat4; + + /** + * Returns the translation vector component of a transformation + * matrix. If a matrix is built with fromRotationTranslation, + * the returned vector will be the same as the translation vector + * originally supplied. + * @param {vec3} out Vector to receive translation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + public static getTranslation(out:vec3, mat:mat4):vec3; + + /** + * Returns a quaternion representing the rotational component + * of a transformation matrix. If a matrix is built with + * fromRotationTranslation, the returned quaternion will be the + * same as the quaternion originally supplied. + * @param {quat} out Quaternion to receive the rotation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {quat} out + */ + public static getRotation(out:quat, mat:mat4):quat; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @param s Scaling vector + * @returns out + */ + public static fromRotationTranslationScale(out:mat4, q:quat, v:vec3, s:vec3):mat4; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * mat4.translate(dest, origin); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * mat4.translate(dest, negativeOrigin); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Rotation quaternion + * @param {vec3} v Translation vector + * @param {vec3} s Scaling vector + * @param {vec3} o The origin vector around which to scale and rotate + * @returns {mat4} out + */ + public static fromRotationTranslationScaleOrigin(out:mat4, q:quat, v:vec3, s:vec3, o:vec3):mat4 + + /** + * Calculates a 4x4 matrix from the given quaternion + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Quaternion to create matrix from + * + * @returns {mat4} out + */ + public static fromQuat(out:mat4, q:quat):mat4 + + /** + * Generates a frustum matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static frustum(out:mat4, left:number, right:number, + bottom:number, top:number, near:number, far:number):mat4; + + /** + * Generates a perspective projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. typically viewport width/height + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static perspective(out:mat4, fovy:number, aspect:number, + near:number, far:number):mat4; + + /** + * Generates a perspective projection matrix with the given field of view. + * This is primarily useful for generating projection matrices to be used + * with the still experimental WebVR API. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + public static perspectiveFromFieldOfView(out:mat4, + fov:{upDegrees:number, downDegrees:number, leftDegrees:number, rightDegrees:number}, + near:number, far:number):mat4 + + /** + * Generates a orthogonal projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static ortho(out:mat4, left:number, right:number, + bottom:number, top:number, near:number, far:number):mat4; + + /** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + public static lookAt(out:mat4, eye:vec3, center:vec3, up:vec3):mat4; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat:mat4):string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a:mat4):number; + + /** + * Adds two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static add(out:mat4, a:mat4, b:mat4):mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static subtract(out:mat4, a:mat4, b:mat4):mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static sub(out:mat4, a:mat4, b:mat4):mat4 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat4} out + */ + public static multiplyScalar(out:mat4, a:mat4, b:number):mat4 + + /** + * Adds two mat4's after multiplying each element of the second operand by a scalar value. + * + * @param {mat4} out the receiving vector + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat4} out + */ + public static multiplyScalarAndAdd (out:mat4, a:mat4, b:mat4, scale:number):mat4 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a:mat4, b:mat4) :boolean + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a:mat4, b:mat4): boolean + +} + +// quat +export class quat extends Float32Array { + private typeQuat:number; + + /** + * Creates a new identity quat + * + * @returns a new quaternion + */ + public static create(): quat; + + /** + * Creates a new quat initialized with values from an existing quaternion + * + * @param a quaternion to clone + * @returns a new quaternion + * @function + */ + public static clone(a: quat): quat; + + /** + * Creates a new quat initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new quaternion + * @function + */ + public static fromValues(x: number, y: number, z: number, w: number): quat; + + /** + * Copy the values from one quat to another + * + * @param out the receiving quaternion + * @param a the source quaternion + * @returns out + * @function + */ + public static copy(out: quat, a: quat): quat; + + /** + * Set the components of a quat to the given values + * + * @param out the receiving quaternion + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + * @function + */ + public static set(out: quat, x: number, y: number, z: number, w: number): quat; + + /** + * Set a quat to the identity quaternion + * + * @param out the receiving quaternion + * @returns out + */ + public static identity(out: quat): quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {vec3} a the initial vector + * @param {vec3} b the destination vector + * @returns {quat} out + */ + public static rotationTo (out:quat, a:vec3, b:vec3): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + public static setAxes (out:quat, view:vec3, right:vec3, up:vec3):quat + + + + /** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param out the receiving quaternion + * @param axis the axis around which to rotate + * @param rad the angle in radians + * @returns out + **/ + public static setAxisAngle(out: quat, axis: vec3, rad: number): quat; + + /** + * Gets the rotation axis and angle for a given + * quaternion. If a quaternion is created with + * setAxisAngle, this method will return the same + * values as providied in the original parameter list + * OR functionally equivalent values. + * Example: The quaternion formed by axis [0, 0, 1] and + * angle -90 is the same as the quaternion formed by + * [0, 0, 1] and 270. This method favors the latter. + * @param {vec3} out_axis Vector receiving the axis of rotation + * @param {quat} q Quaternion to be decomposed + * @return {number} Angle, in radians, of the rotation + */ + public static getAxisAngle (out_axis:vec3, q:quat) :number + + /** + * Adds two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + * @function + */ + public static add(out: quat, a: quat, b: quat): quat; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: quat, a: quat, b: quat): quat; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: quat, a: quat, b: quat): quat; + + /** + * Scales a quat by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + * @function + */ + public static scale(out: quat, a: quat, b: number): quat; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + public static length(a: quat): number; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + public static len(a: quat): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + public static squaredLength(a: quat): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + public static sqrLen(a: quat): number; + + /** + * Normalize a quat + * + * @param out the receiving quaternion + * @param a quaternion to normalize + * @returns out + * @function + */ + public static normalize(out: quat, a: quat): quat; + + /** + * Calculates the dot product of two quat's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + * @function + */ + public static dot(a: quat, b: quat): number; + + /** + * Performs a linear interpolation between two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + * @function + */ + public static lerp(out: quat, a: quat, b: quat, t: number): quat; + + /** + * Performs a spherical linear interpolation between two quat + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static slerp(out:quat, a:quat, b:quat, t:number): quat; + + /** + * Performs a spherical linear interpolation with two control points + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {quat} c the third operand + * @param {quat} d the fourth operand + * @param {number} t interpolation amount + * @returns {quat} out + */ + public static sqlerp(out: quat, a: quat, b: quat, c: quat, d: quat, t: number): quat; + + /** + * Calculates the inverse of a quat + * + * @param out the receiving quaternion + * @param a quat to calculate inverse of + * @returns out + */ + public static invert(out: quat, a: quat): quat; + + /** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param out the receiving quaternion + * @param a quat to calculate conjugate of + * @returns out + */ + public static conjugate(out: quat, a: quat): quat; + + /** + * Returns a string representation of a quaternion + * + * @param a quat to represent as a string + * @returns string representation of the quat + */ + public static str(a: quat): string; + + /** + * Rotates a quaternion by the given angle about the X axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + public static rotateX(out: quat, a: quat, rad: number): quat; + + /** + * Rotates a quaternion by the given angle about the Y axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + public static rotateY(out: quat, a: quat, rad: number): quat; + + /** + * Rotates a quaternion by the given angle about the Z axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + public static rotateZ(out: quat, a: quat, rad: number): quat; + + /** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param out the receiving quaternion + * @param m rotation matrix + * @returns out + * @function + */ + public static fromMat3(out: quat, m: mat3): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param out the receiving quat + * @param view the vector representing the viewing direction + * @param right the vector representing the local "right" direction + * @param up the vector representing the local "up" direction + * @returns out + */ + public static setAxes(out: quat, view: vec3, right: vec3, up: vec3): quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param out the receiving quaternion. + * @param a the initial vector + * @param b the destination vector + * @returns out + */ + public static rotationTo(out: quat, a: vec3, b: vec3): quat; + + /** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param out the receiving quaternion + * @param a quat to calculate W component of + * @returns out + */ + public static calculateW(out: quat, a: quat): quat; + + /** + * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static exactEquals (a:quat, b:quat) : boolean; + + /** + * Returns whether or not the quaternions have approximately the same elements in the same position. + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static equals (a:quat, b:quat) : boolean; +} diff --git a/globalize-compiler/globalize-compiler-tests.ts b/globalize-compiler/globalize-compiler-tests.ts new file mode 100644 index 0000000000..f4fc934d1f --- /dev/null +++ b/globalize-compiler/globalize-compiler-tests.ts @@ -0,0 +1,36 @@ +/// + +import globalizeCompiler = require("globalize-compiler"); +const globalize: GlobalizeStatic = null; + +let extractsArray: GlobalizeCompiler.FormatterOrParserFunction[]; + +const templateFunction: (options: GlobalizeCompiler.CompileTemplateOptions) => string = + (options: GlobalizeCompiler.CompileTemplateOptions): string => { + const deps: string[] = options.dependencies; + const code: string = options.code; + return `${deps.join(';')}${code}`; + }; + +let compileOutput: string; +compileOutput = globalizeCompiler.compile(extractsArray); +compileOutput = globalizeCompiler.compile({ x: () => "test", y: (x: string) => x }); +compileOutput = globalizeCompiler.compile(extractsArray, { template: templateFunction }); +compileOutput = globalizeCompiler.compile({ x: () => "test", y: (x: string) => x }, { template: templateFunction }); + +let extractOutput: GlobalizeCompiler.ExtractFunction; +extractOutput = globalizeCompiler.extract("path"); + +const ast: ESTree.Program = undefined; +extractOutput = globalizeCompiler.extract(ast); + +extractsArray = extractOutput(globalize); + +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en" }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", messages: {} }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", template: templateFunction }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", messages: {}, template: templateFunction }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", cldr: {} }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", cldr: {}, messages: {} }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", cldr: {}, template: templateFunction }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", cldr: {}, messages: {}, template: templateFunction }); diff --git a/globalize-compiler/globalize-compiler.d.ts b/globalize-compiler/globalize-compiler.d.ts new file mode 100644 index 0000000000..3959924412 --- /dev/null +++ b/globalize-compiler/globalize-compiler.d.ts @@ -0,0 +1,106 @@ +// Type definitions for globalize-compiler v0.2.0 +// Project: https://github.com/jquery-support/globalize-compiler +// Definitions by: Ian Clanton-Thuon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace GlobalizeCompiler { + interface CompileTemplateOptions { + /** + * the source of the compiled formatters and parsers. + */ + code: string; + + /** + * a list of globalize runtime modules that the compiled code depends on, e.g. globalize-runtime/number. + */ + dependencies: string[]; + } + + interface CompileOptions { + /** + * A function that replaces the default template. + */ + template?: (options: CompileTemplateOptions) => string; + } + + interface FormatterOrParserFunction { + (...arguments: any[]): any; + } + + interface ExtractFunction { + /** + * @param {globalize} the globalize object. + * + * @returns an Array with the formatters and parsers created using the passed Globalize. + */ + (globalize: GlobalizeStatic): FormatterOrParserFunction[]; + } + + interface CompileExtractsAttributes extends CompileOptions { + /** + * an Array of extracts obtained by @see{GlobalizeCompilerStatic.extract} + */ + extracts: ExtractFunction; + + /** + * a locale to be used as Globalize.locale(defaultLocale) when generating the extracted formatters and parsers. + */ + defaultLocale: string; + + /** + * an Object with CLDR data (in the JSON format) or a Function taking one argument: locale, a String; returning + * an Object with the CLDR data for the passed locale. Defaults to the entire supplemental data plus the entire + * main data for the defaultLocale. + */ + cldr?: Object | ((locale: string) => Object); + + /** + * an Object with messages data (in the JSON format) or a Function taking one argument: locale, a String; returning + * an Object with the messages data for the passed locale. Defaults to {}. + */ + messages?: Object | ((locale: string) => Object); + } + + interface GlobalizeCompilerStatic { + /** + * Generates a JavaScript bundle containing the specified globalize formatters and parsers. + * + * @param {formattersAndParsers} an Array or an Object containing formatters and/or parsers. + * @param {options} compiler options. + * + * @returns a String with the generated JavaScript bundle (UMD wrapped) including the compiled formatters and + * parsers. + */ + compile(formattersAndParsers: FormatterOrParserFunction[] | { [key: string]: FormatterOrParserFunction }, + options?: CompileOptions): string; + + /** + * Creates an extract function from a source file. + * + * @param {input} a String with a filename, or a String with the file content, or an AST Object. + * + * @returns an extract. An extract is a Function taking one argument: Globalize, the Globalize Object; + * and returning an Array with the formatters and parsers created using the passed Globalize. + */ + extract(input: string | ESTree.Program): ExtractFunction; + + /** + * Generates a JavaScript bundle containing the specified globalize formatters and parsers. + * + * @param {options} compiler attributes. + * + * @returns a String with the generated JavaScript bundle (UMD wrapped) including the compiled formatters and + * parsers. + */ + compileExtracts(attributes: CompileExtractsAttributes): string; + } +} + +declare module "globalize-compiler" { + var globalizeCompiler: GlobalizeCompiler.GlobalizeCompilerStatic; + + export = globalizeCompiler; +} diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 58ce037eea..0c551fd712 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1783,21 +1783,22 @@ declare namespace google.maps { } export type LatLngLiteral = { lat: number; lng: number } + export type LatLngBoundsLiteral = { east: number; north: number; south: number; west: number } export class LatLngBounds { - constructor(sw?: LatLng, ne?: LatLng); + constructor(sw?: LatLng|LatLngLiteral, ne?: LatLng|LatLngLiteral); contains(latLng: LatLng): boolean; - equals(other: LatLngBounds): boolean; + equals(other: LatLngBounds|LatLngBoundsLiteral): boolean; extend(point: LatLng): LatLngBounds; getCenter(): LatLng; getNorthEast(): LatLng; getSouthWest(): LatLng; - intersects(other: LatLngBounds): boolean; + intersects(other: LatLngBounds|LatLngBoundsLiteral): boolean; isEmpty(): boolean; toSpan(): LatLng; toString(): string; toUrlValue(precision?: number): string; - union(other: LatLngBounds): LatLngBounds; + union(other: LatLngBounds|LatLngBoundsLiteral): LatLngBounds; } export class Point { diff --git a/grecaptcha/grecaptcha-tests.ts b/grecaptcha/grecaptcha-tests.ts index cfc86e71b6..b252efb04d 100644 --- a/grecaptcha/grecaptcha-tests.ts +++ b/grecaptcha/grecaptcha-tests.ts @@ -2,8 +2,9 @@ var params: ReCaptchaV2.Parameters = { "sitekey": "mySuperSecretKey", - "theme": "black", // no type-checking here. + "theme": "light", "type": "image", + "size": "normal", "tabindex": 5, "callback": (response: string) => { }, "expired-callback": () => { }, diff --git a/grecaptcha/grecaptcha.d.ts b/grecaptcha/grecaptcha.d.ts index 8e3b744d53..c8f165a8f8 100644 --- a/grecaptcha/grecaptcha.d.ts +++ b/grecaptcha/grecaptcha.d.ts @@ -29,6 +29,10 @@ declare namespace ReCaptchaV2 getResponse(opt_widget_id?: number): string; } + type Theme = "light" | "dark"; + type Type = "image" | "audio"; + type Size = "normal" | "compact"; + interface Parameters { /** @@ -39,14 +43,23 @@ declare namespace ReCaptchaV2 * Optional. The color theme of the widget. * Accepted values: "light", "dark" * @default "light" + * @type {Theme} **/ - theme?: string; + theme?: Theme; /** * Optional. The type of CAPTCHA to serve. - * Accepted values: "audio ", "image" + * Accepted values: "audio", "image" * @default "image" + * @type {Type} **/ - type?: string; + type?: Type; + /** + * Optional. The size of the widget. + * Accepted values: "compact", "normal" + * @default "compact" + * @type {Size} + */ + size?: Size; /** * Optional. The tabindex of the widget and challenge. * If other elements in your page use tabindex, it should be set to make user navigation easier. diff --git a/gulp-help-doc/gulp-help-doc-tests.ts b/gulp-help-doc/gulp-help-doc-tests.ts new file mode 100644 index 0000000000..f06c25e55c --- /dev/null +++ b/gulp-help-doc/gulp-help-doc-tests.ts @@ -0,0 +1,27 @@ +/// +/// +/// + +import gulp = require('gulp'); +import usage = require('gulp-help-doc'); + +/** + * Demo task + * + * @task {demo} + * @arg {env} environment + */ +gulp.task('demo', function() {}); + +let logger: { + output: string, + log(msg: string): any +} = { + output: '', + log: msg => logger.output += msg + '\n' +}; + +usage(gulp, { + logger: logger, + gulpfile: __filename +}).then(() => console.log(logger.output)); diff --git a/gulp-help-doc/gulp-help-doc.d.ts b/gulp-help-doc/gulp-help-doc.d.ts new file mode 100644 index 0000000000..80d4922774 --- /dev/null +++ b/gulp-help-doc/gulp-help-doc.d.ts @@ -0,0 +1,56 @@ +// Type definitions for gulp-help-doc +// Project: https://github.com/Mikhus/gulp-help-doc +// Definitions by: Mikhus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module "gulp-help-doc" { + + import gulp = require('gulp'); + + namespace usage { + + interface UsageOptions { + /** + * Defines max line width for the printed output lines + * (by default is 80 characters long) + */ + lineWidth?: number, + + /** + * Defines max width of the column width tasks or args names + * (by default is 20 characters long) + */ + keysColumnWidth?: number, + + /** + * Defines number of empty characters for left-padding of the output + */ + padding?: number, + + /** + * Printing engine (by default is console). Accepted any device + * which has log() function defined to do output. + */ + logger?: { log: Function }, + + /** + * Path to a gulpfile (default is gulpfile.js) + * Normally, there is no need to change this option. It may be used + * for some special cases, like mocking gulpfile for testing. + */ + gulpfile?: string + } + + interface Usage { + (gulp: gulp.Gulp, options?: UsageOptions): Promise + } + + } + + var usage: usage.Usage; + + export = usage; +} diff --git a/hapi/hapi-8.2.0.d.ts b/hapi/hapi-8.2.0.d.ts index d205ade2bc..ef81b4fba3 100644 --- a/hapi/hapi-8.2.0.d.ts +++ b/hapi/hapi-8.2.0.d.ts @@ -221,21 +221,7 @@ declare module "hapi" { defaultExtension?: string; } - /** Concludes the handler activity by setting a response and returning control over to the framework where: - erran optional error response. - resultan optional response payload. - Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. - FLOW CONTROL: - When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ - export interface IReply { - (err: Error, - result?: string|number|boolean|Buffer|stream.Stream | Promise | T, - /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ - credentialData?: any - ): IBoom; - /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ - (result?: string|number|boolean|Buffer|stream.Stream | Promise | T): Response; - + interface IReplyMethods { /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. * The data argument is only used for passing back authentication data and is ignored elsewhere. */ continue(credentialData?: any): void; @@ -282,8 +268,39 @@ declare module "hapi" { redirect(uri: string): Response; } + /** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + resultan optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ + export interface IReply extends IReplyMethods{ + (err: Error, + result?: string|number|boolean|Buffer|stream.Stream | Promise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any + ): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result?: string|number|boolean|Buffer|stream.Stream | Promise | T): Response; + } + + /** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + result an optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ + export interface IStrictReply extends IReplyMethods { + (err: Error, + result?: Promise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result: Promise | T): Response; + } export interface ISessionHandler { (request: Request, reply: IReply): void; + (request: Request, reply: IStrictReply): void; } export interface IRequestHandler { (request: Request): T; @@ -868,6 +885,7 @@ declare module "hapi" { }; server.auth.scheme('custom', scheme);*/ authenticate(request: Request, reply: IReply): void; + authenticate(request: Request, reply: IStrictReply): void; /** payload(request, reply) - optional function called to authenticate the request payload where: request - the request object. reply(err, response) - is called if authentication failed where: @@ -876,6 +894,7 @@ declare module "hapi" { reply.continue() - is called if payload authentication succeeded. When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/ payload? (request: Request, reply: IReply): void; + payload?(request: Request, reply: IStrictReply): void; /** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where: request - the request object. reply(err, response) - is called if an error occurred where: @@ -883,6 +902,7 @@ declare module "hapi" { response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required. reply.continue() - is called if the operation succeeded.*/ response? (request: Request, reply: IReply): void; + response?(request: Request, reply: IStrictReply): void; /** an optional object */ options?: { /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/ @@ -1830,6 +1850,7 @@ declare module "hapi" { server.start(); // All requests will get routed to '/test'*/ ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string|string[]; after: string|string[]; bind?: any }): void; + ext(event: string, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; /** server.handler(name, method) Registers a new handler type to be used in routes where: diff --git a/hapi/hapi-tests-8.2.0.ts b/hapi/hapi-tests-8.2.0.ts index c61504f0fc..e26ce193bc 100644 --- a/hapi/hapi-tests-8.2.0.ts +++ b/hapi/hapi-tests-8.2.0.ts @@ -104,5 +104,25 @@ server.route([{ } }]); +server.route([{ + method: 'GET', + path: '/hello4', + handler: function (request: Hapi.Request, reply: Hapi.IReply) { + reply('hello world2'); + } +}]); + +interface IHello { + msg: string +} + +server.route([{ + method: 'GET', + path: '/hello5', + handler: function (request: Hapi.Request, reply: Hapi.IStrictReply) { + reply({ msg: 'hello world' }) + } +}]); + // Start the server server.start(); diff --git a/hapi/hapi-tests.ts b/hapi/hapi-tests.ts index 743a4ad3ee..3288618816 100644 --- a/hapi/hapi-tests.ts +++ b/hapi/hapi-tests.ts @@ -92,6 +92,26 @@ server.route([{ } }]); +server.route([{ + method: 'GET', + path: '/hello3', + handler: function (request: Hapi.Request, reply: Hapi.IReply) { + reply('hello world2'); + } +}]); + +interface IHello { + msg: string +} + +server.route([{ + method: 'GET', + path: '/hello4', + handler: function (request: Hapi.Request, reply: Hapi.IStrictReply) { + reply({ msg: 'hello world' }) + } +}]); + // config.validate parameters should be optional server.route([{ method: 'GET', diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 4a41a8eb84..68f6857110 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -240,21 +240,9 @@ declare module "hapi" { /** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/ defaultExtension?: string; } - - /** Concludes the handler activity by setting a response and returning control over to the framework where: - erran optional error response. - resultan optional response payload. - Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. - FLOW CONTROL: - When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ - export interface IReply { - (err: Error, - result?: string | number | boolean | Buffer | stream.Stream | IPromise | T, - /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ - credentialData?: any): IBoom; - /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ - (result: string | number | boolean | Buffer | stream.Stream | IPromise | T): Response; - + + + interface IReplyMethods { /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. * The data argument is only used for passing back authentication data and is ignored elsewhere. */ continue(credentialData?: any): void; @@ -310,8 +298,39 @@ declare module "hapi" { unstate(name: string, options?: any): void; } + /** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + result an optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ + export interface IReply extends IReplyMethods { + (err: Error, + result?: string | number | boolean | Buffer | stream.Stream | IPromise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result: string | number | boolean | Buffer | stream.Stream | IPromise | T): Response; + } + + /** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + result an optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ + export interface IStrictReply extends IReplyMethods { + (err: Error, + result?: IPromise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result: IPromise | T): Response; + } + export interface ISessionHandler { (request: Request, reply: IReply): void; + (request: Request, reply: IStrictReply): void; } export interface IRequestHandler { (request: Request): T; @@ -926,6 +945,7 @@ declare module "hapi" { }; server.auth.scheme('custom', scheme);*/ authenticate(request: Request, reply: IReply): void; + authenticate(request: Request, reply: IStrictReply): void; /** payload(request, reply) - optional function called to authenticate the request payload where: request - the request object. reply(err, response) - is called if authentication failed where: @@ -934,6 +954,7 @@ declare module "hapi" { reply.continue() - is called if payload authentication succeeded. When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/ payload?(request: Request, reply: IReply): void; + payload?(request: Request, reply: IStrictReply): void; /** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where: request - the request object. reply(err, response) - is called if an error occurred where: @@ -941,6 +962,7 @@ declare module "hapi" { response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required. reply.continue() - is called if the operation succeeded.*/ response?(request: Request, reply: IReply): void; + response?(request: Request, reply: IStrictReply): void; /** an optional object */ options?: { /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/ @@ -2018,6 +2040,7 @@ declare module "hapi" { server.start(); // All requests will get routed to '/test'*/ ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: string, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; /** server.handler(name, method) Registers a new handler type to be used in routes where: diff --git a/hellojs/hellojs.d.ts b/hellojs/hellojs.d.ts index 686d5c1adf..8f0a9e9caa 100644 --- a/hellojs/hellojs.d.ts +++ b/hellojs/hellojs.d.ts @@ -18,7 +18,45 @@ interface HelloJSLogoutOptions { force?: boolean; } -interface HelloJSEvent { +interface HelloJSImmediateSuccessCB { + (value: T): TP; +} + +interface HelloJSImmediateErrorCB { + (err: any): TP; +} + +interface HelloJSDeferredSuccessCB { + (value: T): HelloJSThenable; +} + +interface HelloJSDeferredErrorCB { + (error: any): HelloJSThenable; +} + +interface HelloJSThenable { + then( + successCB?: HelloJSDeferredSuccessCB, + errorCB?: HelloJSDeferredErrorCB + ): HelloJSThenable; + + then( + successCB?: HelloJSDeferredSuccessCB, + errorCB?: HelloJSImmediateErrorCB + ): HelloJSThenable; + + then( + successCB?: HelloJSImmediateSuccessCB, + errorCB?: HelloJSDeferredErrorCB + ): HelloJSThenable; + + then( + successCB?: HelloJSImmediateSuccessCB, + errorCB?: HelloJSImmediateErrorCB + ): HelloJSThenable; +} + +interface HelloJSEvent extends HelloJSThenable { on(event: string, callback: (auth: HelloJSEventArgument) => void): HelloJSStatic; off(event: string, callback: (auth: HelloJSEventArgument) => void): HelloJSStatic; findEvents(event: string, callback: (name: string, index: number) => void): void; @@ -30,15 +68,17 @@ interface HelloJSEvent { } + interface HelloJSEventArgument { network: string; authResponse?: any; } + interface HelloJSStatic extends HelloJSEvent { init(serviceAppIds: { [id: string]: string; }, options?: HelloJSLoginOptions): void; - login(network: string, options?: HelloJSLoginOptions, callback?: () => void): void; - logout(network: string, options?: HelloJSLogoutOptions, callback?: () => void): void; + login(network: string, options?: HelloJSLoginOptions, callback?: () => void): HelloJSStatic; + logout(network: string, options?: HelloJSLogoutOptions, callback?: () => void): HelloJSStatic; getAuthResponse(network: string): any; service(network: string): HelloJSServiceDef; settings: HelloJSLoginOptions; @@ -50,7 +90,7 @@ interface HelloJSStaticNamed { login(option?: HelloJSLoginOptions, callback?: () => void): void; logout(callback?: () => void): void; getAuthResponse(): any; - api(path?: string, method?: string, data?: any, callback?: (json?: any) => void): HelloJSStatic; + api(path?: string, method?: string, data?: any, callback?: (json?: any) => void): HelloJSStatic; } interface HelloJSOAuthDef { diff --git a/highcharts/highcharts-tests.ts b/highcharts/highcharts-tests.ts index 499dfc9494..d8b74de31e 100644 --- a/highcharts/highcharts-tests.ts +++ b/highcharts/highcharts-tests.ts @@ -2258,6 +2258,7 @@ function test_PointObject() { var point = $('#container').highcharts().get('point1'); var category = point.category; var percentage = point.percentage; + point.index; point.remove(); point.remove(false); point.remove(false, {duration: 50}); diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index 45f69a0bda..4ea165814f 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Highcharts 4.1.9 +// Type definitions for Highcharts 4.2.5 // Project: http://www.highcharts.com/ // Definitions by: Damiano Gambarotto , Dan Lewi Harkestad // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -4817,6 +4817,17 @@ interface HighchartsPlotOptions { */ interface HighchartsIndividualSeriesOptions { type?: string; + /** + * The main color or the series. In line type series it applies to the line and the point markers unless otherwise + * specified. In bar type series it applies to the bars unless a color is specified per point. The default + * value is pulled from the options.colors array. + */ + color?: string; + /** + * You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user + * that the points and lines can be clicked. + */ + cursor?: string; /** * An array of data points for the series. For the area series type, points can be given in the following ways: * @@ -4867,6 +4878,11 @@ interface HighchartsIndividualSeriesOptions { * The name of the series as shown in the legend, tooltip etc. */ name?: string; + /** + * A pixel value specifying a fixed width for each column or bar. When null, the width is calculated from + * the pointPadding and groupPadding. + */ + pointWidth?: number; /** * This option allows grouping series in a stacked chart. The stack option can be a string or a number or anything * else, as long as the grouped series' stack options match each other. @@ -5472,12 +5488,12 @@ interface HighchartsOptions { * The X axis or category axis. Normally this is the horizontal axis, though if the chart is inverted this is the * vertical axis. In case of multiple axes, the xAxis node is an array of configuration objects. */ - xAxis?: HighchartsAxisOptions | HighchartsAxisOptions[]; + xAxis?: HighchartsAxisOptions[] | HighchartsAxisOptions; /** * The Y axis or value axis. Normally this is the vertical axis, though if the chart is inverted this is the * horizontal axis. In case of multiple axes, the yAxis node is an array of configuration objects. */ - yAxis?: HighchartsAxisOptions | HighchartsAxisOptions[]; + yAxis?: HighchartsAxisOptions[] | HighchartsAxisOptions; } interface HighchartsGlobalOptions extends HighchartsOptions { @@ -6037,7 +6053,7 @@ interface HighchartsStatic { * throughout the page's lifetime. When a chart is destroyed, the array item becomes undefined. * @since 2.3.4 */ - charts: HighchartsChart[]; + charts: HighchartsChartObject[]; /** * Formats a JavaScript date timestamp (milliseconds since Jan 1st 1970) into a human readable date string. The * format is a subset of the formats for PHP's strftime function. Additional formats can be given in the @@ -6098,6 +6114,7 @@ interface HighchartsPointObject { */ category: string | number; name: string; + index: number; /** * The percentage for points in a stacked series or pies. * @since 1.2.0 diff --git a/html-webpack-plugin/html-webpack-plugin-tests.ts b/html-webpack-plugin/html-webpack-plugin-tests.ts new file mode 100644 index 0000000000..9aac8c9b98 --- /dev/null +++ b/html-webpack-plugin/html-webpack-plugin-tests.ts @@ -0,0 +1,18 @@ +/// + +import {Configuration} from "webpack"; +import HtmlWebpackPlugin = require("html-webpack-plugin"); + +const a: Configuration = { + plugins: [ + new HtmlWebpackPlugin() + ] +}; + +const b: Configuration = { + plugins: [ + new HtmlWebpackPlugin({ + title: "test" + }) + ] +}; diff --git a/html-webpack-plugin/html-webpack-plugin.d.ts b/html-webpack-plugin/html-webpack-plugin.d.ts new file mode 100644 index 0000000000..59917abf62 --- /dev/null +++ b/html-webpack-plugin/html-webpack-plugin.d.ts @@ -0,0 +1,89 @@ +// Type definitions for html-webpack-plugin v2.22.2 +// Project: https://github.com/ampedandwired/html-webpack-plugin +// Definitions by: Simon Hartcher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "html-webpack-plugin" { + import {Plugin} from "webpack"; + + interface HtmlWebpackPluginConfiguration { + /** + * The title to use for the generated HTML document. + */ + title?: string; + + /** + * The file to write the HTML to. Defaults to index.html. You can specify a subdirectory here too (eg: `assets/admin.html`). + */ + filename?: string; + + /** + * Webpack require path to the template. Please see the docs for details. + */ + template?: string; + + /** + * `true | 'head' | 'body' | false` + * + * Inject all assets into the given template or templateContent - When passing true or 'body' all javascript resources will be placed at the bottom of the body element. 'head' will place the scripts in the head element. + */ + inject?: boolean | "head" | "body"; + + /** + * Adds the given favicon path to the output html. + */ + favicon?: string; + + /** + * Pass a html-minifier options object to minify the output. + * + * https://github.com/kangax/html-minifier#options-quick-reference + */ + minify?: any; + + /** + * `true | false` if `true` then append a unique webpack compilation hash to all included scripts and css files. This is useful for cache busting. + */ + hash?: boolean; + + /** + * `true | false` if `true` (default) try to emit the file only if it was changed. + */ + cache?: boolean; + + /** + * `true | false` if `true` (default) errors details will be written into the html page. + */ + showErrors?: boolean; + + /** + * Allows you to add only some chunks (e.g. only the unit-test chunk) + */ + chunks?: string[]; + + /** + * Allows to control how chunks should be sorted before they are included to the html. Allowed values: `'none' | 'auto' | 'dependency' | {function}` - default: `'auto'` + */ + chunksSortMode?: "none" | "auto" | "dependency" | Function; + + /** + * Allows you to skip some chunks (e.g. don't add the unit-test chunk) + */ + excludeChunks?: string[]; + + /** + * `true | false` If `true` render the link tags as self-closing, XHTML compliant. Default is `false` + */ + xhtml?: boolean; + } + + interface HtmlWebpackPlugin { + new (): Plugin; + new (options: HtmlWebpackPluginConfiguration): Plugin; + } + + const htmlWebpackPlugin: HtmlWebpackPlugin; + export = htmlWebpackPlugin; +} diff --git a/i18next-browser-languagedetector/i18next-browser-languagedetector.d.ts b/i18next-browser-languagedetector/i18next-browser-languagedetector.d.ts index cef510304e..a00acb2265 100644 --- a/i18next-browser-languagedetector/i18next-browser-languagedetector.d.ts +++ b/i18next-browser-languagedetector/i18next-browser-languagedetector.d.ts @@ -3,7 +3,6 @@ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// /// declare namespace I18next { @@ -81,8 +80,6 @@ declare namespace i18nextBrowserLanguageDetector { } declare module "i18next-browser-languagedetector" { - import * as express from "express"; - import * as i18next from "i18next"; export default i18nextBrowserLanguageDetector.LngDetector; } diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index 5e2f8dcd20..5ced8aecdb 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -39,15 +39,15 @@ declare namespace I18next { count?: number; context?: any; replace?: any; - lng?:string; - lngs?:string[]; - fallbackLng?:string; - ns?:string|string[]; - keySeparator?:string; - nsSeparator?:string; - returnObjects?:boolean; - joinArrays?:string; - postProcess?:string|any[]; + lng?: string; + lngs?: string[]; + fallbackLng?: string; + ns?: string | string[]; + keySeparator?: string; + nsSeparator?: string; + returnObjects?: boolean; + joinArrays?: string; + postProcess?: string | any[]; interpolation?: InterpolationOptions; } @@ -56,10 +56,10 @@ declare namespace I18next { resources?: ResourceStore; lng?: string; fallbackLng?: string; - ns?: string|string[]; + ns?: string | string[]; defaultNS?: string; - fallbackNS?: string|string[]; - whitelist?:string[]; + fallbackNS?: string | string[]; + whitelist?: string[]; lowerCaseLng?: boolean; load?: string preload?: string[]; @@ -69,61 +69,72 @@ declare namespace I18next { contextSeparator?: string; saveMissing?: boolean; saveMissingTo?: string; - missingKeyHandler?: (lng:string, ns:string, key:string, fallbackValue:string) => void; - parseMissingKeyHandler?: (key:string) => void; + missingKeyHandler?: (lng: string, ns: string, key: string, fallbackValue: string) => void; + parseMissingKeyHandler?: (key: string) => void; appendNamespaceToMissingKey?: boolean; - postProcess?: string|any[]; + postProcess?: string | any[]; returnNull?: boolean; returnEmptyString?: boolean; returnObjects?: boolean; - returnedObjectHandler?: (key:string, value:string, options:any) => void; + returnedObjectHandler?: (key: string, value: string, options: any) => void; joinArrays?: string; - overloadTranslationOptionHandler?: (args:any[]) => TranslationOptions; + overloadTranslationOptionHandler?: (args: any[]) => TranslationOptions; interpolation?: InterpolationOptions; detection?: any; backend?: any; cache?: any; } - type TranslationFunction = (key:string, options?:TranslationOptions) => string; + type TranslationFunction = (key: string, options?: TranslationOptions) => string; class I18n { - constructor(options?:Options, callback?:(err:any, t:TranslationFunction) => void); + constructor(options?: Options, callback?: (err: any, t: TranslationFunction) => void); - init(options?:Options, callback?:(err:any, t:TranslationFunction) => void):I18n; + init(options?: Options, callback?: (err: any, t: TranslationFunction) => void): I18n; - loadResources(callback?:(err:any) => void):void; + loadResources(callback?: (err: any) => void): void; - language:string; + language: string; - languages:string[]; + languages: string[]; - use(module:any):I18n; + use(module: any): I18n; - changeLanguage(lng:string, callback?:(err:any, t:TranslationFunction) => void):void; + changeLanguage(lng: string, callback?: (err: any, t: TranslationFunction) => void): void; - getFixedT(lng?:string, ns?:string|string[]):TranslationFunction; + getFixedT(lng?: string, ns?: string | string[]): TranslationFunction; - t(key:string, options?:TranslationOptions):string|any|Array; + t(key: string, options?: TranslationOptions): string | any | Array; - exists():boolean; + exists(): boolean; - setDefaultNamespace(ns:string):void; + setDefaultNamespace(ns: string): void; - loadNamespaces(ns:string[], callback?:() => void):void; + loadNamespaces(ns: string[], callback?: () => void): void; - loadLanguages(lngs:string[], callback?:()=>void):void; + loadLanguages(lngs: string[], callback?: () => void): void; - dir(lng?:string):string; + dir(lng?: string): string; - createInstance(options?:Options, callback?:(err:any, t:TranslationFunction) => void):I18n; + createInstance(options?: Options, callback?: (err: any, t: TranslationFunction) => void): I18n; - cloneInstance(options?:Options, callback?:(err:any, t:TranslationFunction) => void):I18n; + cloneInstance(options?: Options, callback?: (err: any, t: TranslationFunction) => void): I18n; + + on(event: string, listener: () => void): void; + on(initialized: 'initialized', listener: (options: I18next.Options) => void): void; + on(loaded: 'loaded', listener: (loaded: any) => void): void; + on(failedLoading: 'failedLoading', listener: (lng: string, ns: string, msg: string) => void): void; + on(missingKey: 'missingKey', listener: (lngs: any, namespace: string, key: string, res: any) => void): void; + on(added: 'added', listener: (lng: string, ns: string) => void): void; + on(removed: 'removed', listener: (lng: string, ns: string) => void): void; + on(languageChanged: 'languageChanged', listener: (lng: string) => void): void; + + off(event: string, listener: () => void): void; } } declare module 'i18next' { - var i18n:I18next.I18n; + var i18n: I18next.I18n; export = i18n; } diff --git a/jasmine-ajax/jasmine-ajax.d.ts b/jasmine-ajax/jasmine-ajax.d.ts index 143b3b1a5c..0eb873e048 100644 --- a/jasmine-ajax/jasmine-ajax.d.ts +++ b/jasmine-ajax/jasmine-ajax.d.ts @@ -73,6 +73,9 @@ declare class MockAjax { stubRequest(url: RegExp, data?: string, method?: string): JasmineAjaxRequestStub; stubRequest(url: string, data?: string, method?: string): JasmineAjaxRequestStub; + + stubRequest(url: RegExp, data?: RegExp, method?: string): JasmineAjaxRequestStub; + stubRequest(url: string, data?: RegExp, method?: string): JasmineAjaxRequestStub; requests: JasmineAjaxRequestTracker; stubs: JasmineAjaxStubTracker; diff --git a/jqgrid/jqgrid-tests.ts b/jqgrid/jqgrid-tests.ts index 6f112d2976..b9012185bc 100644 --- a/jqgrid/jqgrid-tests.ts +++ b/jqgrid/jqgrid-tests.ts @@ -2,5 +2,25 @@ // Definitions by: Lokesh Peta // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// \ No newline at end of file +/// +/// + +var mydata: any[] = []; + +$('#jqGrid') + .jqGrid({ + datatype: 'local', + data: mydata, + loadonce: true, + gridview: true, + height: 400, + shrinkToFit: true, + width: null, + colModel: [ + { label: 'Name', name: 'id', width: 75, key: true, align: 'left' }, + { label: 'Description', name: 'description', width: 100 } + ], + viewrecords: true, // show the current page, data rang and total records on the toolbar + caption: 'Matches', + onSelectRow(id: any, status: any, e: Event) { } + }); diff --git a/jqgrid/jqgrid.d.ts b/jqgrid/jqgrid.d.ts index 82807282a0..6b7d4cb2e0 100644 --- a/jqgrid/jqgrid.d.ts +++ b/jqgrid/jqgrid.d.ts @@ -4,44 +4,337 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// + +// http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options interface JQueryJqGridColumn { - name: string; - index: string; + + /** + * Defines the alignment of the cell in the Body layer, not in header cell. Possible values: left, center, right + */ + align?: "left" | "center" | "right"; + + /** + * This function add attributes to the cell during the creation of the data - i.e dynamically. + * By example all valid attributes for the table cell can be used or a style attribute with different properties. + * @param rowId the id of the row + * @param val the value which will be added in the cell + * @param rowObject the raw object of the data row - i.e if datatype is json - array, if datatype is xml xml node. + * @param cm all the properties of this column listed in the colModel + * @param rdata the data row which will be inserted in the row. This parameter is array of type name:value, where name is the name in colModel + * @returns {} + */ + cellattr?: (rowId: any, val: any, rowObject: any, cm: any, rdata: any) => string; + + /** + * This option allow to add classes to the column. If more than one class will be used a space should be set. + * By example classes:'class1 class2' will set a class1 and class2 to every cell on that column. + * In the grid css there is a predefined class ui-ellipsis which allow to attach ellipsis to a particular row. + * Also this will work in FireFox too. + */ + classes?: string; + + /** + * Governs format of sorttype:date (when datetype is set to local) and editrules {date:true} fields. + * Determines the expected date format for that column. Uses a PHP-like date formatting. Currently "/", "-", and "." are supported as date separators. Valid formats are: + * y,Y,yyyy for four digits year + * YY, yy for two digits year + * m,mm for months + * d,dd for days. + */ + datefmt?: string; + + /** + * Defines if the field is editable. This option is used in cell, inline and form modules. + */ + editable?: boolean; + + /** + * The predefined types (string) or custom function name that controls the format of this field + * @param cellvalue is the value to be formatted + * @param options is an object containing the following element: rowId - is the id of the row colModel is the object of the properties for this column getted from colModel array of jqGrid + * @param rowObject is a row data represented in the format determined from datatype option. If we have datatype: xml/xmlstring - the rowObject is xml node,provided according to the rules from xmlReader If we have datatype: json/jsonstring - the rowObject is array, provided according to the rules from jsonReader + * @returns {} the formatted value + */ + formatter?: "integer" | "number" | "currency" | "date" | "email" | "link" | "showlink" | "checkbox" | "select" | "actions" | ((cellvalue: any, options: { rowId: any, colModel: any }, rowObject: any) => any); + + /** + * Defines if this column is hidden at initialization. + */ hidden?: boolean; - sortable?: boolean; + + /** + * Set the index name when sorting. Passed as sidx parameter. + */ + index?: string; + + /** + * Overwrite the id (defined in readers) from server. Can be set as id for the unique row id. Only one column can have this property. + * This option have higher priority as those from the readers. + * If there are more than one key set the grid finds the first one and the second is ignored. + */ + key?: boolean; + + /** + * When colNames array is empty, defines the heading for this column. + * If both the colNames array and this setting are empty, the heading for this column comes from the name property. + */ + label?: string; + + /** + * Set the unique name in the grid for the column. + * This property is required. + * As well as other words used as property/event names, the reserved words (which cannot be used for names) include subgrid, cb and rn. + */ + name: string; + + /** + * When used in search modules, disables or enables searching on that column + */ search?: boolean; + + /** + * Defines is this can be sorted + */ + sortable?: boolean; + + /** + * Set the initial width of the column, in pixels. This value currently can not be set as percentage + */ width?: number; - formatter?: (cellvalue: any, options: any, rowObject: any) => any; } interface IJqGridJsonReader { + /** + * tells jqGrid that the information for the data in the row is repeatable - i.e. the elements have the same tag cell described in cell element. Setting this option to false instructs jqGrid to search elements in the json data by name. + * This is the name from colModel or the name described with the jsonmap option in colModel + */ repeatitems: boolean; - root(obj: any): any; - page(obj: any): any; - total(obj: any): number; - records(obj: {data: any[]}): number; + + /** + * Name of the root property + * @param obj + * @returns {} + */ + root: string | ((obj: any) => any); + + /** + * current page of the query + * @param obj + * @returns {} + */ + page: string | ((obj: any) => number); + + /** + * total pages for the query + * @param obj + * @returns {} + */ + total: string | ((obj: any) => number); + + /** + * total number of records for the query + * @param obj + * @returns {} + */ + records: string | ((obj: {data: any[]}) => number); } interface JQueryJqGridOptions { - datatype?: string; - mtype?: string; + /** + * When set to true encodes (html encode) the incoming (from server) and posted data (from editing modules). + */ autoencode?: boolean; - pager?: string; - rowNum?: number; - rowList?: number[]; - colNames?: string[]; + + /** + * When set to true, the grid width is recalculated automatically to the width of the parent element. + * This is done only initially when the grid is created. + * In order to resize the grid when the parent element changes width you should apply custom code and use the setGridWidth method for this purpose + */ + autoWidth?: boolean; + + /** + * Defines the caption for the grid. This caption appears in the caption layer, which is above the header layer + */ + caption?: string; + + /** + * Array which describes the parameters of the columns. This is the most important part of the grid. + */ colModel?: JQueryJqGridColumn[]; - sortname?: string; - sortorder?: string; - multiselect?: boolean; - multiboxonly?: boolean; + + /** + * An array in which we place the names of the columns. + * This is the text that appears in the head of the grid (header layer). The names are separated with commas. + * Note that the number of elements in this array should be equal of the number elements in the colModel array. + */ + colNames?: string[]; + + /** + * An array that stores the local data passed to the grid. You can directly point to this variable in case you want to load an array data. + * It can replace the addRowData method which is slow on relative big data + */ + data?: any[]; + + /** + * Defines in what format to expect the data that fills the grid. + * Valid options are xml (we expect data in xml format), xmlstring (we expect xml data as string), json (we expect data in JSON format), + * jsonstring (we expect JSON data as a string), local (we expect data defined at client side (array data)), + * javascript (we expect javascript as data), function (custom defined function for retrieving data), + * or clientSide to manually load data via the data array + */ + datatype?: "xml" | "xmlstring" | "json" | "jsonstring" | "local" | "javascript" | Function | "clientSide"; + + /** + * If set to true, and a column's width is changed, the adjacent column (to the right) will resize so that the overall grid width is maintained + * (e.g., reducing the width of column 2 by 30px will increase the size of column 3 by 30px). In this case there is no horizontal scrollbar. + * Note: This option is not compatible with shrinkToFit option - i.e if shrinkToFit is set to false, forceFit is ignored. + */ forceFit?: boolean; - height?: number; - width?: number; - shrinkToFit?: boolean; - url?: string; + /** + * What will be the result if we insert all the data at once? + * Yes, this can be done with a help of gridview option (set it to true). + * The result is a grid that is 5 to 10 times faster. Of course, when this option is set to true we have some limitations. + * If set to true we can not use treeGrid, subGrid, or the afterInsertRow event. + * If you do not use these three options in the grid you can set this option to true and enjoy the speed. + */ + gridview?: boolean; + + /** + * The height of the grid. + * Can be set as number (in this case we mean pixels) or as percentage (only 100% is accepted) or value of auto is acceptable. + */ + height?: number | string | "auto"; + + /** + * If this flag is set to true, the grid loads the data from the server only once (using the appropriate datatype). + * After the first request, the datatype parameter is automatically changed to local and all further manipulations are done on the client side. + * The functions of the pager (if present) are disabled. + */ + loadonce?: boolean; + + /** + * An array which describes the structure of the expected json data. + */ jsonReader?: IJqGridJsonReader; - gridComplete?:()=>void; + + /** + * Defines the type of request to make ("POST" or "GET") + */ + mtype?: "GET" | "POST"; + + /** + * This option works only when the multiselect option is set to true. + * When multiselect is set to true, clicking anywhere on a row selects that row; + * when multiboxonly is also set to true, the multiselection is done only when the checkbox is clicked (Yahoo style). + * Clicking in any other row (suppose the checkbox is not clicked) deselects all rows and selects the current row. + */ + multiboxonly?: boolean; + + /** + * If this flag is set to true a multi selection of rows is enabled. A new column at left side containing checkboxes is added. + * Can be used with any datatype option + */ + multiselect?: boolean; + + /** + * Defines that we want to use a pager bar to navigate through the records. + * This must be a valid HTML element; in our example we gave the div the id of "pager", but any name is acceptable. + * Note that the navigation layer (the "pager" div) can be positioned anywhere you want, determined by your HTML; + * in our example we specified that the pager will appear after the body layer. + * The valid settings can be (in the context of our example) pager, #pager, jQuery('#pager'). + * I recommend to use the second one - #pager + */ + pager?: string; + + /** + * An array to construct a select box element in the pager in which we can change the number of the visible rows. + * When changed during the execution, this parameter replaces the rowNum parameter that is passed to the url. + * If the array is empty, this element does not appear in the pager. Typically you can set this like [10,20,30]. + * If the rowNum parameter is set to 30 then the selected value in the select box is 30 + */ + rowList?: number[]; + + /** + * Sets how many records we want to view in the grid. This parameter is passed to the url for use by the server routine retrieving the data. + * Note that if you set this parameter to 10 (i.e. retrieve 10 records) and your server return 15 then only 10 records will be loaded + */ + rowNum?: number; + + /** + * This option, if set, defines how the the width of the columns of the grid should be re-calculated, taking into consideration the width of the grid. + * If this value is true, and the width of the columns is also set, then every column is scaled in proportion to its width. + * For example, if we define two columns with widths 80 and 120 pixels, but want the grid to have a width of 300 pixels, + * then the columns will stretch to fit the entire grid, and the extra width assigned to them will depend on the width of the columns themselves and the extra width available. + * The re-calculation is done as follows: the first column gets the width (300(new width)/200(sum of all widths))*80(first column width) = 120 pixels, + * and the second column gets the width (300(new width)/200(sum of all widths))*120(second column width) = 180 pixels. + * Now the widths of the columns sum up to 300 pixels, which is the width of the grid. + * If the value is false and the value in width option is set, then no re-sizing happens whatsoever. + * So in this example, if shrinkToFit is set to false, column one will have a width of 80 pixels, + * column two will have a width of 120 pixels and the grid will retain the width of 300 pixels. + * If the value of shrinkToFit is an integer, the width is calculated according to it. + */ + shrinkToFit?: boolean | number; + + /** + * The column according to which the data is to be sorted when it is initially loaded from the server + * (note that you will have to use datatypes xml or json to load remote data). This parameter is appended to the url. + * If this value is set and the index (name) matches the name from colModel, + * then an icon indicating that the grid is sorted according to this column is added to the column header. + * This icon also indicates the sorting order - descending or ascending (see the parameter sortorder). Also see prmNames + */ + sortname?: string; + + /** + * The initial sorting order (ascending or descending) when we fetch data from the server using datatypes xml or json. + * This parameter is appended to the url - see prnNames. The two allowed values are - asc or desc. + */ + sortorder?: "asc" | "desc"; + + /** + * The url of the file that returns the data needed to populate the grid. May be set to clientArray to manualy post data to server + */ + url?: string | "clientArray"; + + /** + * If true, jqGrid displays the beginning and ending record number in the grid, out of the total number of records in the query. + * This information is shown in the pager bar (bottom right by default)in this format: "View X to Y out of Z". + * If this value is true, there are other parameters that can be adjusted, including emptyrecords and recordtext. + */ + viewrecords?: boolean; + + /** + * If this option is not set, the width of the grid is the sum of the widths of the columns defined in the colModel (in pixels). + * If this option is set, the initial width of each column is set according to the value of the shrinkToFit option. + */ + width?: number; + + // events + + /** + * This fires after all the data is loaded into the grid and all other processes are complete. + * Also the event fires independent from the datatype parameter and after sorting paging and etc. + * @returns {} + */ + gridComplete?: () => void; + + /** + * Raised immediately after row was right clicked + * @param rowid is the id of the row + * @param iRow is the index of the row (do not mix this with the rowid) + * @param iCol is the index of the cell + * @param e is the event object + * @returns {} + */ + onRightClickRow?: (rowid: any, iRow: number, iCol: number, e: Event) => void; + + /** + * Raised immediately after row was clicked. + * @param id is the id of the row + * @param status is the status of the selection + * @param e is the event object. Can be used when multiselect is set to true. true if the row is selected, false if the row is deselected. + * @returns {} + */ + onSelectRow?: (id: string, status: any, e: Event) => void; } interface JQueryJqGridStatic { @@ -60,5 +353,64 @@ interface JQueryStatic { interface JQuery { jqGrid?: JQueryJqGridStatic; + /** + * Populates a grid with the passed data (an array) + * @param data + * @returns {} + */ + addJSONData(data: any[]): void; + + /** + * Edits the row specified by rowid. + * keys is a boolean value, indicating if to use the Enter key to accept the value ane Esc to cancel the edit, or not. + * @param rowid the id of the row to edit + * @param keys when set to true we can use [Enter] key to save the row and [Esc] to cancel editing + * @returns {} + */ + editRow(rowid: any, keys?: boolean): void; + + /** + * Returns the value of the requested parameter. name is the name from the options array. If the name is not set, the entry options are returned. + * @param name + * @returns {} + */ + getGridParam(name: string): any; + + /** + * This method restores the data to original values before the editing of the row + * @param rowId the row to restore + * @param afterRestoreFunc if defined this function is called in after the row is restored. + * @returns {} + */ + restoreRow(rowId: any, afterRestoreFunc?: (response: any) => void): void; + + /** + * Saves the edited row. + * @param rowid the id of the row to save + * @param successfunc + * @param url if defined, this parameter replaces the editurl parameter from the options array. If set to 'clientArray', the data is not posted to the server but rather is saved only to the grid (presumably for later manual saving). + * @param extraparam an array of type name: value. When set these values are posted along with the other values to the server. + * @returns {} + */ + saveRow(rowid: string, successfunc?: (response: any) => boolean, url?: string, extraparam?: any): void; + + /** + * Saves the edited row. + * @param rowid the id of the row to save + * @param successfunc + * @param url + * @param extraparam + * @returns {} + */ + saveRow(rowid: string, successfunc?: boolean, url?: string, extraparam?: any): void; + + /** + * Sets a particular parameter. + * Note - for some parameters to take effect a trigger("reloadGrid") should be executed. + * Note that with this method we can override events. + * The name (in the name:value pair) is the name from options array + * @param obj + * @returns {} + */ setGridParam(obj: any): void; } \ No newline at end of file diff --git a/jquery.colorbox/jquery.colorbox.d.ts b/jquery.colorbox/jquery.colorbox.d.ts index 4af0e7e87f..5437c0bf18 100644 --- a/jquery.colorbox/jquery.colorbox.d.ts +++ b/jquery.colorbox/jquery.colorbox.d.ts @@ -252,7 +252,7 @@ interface ColorboxStatic { /** * This method allows you to call Colorbox without having to assign it to an element. */ - (settings: ColorboxSettings); + (settings: ColorboxSettings): any; /** * This method moves to the next item in a group and are the same as pressing the 'next' or 'previous' buttons. */ diff --git a/js-base64/js-base64-test.ts b/js-base64/js-base64-test.ts new file mode 100644 index 0000000000..c10943df2e --- /dev/null +++ b/js-base64/js-base64-test.ts @@ -0,0 +1,12 @@ +/// + +import { Base64 } from 'js-base64' + +Base64.encode('dankogai'); // ZGFua29nYWk= +Base64.encode('小飼弾'); // 5bCP6aO85by+ +Base64.encodeURI('小飼弾'); // 5bCP6aO85by- + +Base64.decode('ZGFua29nYWk='); // dankogai +Base64.decode('5bCP6aO85by+'); // 小飼弾 +// note .decodeURI() is unnecessary since it accepts both flavors +Base64.decode('5bCP6aO85by-'); // 小飼弾 diff --git a/js-base64/js-base64.d.ts b/js-base64/js-base64.d.ts new file mode 100644 index 0000000000..30fd18620d --- /dev/null +++ b/js-base64/js-base64.d.ts @@ -0,0 +1,52 @@ +// Type definitions for js-base64 v2.1.9 +// Project: https://github.com/dankogai/js-base64 +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** +## TODO + +add methods: +- [x] encode +- [x] encodeURI +- [x] decode +- [ ] atob +- [ ] btoa +- [ ] fromBase64 +- [ ] toBase64 +- [ ] utob +- [ ] btou +- [ ] noConflict + */ + +interface Base64 { + /** + * .encode + * @param {String} string + * @return {String} + */ + encode(base64: string): string; + + /** + * .encodeURI + * @param {String} string + * @return {String} + */ + encodeURI(base64: string): string + + /** + * .decode + * @param {String} string + * @return {String} + */ + decode(base64: string): string + + /** + * Library version + */ + VERSION:string +} + +declare module 'js-base64' { + const Base64: Base64 +} \ No newline at end of file diff --git a/js-priority-queue/js-priority-queue-tests.ts b/js-priority-queue/js-priority-queue-tests.ts new file mode 100644 index 0000000000..e63cd0a8b8 --- /dev/null +++ b/js-priority-queue/js-priority-queue-tests.ts @@ -0,0 +1,26 @@ +/// + +import * as PriorityQueue from "js-priority-queue"; + +{ + var queue = new PriorityQueue({ comparator: (a, b) => b - a }); + queue.queue(5); + queue.queue(3); + queue.queue(2); + var lowest = queue.dequeue(); // returns 5 +} +{ + var compareNumbers = (a: number, b: number) => a - b; + new PriorityQueue({ comparator: compareNumbers }); +} +{ + new PriorityQueue({ initialValues: [1, 2, 3] }) +} +{ + new PriorityQueue({ strategy: PriorityQueue.ArrayStrategy }); // Array + new PriorityQueue({ strategy: PriorityQueue.BinaryHeapStrategy }); // Default + new PriorityQueue({ strategy: PriorityQueue.BHeapStrategy }); // Slower +} +{ + var a: PriorityQueue.PriorityQueueOptions; +} diff --git a/js-priority-queue/js-priority-queue.d.ts b/js-priority-queue/js-priority-queue.d.ts new file mode 100644 index 0000000000..dda0c47097 --- /dev/null +++ b/js-priority-queue/js-priority-queue.d.ts @@ -0,0 +1,64 @@ +// Type definitions for js-priority-queue +// Project: https://github.com/adamhooper/js-priority-queue +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* =================== USAGE =================== + import * as PriorityQueue from "js-priority-queue"; + var queue = new PriorityQueue({ comparator: (a, b) => b - a }); + queue.queue(5); + =============================================== */ + +declare module "js-priority-queue" { + class AbstractPriorityQueue { + /** + * Returns the number of elements in the queue + */ + public length: number; + /** + * Creates a priority queue + */ + constructor(options?: PriorityQueue.PriorityQueueOptions); + /** + * Inserts a new value in the queue + */ + public queue(value: T): void; + /** + * Returns the smallest item in the queue and leaves the queue unchanged + */ + public peek(): T; + /** + * Returns the smallest item in the queue and removes it from the queue + */ + public dequeue(): T; + /** + * Removes all values from the queue + */ + public clear(): void; + } + namespace PriorityQueue { + type PriorityQueueOptions = { + /** + * This is the argument we would pass to Array.prototype.sort + */ + comparator?: (a: T, b: T) => number; + /** + * You can also pass initial values, in any order. + * With lots of values, it's faster to load them all at once than one at a time. + */ + initialValues?: T[]; + /** + * According to JsPerf, the fastest strategy for most cases is BinaryHeapStrategy. + * Only use ArrayStrategy only if you're queuing items in a very particular order. + * Don't use BHeapStrategy, except as a lesson in how sometimes miracles in one programming language aren't great in other languages. + */ + strategy?: typeof AbstractPriorityQueue; + } + class ArrayStrategy extends AbstractPriorityQueue{ } + class BinaryHeapStrategy extends AbstractPriorityQueue{ } + class BHeapStrategy extends AbstractPriorityQueue{ } + + } + class PriorityQueue extends AbstractPriorityQueue { } + export = PriorityQueue; +} diff --git a/json-merge-patch/json-merge-patch-tests.ts b/json-merge-patch/json-merge-patch-tests.ts new file mode 100644 index 0000000000..36d0d34a8a --- /dev/null +++ b/json-merge-patch/json-merge-patch-tests.ts @@ -0,0 +1,225 @@ +/// + +import * as jmp from "json-merge-patch"; + +var merge = jmp.merge; +var apply = jmp.apply; +var generate = jmp.generate; +var assert = {deepEqual: function (a: Object, b: Object) { + return JSON.stringify(a) === JSON.stringify(b); +}}; + +assert.deepEqual( + merge({a: 'b'}, {b: 'c'}), + {a: 'b', b: 'c'} +); + +assert.deepEqual( + merge({a: 'b'}, {a: 'c'}), + {a: 'c'} +); + +assert.deepEqual( + merge({a: 'b', b: 'd'}, {a: 'c'}), + {a: 'c', b: 'd'} +); + +assert.deepEqual( + merge({a: null}, {b: 'c'}), + {a: null, b: 'c'} +); + +assert.deepEqual( + merge({a: null}, {a: 'b'}), + {a: 'b'} +); + +assert.deepEqual( + merge({a: 'b'}, {a: null}), + {a: null} +); + +assert.deepEqual( + merge([], {a: 'b'}), + {a: 'b'} +); + +assert.deepEqual( + merge({a: 'b'}, []), + [] +); + +assert.deepEqual( + merge({a: {b: {c: 'd'}}, d: 'e'}, {a: {b: 'a'}}), + {a: {b: 'a'}, d: 'e'} +); + +assert.deepEqual( + merge({a: {b: {c: 'd'}, d: 'e'}}, {a: {b: {c: 'e'}}}), + {a: {b: {c: 'e'}, d: 'e'}} +); + +assert.deepEqual( + merge({a: 'b'}, null), + null +); + +assert.deepEqual( + generate({a: 'b'}, {a: 'c'}), + {a: 'c'} +); + +assert.deepEqual( + generate({a: 'b'}, { a: 'b', b: 'c'}), + {b: 'c'} +); + +assert.deepEqual( + generate({a: 'b'}, {}), + {a: null} +); + +assert.deepEqual( + generate({a: 'b', b: 'c'}, {b: 'c'}), + {a: null} +); + +assert.deepEqual( + generate({a: ['b']}, {a: 'c'}), + {a: 'c'} +); + +assert.deepEqual( + generate({a: 'c'}, {a: ['b']}), + {a: ['b']} +); + +assert.deepEqual( + generate({a: [{b: 'c'}]}, {a: [1]}), + {a: [1]} +); + +assert.deepEqual( + generate(['a', 'b'], ['c', 'd']), + ['c', 'd'] +); + +assert.deepEqual( + generate(['a', 'b'], ['a']), + ['a'] +); + +assert.deepEqual( + generate({a: 'b'}, ['c']), + ['c'] +); + +assert.deepEqual( + generate({a: 'foo'}, null), + null +); + +assert.deepEqual( + generate({a: 'foo'}, 'bar'), + 'bar' +); + +assert.deepEqual( + generate({e: null}, {e: null, a: 1}), + {a: 1} +); + +assert.deepEqual( + generate({}, {a: {bb: {}}}), + {a: {bb: {}}} +); + +assert.deepEqual( + generate({a: 'a'}, {a: 'a'}), + undefined +); + +assert.deepEqual( + generate({a: {b: 'c'}}, {a: {b: 'c'}}), + undefined +); + +assert.deepEqual( + generate([1,2,3], [1,2,3]), + undefined +); + +assert.deepEqual( + apply({a: 'b'}, {a: 'c'}), + {a: 'c'} +); + +assert.deepEqual( + apply({a: 'b'}, {b: 'c'}), + {a: 'b', b: 'c'} +); + +assert.deepEqual( + apply({a: 'b'}, {a: null}), + {} +); + +assert.deepEqual( + apply({a: 'b', b: 'c'}, {a: null}), + {b: 'c'} +); + +assert.deepEqual( + apply({a: ['b']}, {a: 'c'}), + {a: 'c'} +); + +assert.deepEqual( + apply({a: 'c'}, {a: ['b']}), + {a: ['b']} +); + +assert.deepEqual( + apply({a: {b: 'c'}}, {a: {b: 'd', c: null}}), + {a: {b: 'd'}} +); + +assert.deepEqual( + apply({a: [{b: 'c'}]}, {a: [1]}), + {a: [1]} +); + +assert.deepEqual( + apply(['a', 'b'], ['c', 'd']), + ['c', 'd'] +); + +assert.deepEqual( + apply({a: 'b'}, ['c']), + ['c'] +); + +assert.deepEqual( + apply({a: 'foo'}, null), + null +); + +assert.deepEqual( + apply({a: 'foo'}, 'bar'), + 'bar' +); + +assert.deepEqual( + apply({e: null}, {a: 1}), + {e: null, a: 1} +); + +assert.deepEqual( + apply([1, 2], {a: 'b', c: null}), + {a: 'b'} +); + +assert.deepEqual( + apply({}, {a: {bb: {ccc: null}}}), + {a: {bb: {}}} +); \ No newline at end of file diff --git a/json-merge-patch/json-merge-patch.d.ts b/json-merge-patch/json-merge-patch.d.ts new file mode 100644 index 0000000000..bbf7c1d810 --- /dev/null +++ b/json-merge-patch/json-merge-patch.d.ts @@ -0,0 +1,11 @@ +// Type definitions for json-merge-patch +// Project: https://github.com/pierreinglebert/json-merge-patch +// Definitions by: Arsenij Schuetzer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "json-merge-patch" { + function apply(target: Object, patch: Object): Object; + function generate(before: Object, after: Object): Object; + function merge(patch1: Object, patch2: Object): Object; +} \ No newline at end of file diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index a7a0417cc4..04ba8409ee 100644 --- a/knex/knex-tests.ts +++ b/knex/knex-tests.ts @@ -57,6 +57,19 @@ var knex = Knex({ } }); +// acquireConnectionTimeout +var knex = Knex({ + debug: true, + client: 'mysql', + connection: { + socketPath : '/path/to/socket.sock', + user : 'your_database_user', + password : 'your_database_password', + database : 'myapp_test' + }, + acquireConnectionTimeout: 60000, +}); + // Pure Query Builder without a connection var knex = Knex({}); diff --git a/knex/knex.d.ts b/knex/knex.d.ts index bb6395807e..a8501f2e51 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -453,6 +453,7 @@ declare module "knex" { Sqlite3ConnectionConfig|SocketConnectionConfig; pool?: PoolConfig; migrations?: MigratorConfig; + acquireConnectionTimeout?: number; } interface ConnectionConfig { diff --git a/koa-static/koa-static.d.ts b/koa-static/koa-static.d.ts index 4b95eca3be..feba76fb8d 100644 --- a/koa-static/koa-static.d.ts +++ b/koa-static/koa-static.d.ts @@ -46,6 +46,6 @@ declare module "koa-static" { */ gzip?: boolean; }): { (ctx: Koa.Context, next?: () => any): any }; - + namespace serve{} export = serve; } diff --git a/lodash/lodash-3.10.d.ts b/lodash/lodash-3.10.d.ts index eca84d937f..aea06a8362 100644 --- a/lodash/lodash-3.10.d.ts +++ b/lodash/lodash-3.10.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Lo-Dash +// Type definitions for Lo-Dash 3.10 // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 35c6611596..52f274fd3c 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Lo-Dash +// Type definitions for Lo-Dash 4.14 // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/mainloop.js/mainloop.js-tests.ts b/mainloop.js/mainloop.js-tests.ts new file mode 100644 index 0000000000..86a4db6240 --- /dev/null +++ b/mainloop.js/mainloop.js-tests.ts @@ -0,0 +1,95 @@ +/// + +// To see what this test does, create an HTML file with these contents and open it: +/* + + + + + + + MainLoop.js test + + + + + + + + + + +*/ + +window.addEventListener('load', () => { + + let cx = window.innerWidth / 2 - 15, + cy = window.innerHeight / 2 - 15, + x = cx + 120, + y = cy, + lx = x, + ly = y, + theta = 0 + const radius = 120, + velocity = 0.1 * Math.PI / 180; + + const actor = document.createElement('div'); + actor.style.width = '30px'; + actor.style.height = '30px'; + actor.style.backgroundColor = 'red'; + actor.style.position = 'absolute'; + actor.style.left = x + 'px'; + actor.style.top = y + 'px'; + + document.body.appendChild(actor); + + const fpsCounter = document.createElement('div'); + fpsCounter.style.position = 'absolute'; + fpsCounter.style.left = '10px'; + fpsCounter.style.top = '10px'; + + document.body.appendChild(fpsCounter); + + document.body.addEventListener('click', (event) => { + cx = event.pageX; + cy = event.pageY; + }); + + MainLoop + .setBegin((timestamp, delta) => { + lx = x; + ly = y; + x = cx + Math.cos(theta) * radius; + y = cy + Math.sin(theta) * radius; + }) + .setDraw((interpolationPercentage) => { + actor.style.left = (lx + (x - lx) * interpolationPercentage) + 'px'; + actor.style.top = (ly + (y - ly) * interpolationPercentage) + 'px'; + }) + .setUpdate((delta) => { + theta += velocity * delta; + }) + .setEnd((fps, panic) => { + fpsCounter.textContent = Math.round(fps) + ' FPS'; + if (panic) { + console.info( + `Main loop panicked; tried to simulate too much time. Discarding ${MainLoop.resetFrameDelta()}ms` + ); + } + }) + .start(); + + document.body.addEventListener('keyup', (event) => { + if ((event.which || event.keyCode) === 80) { // Hit P to toggle Pause + if (MainLoop.isRunning()) { + MainLoop.stop(); + } + else { + MainLoop.start(); + } + } + }); + +}); diff --git a/mainloop.js/mainloop.js.d.ts b/mainloop.js/mainloop.js.d.ts new file mode 100644 index 0000000000..f34d6f035a --- /dev/null +++ b/mainloop.js/mainloop.js.d.ts @@ -0,0 +1,28 @@ +// Type definitions for MainLoop.js v1.0.3 +// Project: https://github.com/IceCreamYou/MainLoop.js +// Definitions by: Isaac Sukin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Interface for the MainLoop.js global. + * + * See the API documentation for a detailed explanation of these methods: + * http://icecreamyou.github.com/MainLoop.js/docs/#!/api/MainLoop + */ +interface MainLoop { + getFPS(): number; + getMaxAllowedFPS(): number; + getSimulationTimestep(): number; + isRunning(): boolean; + resetFrameDelta(): number; + setBegin(begin: (timestamp: number, delta: number) => void): MainLoop; + setDraw(draw: (interpolationPercentage: number) => void): MainLoop; + setUpdate(update: (delta: number) => void): MainLoop; + setEnd(end: (fps: number, panic: boolean) => void): MainLoop; + setMaxAllowedFPS(fps?: number): MainLoop; + setSimulationTimestep(timestep: number): MainLoop; + start(): MainLoop; + stop(): MainLoop; +} + +declare var MainLoop: MainLoop; diff --git a/maker.js/makerjs-tests.ts b/maker.js/makerjs-tests.ts index ef32f885ff..8b75fecc8c 100644 --- a/maker.js/makerjs-tests.ts +++ b/maker.js/makerjs-tests.ts @@ -12,16 +12,22 @@ function test() { function testRoot() { makerjs.cloneObject({}); + makerjs.createRouteKey([]); makerjs.extendObject({abc:123}, {xyz:789}); + makerjs.isFunction(function(){}); + makerjs.isNumber(0); + makerjs.isObject({}); makerjs.isModel({}); makerjs.isPath({}); makerjs.isPathArc(paths.arc); + makerjs.isPathArcInBezierCurve({}); makerjs.isPathCircle(paths.circle); makerjs.isPathLine(paths.line); makerjs.isPoint([]); makerjs.pathType.Circle; makerjs.round(44.44444, .01); makerjs.unitType.Millimeter; + new makerjs.Collector(); } function testAngle() { @@ -41,6 +47,7 @@ function test() { new makerjs.exporter.Exporter({}); makerjs.exporter.toDXF(model); makerjs.exporter.toOpenJsCad(model); + makerjs.exporter.toPDF({} as PDFKit.PDFDocument, model); makerjs.exporter.toSTL(model); makerjs.exporter.toSVG(model, { @@ -58,6 +65,11 @@ function test() { makerjs.exporter.tryGetModelUnits(model); } + function testImporter() { + makerjs.importer.fromSVGPathData(''); + makerjs.importer.parseNumericList(''); + } + function testKit() { makerjs.kit.construct(null, null); makerjs.kit.getParameterValues(null); @@ -67,26 +79,42 @@ function test() { } function testMeasure() { + makerjs.measure.increase(mp, mm); makerjs.measure.isPointEqual(p1, p2); makerjs.measure.isPathEqual(paths.line, paths.circle, 4); makerjs.measure.isAngleEqual(12, 13); makerjs.measure.isArcConcaveTowardsPoint(paths.arc, [0,0]); + makerjs.measure.isArcOverlapping(paths.arc, paths.arc, true); makerjs.measure.isBetween(7, 8, 9, false); makerjs.measure.isBetweenArcAngles(7, paths.arc, false); makerjs.measure.isBetweenPoints([1,1], paths.line, true); - makerjs.measure.modelExtents(model).high[0]; - makerjs.measure.pathExtents(paths.circle).low[0]; + makerjs.measure.isBezierSeedLinear({type: '', origin:[], end:[], controls:[]}); + makerjs.measure.isLineOverlapping(paths.line, paths.line, false); + makerjs.measure.isMeasurementOverlapping(mm, mp); + var mm = makerjs.measure.modelExtents(model); + var mp = makerjs.measure.pathExtents(paths.circle); makerjs.measure.pathLength(paths.line); makerjs.measure.pointDistance([0,0], [9,9]); + new makerjs.measure.Atlas(model); + mm.low[0]; + mp.high[1]; + var s = makerjs.measure.lineSlope(paths.line); + makerjs.measure.isPointOnSlope([], s); + makerjs.measure.isSlopeEqual(s, s); } function testModel(){ makerjs.model.breakPathsAtIntersections(model, { paths:{ } }); var opts: MakerJs.ICombineOptions = { trimDeadEnds: true, pointMatchingDistance: 2 }; makerjs.model.combine(model, model, true, false, true, false, opts); + makerjs.model.combineIntersection(model, model); + makerjs.model.combineSubtraction(model, model); + makerjs.model.combineUnion(model, model); makerjs.model.convertUnits(model, makerjs.unitType.Centimeter); makerjs.model.countChildModels(model); makerjs.model.detachLoop(model); + makerjs.model.expandPaths(model, 7); + makerjs.model.findChains(model, function (chains: MakerJs.IChain[], loose: MakerJs.IWalkPath[], layer: string) {}) makerjs.model.findLoops(model); makerjs.model.getSimilarModelId(model, 'foo'); makerjs.model.getSimilarPathId(model, 'foo'); @@ -95,18 +123,26 @@ function test() { makerjs.model.move(makerjs.model.originate(model, [9,9]), [0,0]); makerjs.model.moveRelative(model, [1,1]); makerjs.model.originate(model); + makerjs.model.outline(model, 5); + makerjs.model.prefixPathIds(model, 'a'); + makerjs.model.removeDeadEnds(model); makerjs.model.rotate(makerjs.model.scale(model, 6), 45, [0,0]); makerjs.model.scale(model, 7); + makerjs.model.simplify(model); + makerjs.model.walk(model, {}); makerjs.model.walkPaths(model, (modelContext: MakerJs.IModel, pathId: string, pathContext: MakerJs.IPath) => {}); model.exporterOptions = { foo: 'bar' }; } function testModels(): MakerJs.IModel[] { return [ + new makerjs.models.BezierCurve([]), new makerjs.models.BoltCircle(7, 7, 7, 7), new makerjs.models.BoltRectangle(2, 2, 2), new makerjs.models.ConnectTheDots(true, [ [0,0], [1,1] ]), new makerjs.models.Dome(5, 7), + new makerjs.models.Ellipse(2,2), + new makerjs.models.EllipticArc(2,2,3,4), new makerjs.models.Oval(7, 7), new makerjs.models.OvalArc(6, 4, 2, 12, true), new makerjs.models.Polygon(7, 5), @@ -116,20 +152,27 @@ function test() { new makerjs.models.SCurve(5, .9), new makerjs.models.Slot([0, 0], [1, 1], 7), new makerjs.models.Square(8), - new makerjs.models.Star(5, 10, 5) + new makerjs.models.Star(5, 10, 5), + new makerjs.models.Text({} as opentypejs.Font, 'z', 12) ]; } function testPath() { makerjs.path.breakAtPoint(paths.arc, [0,0]).type; + makerjs.path.clone(paths.line); + makerjs.path.converge(paths.line, paths.line); + makerjs.path.distort(paths.arc, 5, 6); makerjs.path.dogbone(paths.line, paths.line, 7); + makerjs.path.expand(paths.line, 5); makerjs.path.fillet(paths.arc, paths.line, 4); makerjs.path.intersection(paths.circle, paths.arc, { excludeTangents: true }).intersectionPoints; makerjs.path.mirror(paths.arc, true, true); makerjs.path.move(paths.line, [1,1]); makerjs.path.moveRelative(paths.circle, [0,0]); + makerjs.path.moveTemporary([], [], function(){}); makerjs.path.rotate(paths.line, 5, [0,0]); makerjs.path.scale(paths.arc, 8); + makerjs.path.straighten(paths.arc); } function testPaths() { @@ -141,7 +184,7 @@ function test() { new makerjs.paths.Chord(paths.arc); new makerjs.paths.Parallel(paths.line, 4, [1,1]); - + //paths.line.layer = "0"; var x: MakerJs.IPathLine = { @@ -154,15 +197,17 @@ function test() { return paths; } - function testPoint() { + function testPoint() { makerjs.point.add(p1, p2); makerjs.point.average(p1, p2); makerjs.point.clone(p1); makerjs.point.closest([0,0], [p1, p2]); + makerjs.point.distort([1,1], 2, 3); makerjs.point.fromAngleOnCircle(22, paths.circle); makerjs.point.fromArc(paths.arc); makerjs.point.fromPathEnds(paths.line); makerjs.point.fromPolar(Math.PI, 7); + makerjs.point.fromSlopeIntersection(new makerjs.paths.Line([]), new makerjs.paths.Line([])); makerjs.point.middle(paths.line); makerjs.point.mirror(p1, true, false); makerjs.point.rotate(p1, 5, p2); diff --git a/maker.js/makerjs.d.ts b/maker.js/makerjs.d.ts index 28db25f854..7911249c66 100644 --- a/maker.js/makerjs.d.ts +++ b/maker.js/makerjs.d.ts @@ -2,6 +2,8 @@ // Project: https://github.com/Microsoft/maker.js // Definitions by: Dan Marshall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// +/// /// /** * Root module for Maker.js. @@ -65,6 +67,27 @@ declare namespace MakerJs { * @returns The original object after merging. */ function extendObject(target: Object, other: Object): Object; + /** + * Test to see if a variable is a function. + * + * @param value The object to test. + * @returns True if the object is a function type. + */ + function isFunction(value: any): boolean; + /** + * Test to see if a variable is a number. + * + * @param value The object to test. + * @returns True if the object is a number type. + */ + function isNumber(value: any): boolean; + /** + * Test to see if a variable is an object. + * + * @param value The object to test. + * @returns True if the object is an object type. + */ + function isObject(value: any): boolean; /** * An x-y point in a two-dimensional space. * Implemented as an array with 2 elements. The first element is x, the second element is y. @@ -193,6 +216,44 @@ declare namespace MakerJs { * @param item The item to test. */ function isPathArc(item: any): boolean; + /** + * A bezier seed defines the endpoints and control points of a bezier curve. + */ + interface IPathBezierSeed extends IPathLine { + /** + * The bezier control points. One point for quadratic, 2 points for cubic. + */ + controls: IPoint[]; + /** + * T values of the parent if this is a child that represents a split. + */ + parentRange?: IBezierRange; + } + /** + * Bezier t values for an arc path segment in a bezier curve. + */ + interface IBezierRange { + /** + * The bezier t-value at the starting point. + */ + startT: number; + /** + * The bezier t-value at the end point. + */ + endT: number; + } + /** + * An arc path segment in a bezier curve. + */ + interface IPathArcInBezierCurve extends IPathArc { + bezierData: IBezierRange; + } + /** + * Test to see if an object implements the required properties of an arc in a bezier curve. + * + * @param item The item to test. + */ + function isPathArcInBezierCurve(item: any): boolean; /** * A map of functions which accept a path as a parameter. */ @@ -224,6 +285,7 @@ declare namespace MakerJs { Line: string; Circle: string; Arc: string; + BezierSeed: string; }; /** * Slope and y-intercept of a line. @@ -457,6 +519,12 @@ declare namespace MakerJs { interface IWalkPathCallback { (context: IWalkPath): void; } + /** + * Callback for returning a boolean from an IWalkPath. + */ + interface IWalkPathBooleanCallback { + (context: IWalkPath): boolean; + } /** * A link in a chain, with direction of flow. */ @@ -501,6 +569,10 @@ declare namespace MakerJs { * Flag to separate chains by layers. */ byLayers?: boolean; + /** + * Flag to not recurse models, look only within current model's immediate paths. + */ + shallow?: boolean; } /** * Reference to a model within a model. @@ -774,6 +846,15 @@ declare namespace MakerJs.point { * @returns A new point. */ function scale(pointToScale: IPoint, scaleValue: number): IPoint; + /** + * Distort a point's coordinates. + * + * @param pointToDistort The point to distort. + * @param scaleX The amount of x scaling. + * @param scaleY The amount of y scaling. + * @returns A new point. + */ + function distort(pointToDistort: IPoint, scaleX: number, scaleY: number): IPoint; /** * Subtract a point from another point, and return the result as a new point. Shortcut to Add(a, b, subtract = true). * @@ -804,10 +885,9 @@ declare namespace MakerJs.path { * @param pathToMirror The path to mirror. * @param mirrorX Boolean to mirror on the x axis. * @param mirrorY Boolean to mirror on the y axis. - * @param newId Optional id to assign to the new path. * @returns Mirrored path. */ - function mirror(pathToMirror: IPath, mirrorX: boolean, mirrorY: boolean, newId?: string): IPath; + function mirror(pathToMirror: IPath, mirrorX: boolean, mirrorY: boolean): IPath; /** * Move a path to an absolute point. * @@ -850,6 +930,24 @@ declare namespace MakerJs.path { * @returns The original path (for chaining). */ function scale(pathToScale: IPath, scaleValue: number): IPath; + /** + * Distort a path - scale x and y individually. + * + * @param pathToDistort The path to distort. + * @param scaleX The amount of x scaling. + * @param scaleY The amount of y scaling. + * @returns A new IModel (for circles and arcs) or IPath (for lines and bezier seeds). + */ + function distort(pathToDistort: IPath, scaleX: number, scaleY: number): IModel | IPath; + /** + * Connect 2 lines at their slope intersection point. + * + * @param lineA First line to converge. + * @param lineB Second line to converge. + * @param useOriginA Optional flag to converge the origin point of lineA instead of the end point. + * @param useOriginB Optional flag to converge the origin point of lineB instead of the end point. + */ + function converge(lineA: IPathLine, lineB: IPathLine, useOriginA?: boolean, useOriginB?: boolean): IPoint; } declare namespace MakerJs.path { /** @@ -916,9 +1014,25 @@ declare namespace MakerJs.paths { type: string; origin: IPoint; radius: number; + /** + * Class for circle path, created from radius. Origin will be [0, 0]. + * + * Example: + * ``` + * var c = new makerjs.paths.Circle(7); + * ``` + * + * @param radius The radius of the circle. + */ + constructor(radius: number); /** * Class for circle path, created from origin point and radius. * + * Example: + * ``` + * var c = new makerjs.paths.Circle([10, 10], 7); + * ``` + * * @param origin The center point of the circle. * @param radius The radius of the circle. */ @@ -926,6 +1040,11 @@ declare namespace MakerJs.paths { /** * Class for circle path, created from 2 points. * + * Example: + * ``` + * var c = new makerjs.paths.Circle([5, 15], [25, 15]); + * ``` + * * @param pointA First point on the circle. * @param pointB Second point on the circle. */ @@ -933,6 +1052,11 @@ declare namespace MakerJs.paths { /** * Class for circle path, created from 3 points. * + * Example: + * ``` + * var c = new makerjs.paths.Circle([0, 0], [0, 10], [20, 0]); + * ``` + * * @param pointA First point on the circle. * @param pointB Second point on the circle. * @param pointC Third point on the circle. @@ -941,14 +1065,23 @@ declare namespace MakerJs.paths { } /** * Class for line path. - * - * @param origin The origin point of the line. - * @param end The end point of the line. */ class Line implements IPathLine { + type: string; origin: IPoint; end: IPoint; - type: string; + /** + * Class for line path, constructed from array of 2 points. + * + * @param points Array of 2 points. + */ + constructor(points: IPoint[]); + /** + * Class for line path, constructed from 2 points. + * + * @param origin The origin point of the line. + * @param end The end point of the line. + */ constructor(origin: IPoint, end: IPoint); } /** @@ -1247,6 +1380,14 @@ declare namespace MakerJs.measure { * @returns true if points are the same, false if they are not */ function isPointEqual(a: IPoint, b: IPoint, withinDistance?: number): boolean; + /** + * Find out if point is on a slope. + * + * @param p Point to check. + * @param b Slope. + * @returns true if point is on the slope + */ + function isPointOnSlope(p: IPoint, slope: ISlope, withinDistance?: number): boolean; /** * Check for slope equality. * @@ -1311,6 +1452,13 @@ declare namespace MakerJs.measure { * @returns Boolean true if point is between (or equal to) the line's origin and end points. */ function isBetweenPoints(pointInQuestion: IPoint, line: IPathLine, exclusive: boolean): boolean; + /** + * Check if a given bezier seed is simply a line. + * + * @param seed The bezier seed to test. + * @returns Boolean true if bezier seed has control points on the line slope and between the line endpoints. + */ + function isBezierSeedLinear(seed: IPathBezierSeed): boolean; /** * Check for line overlapping another line. * @@ -1446,6 +1594,20 @@ declare namespace MakerJs.exporter { exportItem(itemId: string, itemToExport: any, origin: IPoint): void; } } +declare namespace MakerJs.importer { + /** + * Create a numeric array from a string of numbers. The numbers may be delimited by anything non-numeric. + * + * Example: + * ``` + * var n = makerjs.importer.parseNumericList('5, 10, 15.20 25-30-35 4e1 .5'); + * ``` + * + * @param s The string of numbers. + * @returns Array of numbers. + */ + function parseNumericList(s: string): number[]; +} declare namespace MakerJs.exporter { function toDXF(modelToExport: IModel, options?: IDXFRenderOptions): string; function toDXF(pathsToExport: IPath[], options?: IDXFRenderOptions): string; @@ -1528,7 +1690,6 @@ declare namespace MakerJs.model { * * @param modelContext The model to search for chains. * @param options Optional options object. - * @returns A list of chains. */ function findChains(modelContext: IModel, callback: IChainCallback, options?: IFindChainsOptions): void; } @@ -1554,7 +1715,7 @@ declare namespace MakerJs.model { * @param options Optional options object. * @returns The input model (for chaining). */ - function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: number): IModel; + function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: any, keep?: IWalkPathBooleanCallback): IModel; } declare namespace MakerJs.exporter { /** @@ -1676,11 +1837,11 @@ declare namespace MakerJs.exporter { /** * Convert a chain to SVG path data. */ - function chainToSVGPathData(chain: IChain, offset: IPoint): string; + function chainToSVGPathData(chain: IChain, offset: IPoint, scale: number): string; /** * Convert a path to SVG path data. */ - function pathToSVGPathData(pathToExport: IPath, offset: IPoint, offset2: IPoint): string; + function pathToSVGPathData(pathToExport: IPath, offset: IPoint, offset2: IPoint, scale: number): string; function toSVG(modelToExport: IModel, options?: ISVGRenderOptions): string; function toSVG(pathsToExport: IPath[], options?: ISVGRenderOptions): string; function toSVG(pathToExport: IPath, options?: ISVGRenderOptions): string; @@ -1743,9 +1904,119 @@ declare namespace MakerJs.exporter { viewBox?: boolean; } } +declare namespace MakerJs.importer { + function fromSVGPathData(pathData: string): IModel; +} +declare namespace MakerJs.models { + class BezierCurve implements IModel { + models: IModelMap; + paths: IPathMap; + origin: IPoint; + type: string; + seed: IPathBezierSeed; + accuracy: number; + constructor(points: IPoint[], accuracy?: number); + constructor(seed: IPathBezierSeed, accuracy?: number); + constructor(seed: IPathBezierSeed, isChild: boolean, accuracy?: number); + constructor(origin: IPoint, control: IPoint, end: IPoint, accuracy?: number); + constructor(origin: IPoint, controls: IPoint[], end: IPoint, accuracy?: number); + constructor(origin: IPoint, control1: IPoint, control2: IPoint, end: IPoint, accuracy?: number); + static typeName: string; + static getBezierSeeds(curve: BezierCurve, options?: IFindChainsOptions): IPathBezierSeed[]; + static computePoint(seed: IPathBezierSeed, t: number): IPoint; + } +} +declare var Bezier: typeof BezierJs.Bezier; +declare namespace MakerJs.models { + class Ellipse implements IModel { + models: IModelMap; + origin: IPoint; + /** + * Class for Ellipse created with 2 radii. + * + * @param radiusX The x radius of the ellipse. + * @param radiusY The y radius of the ellipse. + * @param accuracy Optional accuracy of the underlying BezierCurve. + */ + constructor(radiusX: number, radiusY: number, accuracy?: number); + /** + * Class for Ellipse created at a specific origin and 2 radii. + * + * @param origin The center of the ellipse. + * @param radiusX The x radius of the ellipse. + * @param radiusY The y radius of the ellipse. + * @param accuracy Optional accuracy of the underlying BezierCurve. + */ + constructor(origin: IPoint, radiusX: number, radiusY: number, accuracy?: number); + /** + * Class for Ellipse created at a specific x, y and 2 radii. + * + * @param cx The x coordinate of the center of the ellipse. + * @param cy The y coordinate of the center of the ellipse. + * @param rX The x radius of the ellipse. + * @param rY The y radius of the ellipse. + * @param accuracy Optional accuracy of the underlying BezierCurve. + */ + constructor(cx: number, cy: number, rx: number, ry: number, accuracy?: number); + } + class EllipticArc implements IModel { + models: IModelMap; + /** + * Class for Elliptic Arc created by distorting a circular arc. + * + * @param arc The circular arc to use as the basis of the elliptic arc. + * @param radiusX The x radius of the ellipse. + * @param radiusY The y radius of the ellipse. + * @param accuracy Optional accuracy of the underlying BezierCurve. + */ + constructor(startAngle: number, endAngle: number, radiusX: number, radiusY: number, accuracy?: number); + /** + * Class for Elliptic Arc created by distorting a circular arc. + * + * @param arc The circular arc to use as the basis of the elliptic arc. + * @param distortX The x scale of the ellipse. + * @param distortY The y scale of the ellipse. + * @param accuracy Optional accuracy of the underlying BezierCurve. + */ + constructor(arc: IPathArc, distortX: number, distortY: number, accuracy?: number); + } +} declare namespace MakerJs.models { class ConnectTheDots implements IModel { paths: IPathMap; + /** + * Create a model by connecting points designated in a string. The model will be 'closed' - i.e. the last point will connect to the first point. + * + * Example: + * ``` + * var c = new makerjs.models.ConnectTheDots('-10 0 10 0 0 20'); // 3 coordinates to form a triangle + * ``` + * + * @param numericList String containing a list of numbers which can be delimited by spaces, commas, or anything non-numeric (Note: [exponential notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) is allowed). + */ + constructor(numericList: string); + /** + * Create a model by connecting points designated in a numeric array. The model will be 'closed' - i.e. the last point will connect to the first point. + * + * Example: + * ``` + * var c = new makerjs.models.ConnectTheDots([-10, 0, 10, 0, 0, 20]); // 3 coordinates to form a triangle + * ``` + * + * @param coords Array of coordinates. + */ + constructor(coords: number[]); + /** + * Create a model by connecting points designated in an array of points. The model may be closed, or left open. + * + * Example: + * ``` + * var c = new makerjs.models.ConnectTheDots(false, [[-10, 0], [10, 0], [0, 20]]); // 3 coordinates left open + * ``` + * + * @param isClosed Flag to specify if last point should connect to the first point. + * @param points Array of IPoints. + */ constructor(isClosed: boolean, points: IPoint[]); } } @@ -1777,8 +2048,34 @@ declare namespace MakerJs.models { } declare namespace MakerJs.models { class RoundRectangle implements IModel { + origin: IPoint; paths: IPathMap; + /** + * Create a round rectangle from width, height, and corner radius. + * + * Example: + * ``` + * var r = new makerjs.models.RoundRectangle(100, 50, 5); + * ``` + * + * @param width Width of the rectangle. + * @param height Height of the rectangle. + * @param radius Corner radius. + */ constructor(width: number, height: number, radius: number); + /** + * Create a round rectangle which will surround a model. + * + * Example: + * ``` + * var b = new makerjs.models.BoltRectangle(30, 20, 1); //draw a bolt rectangle so we have something to surround + * var r = new makerjs.models.RoundRectangle(b, 2.5); //surround it + * ``` + * + * @param modelToSurround IModel object. + * @param margin Distance from the model. This will also become the corner radius. + */ + constructor(modelToSurround: IModel, margin: number); } } declare namespace MakerJs.models { @@ -1798,7 +2095,43 @@ declare namespace MakerJs.models { class Rectangle implements IModel { paths: IPathMap; origin: IPoint; + /** + * Create a rectangle from width and height. + * + * Example: + * ``` + * var r = new makerjs.models.Rectangle(100, 50); + * ``` + * + * @param width Width of the rectangle. + * @param height Height of the rectangle. + */ constructor(width: number, height: number); + /** + * Create a rectangle which will surround a model. + * + * Example: + * ``` + * var e = new makerjs.models.Ellipse(17, 10); // draw an ellipse so we have something to surround. + * var r = new makerjs.models.Rectangle(e, 3); // draws a rectangle surrounding the ellipse by 3 units. + * ``` + * + * @param modelToSurround IModel object. + * @param margin Optional distance from the model. + */ + constructor(modelToSurround: IModel, margin?: number); + /** + * Create a rectangle from a measurement. + * + * Example: + * ``` + * var e = new makerjs.models.Ellipse(17, 10); // draw an ellipse so we have something to measure. + * var m = makerjs.measure.modelExtents(e); // measure the ellipse. + * var r = new makerjs.models.Rectangle(m); // draws a rectangle surrounding the ellipse. + * ``` + * + * @param measurement IMeasure object. See http://microsoft.github.io/maker.js/docs/api/modules/makerjs.measure.html#pathextents and http://microsoft.github.io/maker.js/docs/api/modules/makerjs.measure.html#modelextents to get measurements of paths and models. + */ constructor(measurement: IMeasure); } } @@ -1835,3 +2168,9 @@ declare namespace MakerJs.models { static InnerRadiusRatio(numberOfPoints: number, skipPoints: number): number; } } +declare namespace MakerJs.models { + class Text implements IModel { + models: IModelMap; + constructor(font: opentypejs.Font, text: string, fontSize: number, combine?: boolean); + } +} diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 2aaa0d268a..421129320f 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -78,6 +78,7 @@ declare module "mongoose" { import events = require('events'); import mongodb = require('mongodb'); import stream = require('stream'); + import mongoose = require('mongoose'); /* * Some mongoose classes have the same name as the native JS classes @@ -90,234 +91,207 @@ declare module "mongoose" { /* * Public API */ - export = mongoose; /* * section index.js * http://mongoosejs.com/docs/api.html#index-js - * - * require('mongoose') is not actually a class with static - * methods. It is an instance of the Mongoose class. - * - * Reasons we use a class with static properties below: - * 1. MongooseThenable extends mongoose, so we need a - * scope to wrap everything. We can't use a namespace - * since namespaces can't be inherited from. - * 2. We can't use an interface to wrap everything, since - * some properties of mongoose are class constructors. - * Exporting an interface won't, for example, let us - * call new mongoose.Schema({}) - * 3. We can't use a normal class since require('mongoose') - * is an instance object. All of its properties are - * immediately accessible: require('mongoose').model('') - * If we export a normal class and import * as mongoose - * we'll have to call new mongoose() before we can use - * any of its methods, which would be inaccurate. - * - * NOTE: the static properties below cannot be used for - * type-checking. If you want to use the names for - * type-checking you must add a corresponding interface - * inside namespace mongoose {} defined below. */ + + /* Class constructors */ + export var Aggregate: typeof _mongoose.Aggregate; + export var CastError: typeof _mongoose.CastError; + export var Collection: _mongoose.Collection; + export var Connection: typeof _mongoose.Connection; + export var Document: typeof _mongoose.Document; + export var DocumentProvider: any; + export var Error: typeof _mongoose.Error; + export var Model: _mongoose.ModelConstructor<{}>; + export var Mongoose: { + // recursive constructor + new(...args: any[]): typeof mongoose; + } + /** - * Contains all the public properties and methods that can - * be accessed by mongoose = require('mongoose') + * To assign your own promise library: + * + * 1. Include this somewhere in your code: + * mongoose.Promise = YOUR_PROMISE; + * + * 2. Include this somewhere in your main .d.ts file: + * type MongoosePromise = YOUR_PROMISE; */ - class mongoose { - /* Class constructors */ - static Aggregate: typeof _mongoose.Aggregate; - static CastError: typeof _mongoose.CastError; - static Collection: _mongoose.Collection; - static Connection: typeof _mongoose.Connection; - static Document: typeof _mongoose.Document; - static DocumentProvider: any; - static Error: typeof _mongoose.Error; - static Model: _mongoose.ModelConstructor<{}>; - static Mongoose: { - // recursive constructor - new(...args: any[]): typeof mongoose; - } - /** - * To assign your own promise library: - * - * 1. Include this somewhere in your code: - * mongoose.Promise = YOUR_PROMISE; - * - * 2. Include this somewhere in your main .d.ts file: - * type MongoosePromise = YOUR_PROMISE; - */ - static Promise: any; - static PromiseProvider: any; - static Query: typeof _mongoose.ModelQuery; - static Schema: typeof _mongoose.Schema; - static SchemaType: typeof _mongoose.SchemaType; - static SchemaTypes: typeof _mongoose.Schema.Types; - static Types: { - Subdocument: typeof _mongoose.Types.Subdocument; - Array: typeof _mongoose.Types.Array; - DocumentArray: typeof _mongoose.Types.DocumentArray; - Buffer: typeof _mongoose.Types.Buffer; - ObjectId: typeof _mongoose.Types.ObjectId; - Embedded: typeof _mongoose.Types.Embedded; - } - static VirtualType: typeof _mongoose.VirtualType; - /* Properties */ - /** Expose connection states for user-land */ - static STATES: Object - /** The default connection of the mongoose module. */ - static connection: _mongoose.Connection; - /** The node-mongodb-native driver Mongoose uses. */ - static mongo: typeof mongodb; - /** - * The mquery query builder Mongoose uses. - * Currently there is no mquery type definition. - */ - static mquery: any; - /** The Mongoose version */ - static version: string; - - /* Methods */ - /** - * Opens the default mongoose connection. - * Options passed take precedence over options included in connection strings. - * @returns pseudo-promise wrapper around this - */ - static connect(uris: string, - options?: _mongoose.MongooseConnectOptions, - callback?: (err: mongodb.MongoError) => void): typeof _mongoose.MongooseThenable; - static connect(uris: string, - callback?: (err: mongodb.MongoError) => void): typeof _mongoose.MongooseThenable; - - /** - * Creates a Connection instance. - * Each connection instance maps to a single database. This method is helpful - * when mangaging multiple db connections. - * @param uri a mongodb:// URI - * @param options options to pass to the driver - * @returns the created Connection object - */ - static createConnection(): _mongoose.Connection; - static createConnection(uri: string, - options?: _mongoose.MongooseConnectOptions - ): _mongoose.Connection; - static createConnection(host: string, database_name: string, port?: number, - options?: _mongoose.MongooseConnectOptions - ): _mongoose.Connection; - - /** - * Disconnects all connections. - * @param fn called after all connection close. - * @returns pseudo-promise wrapper around this - */ - static disconnect(fn?: (error: any) => void): typeof _mongoose.MongooseThenable; - - /** Gets mongoose options */ - static get(key: string): any; - - /** - * Defines a model or retrieves it. - * Models defined on the mongoose instance are available to all connection - * created by the same mongoose instance. - * @param name model name - * @param collection (optional, induced from model name) - * @param skipInit whether to skip initialization (defaults to false) - */ - static model(name: string, schema?: _mongoose.Schema, collection?: string, - skipInit?: boolean): _mongoose.ModelConstructor; - static model(name: string, schema?: _mongoose.Schema, collection?: string, - skipInit?: boolean): Statics & _mongoose.ModelConstructor; - - /** - * Returns an array of model names created on this instance of Mongoose. - * Does not include names of models created using connection.model(). - */ - static modelNames(): string[]; - - /** - * Declares a global plugin executed on all Schemas. - * Equivalent to calling .plugin(fn) on each Schema you create. - * @param fn plugin callback - * @param opts optional options - */ - static plugin(fn: Function, opts?: Object): typeof mongoose; - - /** Sets mongoose options */ - static set(key: string, value: any): void; + export var Promise: any; + export var PromiseProvider: any; + export var Query: typeof _mongoose.ModelQuery; + export var Schema: typeof _mongoose.Schema; + export var SchemaType: typeof _mongoose.SchemaType; + export var SchemaTypes: typeof _mongoose.Schema.Types; + export var Types: { + Subdocument: typeof _mongoose.Types.Subdocument; + Array: typeof _mongoose.Types.Array; + DocumentArray: typeof _mongoose.Types.DocumentArray; + Buffer: typeof _mongoose.Types.Buffer; + ObjectId: typeof _mongoose.Types.ObjectId; + Embedded: typeof _mongoose.Types.Embedded; } + export var VirtualType: typeof _mongoose.VirtualType; - /** All the types that are exposed for type checking. */ - namespace mongoose { - type Aggregate = _mongoose.Aggregate; - type CastError = _mongoose.CastError; - type Collection = _mongoose.Collection; - type Connection = _mongoose.Connection; - type Document = _mongoose.Document; - type Error = _mongoose.Error; - type ValidationError = _mongoose.ValidationError; + /** Expose connection states for user-land */ + export var STATES: Object + /** The default connection of the mongoose module. */ + export var connection: _mongoose.Connection; + /** The node-mongodb-native driver Mongoose uses. */ + export var mongo: typeof mongodb; + /** + * The mquery query builder Mongoose uses. + * Currently there is no mquery type definition. + */ + export var mquery: any; + /** The Mongoose version */ + export var version: string; - /** Document created from model constructors. */ - type model = _mongoose.Model; - /** Model Constructor. */ - type Model = _mongoose.ModelConstructor; + /* Methods */ + /** + * Opens the default mongoose connection. + * Options passed take precedence over options included in connection strings. + * @returns pseudo-promise wrapper around this + */ + export function connect(uris: string, + options?: _mongoose.MongooseConnectOptions, + callback?: (err: mongodb.MongoError) => void): _mongoose.MongooseThenable; + export function connect(uris: string, + callback?: (err: mongodb.MongoError) => void): _mongoose.MongooseThenable; + + /** + * Creates a Connection instance. + * Each connection instance maps to a single database. This method is helpful + * when mangaging multiple db connections. + * @param uri a mongodb:// URI + * @param options options to pass to the driver + * @returns the created Connection object + */ + export function createConnection(): _mongoose.Connection; + export function createConnection(uri: string, + options?: _mongoose.MongooseConnectOptions + ): _mongoose.Connection; + export function createConnection(host: string, database_name: string, port?: number, + options?: _mongoose.MongooseConnectOptions + ): _mongoose.Connection; + + /** + * Disconnects all connections. + * @param fn called after all connection close. + * @returns pseudo-promise wrapper around this + */ + export function disconnect(fn?: (error: any) => void): _mongoose.MongooseThenable; + + /** Gets mongoose options */ + export function get(key: string): any; + + /** + * Defines a model or retrieves it. + * Models defined on the mongoose instance are available to all connection + * created by the same mongoose instance. + * @param name model name + * @param collection (optional, induced from model name) + * @param skipInit whether to skip initialization (defaults to false) + */ + export function model(name: string, schema?: _mongoose.Schema, collection?: string, + skipInit?: boolean): _mongoose.ModelConstructor; + export function model(name: string, schema?: _mongoose.Schema, collection?: string, + skipInit?: boolean): Statics & _mongoose.ModelConstructor; + + /** + * Returns an array of model names created on this instance of Mongoose. + * Does not include names of models created using connection.model(). + */ + export function modelNames(): string[]; + + /** + * Declares a global plugin executed on all Schemas. + * Equivalent to calling .plugin(fn) on each Schema you create. + * @param fn plugin callback + * @param opts optional options + */ + export function plugin(fn: Function, opts?: Object): typeof mongoose; + + /** Sets mongoose options */ + export function set(key: string, value: any): void; - type Mongoose = typeof mongoose; - type Promise = _mongoose._MongoosePromise; - type Query = _mongoose.Query; - type QueryCursor = _mongoose.QueryCursor; - type QueryStream = _mongoose.QueryStream; - type Schema = _mongoose.Schema; - namespace Schema { - namespace Types { - type Array = _mongoose.Schema._Types.Array; - type String = _mongoose.Schema._Types.String; - type DocumentArray = _mongoose.Schema._Types.DocumentArray; - type Number = _mongoose.Schema._Types.Number; - type Date = _mongoose.Schema._Types.Date; - type Buffer = _mongoose.Schema._Types.Buffer; - type Boolean = _mongoose.Schema._Types.Boolean; - type Bool = _mongoose.Schema._Types.Boolean; - type ObjectId = _mongoose.Schema._Types.ObjectId; - type Oid = _mongoose.Schema._Types.ObjectId; - type Mixed = _mongoose.Schema._Types.Mixed; - type Object = _mongoose.Schema._Types.Mixed; - type Embedded = _mongoose.Schema._Types.Embedded; - } - } - type SchemaType = _mongoose.SchemaType; - namespace Types { - type Subdocument = _mongoose.Types.Subdocument; - type Array = _mongoose.Types.Array; - type DocumentArray = _mongoose.Types.DocumentArray; - type Buffer = _mongoose.Types.Buffer; - type ObjectId = _mongoose.Types.ObjectId; - type Embedded = _mongoose.Types.Embedded; - } - type VirtualType = _mongoose.VirtualType; - type ConnectionOptions = _mongoose.MongooseConnectOptions; - } /* - * Public API Details. + * All the types that are exposed for type checking. */ + export type Aggregate = _mongoose.Aggregate; + export type CastError = _mongoose.CastError; + export type Collection = _mongoose.Collection; + export type Connection = _mongoose.Connection; + export type Document = _mongoose.Document; + export type Error = _mongoose.Error; + export type ValidationError = _mongoose.ValidationError; + + /** Document created from model constructors. */ + export type model = _mongoose.Model; + /** Model Constructor. */ + export type Model = _mongoose.ModelConstructor; + + export type Mongoose = typeof mongoose; + export type Promise = _mongoose._MongoosePromise; + export type Query = _mongoose.Query; + export type QueryCursor = _mongoose.QueryCursor; + export type QueryStream = _mongoose.QueryStream; + export type Schema = _mongoose.Schema; + namespace Schema { + namespace Types { + export type Array = _mongoose.Schema._Types.Array; + export type String = _mongoose.Schema._Types.String; + export type DocumentArray = _mongoose.Schema._Types.DocumentArray; + export type Number = _mongoose.Schema._Types.Number; + export type Date = _mongoose.Schema._Types.Date; + export type Buffer = _mongoose.Schema._Types.Buffer; + export type Boolean = _mongoose.Schema._Types.Boolean; + export type Bool = _mongoose.Schema._Types.Boolean; + export type ObjectId = _mongoose.Schema._Types.ObjectId; + export type Oid = _mongoose.Schema._Types.ObjectId; + export type Mixed = _mongoose.Schema._Types.Mixed; + export type Object = _mongoose.Schema._Types.Mixed; + export type Embedded = _mongoose.Schema._Types.Embedded; + } + } + export type SchemaType = _mongoose.SchemaType; + namespace Types { + export type Subdocument = _mongoose.Types.Subdocument; + export type Array = _mongoose.Types.Array; + export type DocumentArray = _mongoose.Types.DocumentArray; + export type Buffer = _mongoose.Types.Buffer; + export type ObjectId = _mongoose.Types.ObjectId; + export type Embedded = _mongoose.Types.Embedded; + } + export type VirtualType = _mongoose.VirtualType; + export type ConnectionOptions = _mongoose.MongooseConnectOptions; + + + /** Private */ namespace _mongoose { /* * section index.js * http://mongoosejs.com/docs/api.html#index-js */ - class MongooseThenable extends mongoose { + type MongooseThenable = typeof mongoose & _MongooseThenable; + interface _MongooseThenable { /** * Ability to use mongoose object as a pseudo-promise so .connect().then() * and .disconnect().then() are viable. */ - static then(onFulfill?: () => void | TRes | PromiseLike, + then(onFulfill?: () => void | TRes | PromiseLike, onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; /** * Ability to use mongoose object as a pseudo-promise so .connect().then() * and .disconnect().then() are viable. */ - static catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; + catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; } class CastError extends _mongoose.Error { @@ -1148,7 +1122,9 @@ declare module "mongoose" { * potentially overwritting any changes that happen between when you retrieved the object * and when you save it. */ - sort(compareFn?: (a: T, b: T) => number): T[]; + // some lib.d.ts have return type "this" and others have return type "T[]" + // which causes errors. Let the inherited array provide the sort() method. + //sort(compareFn?: (a: T, b: T) => number): T[]; /** * Wraps Array#splice with proper change tracking and casting. @@ -2627,4 +2603,4 @@ declare module "mongoose" { name: string; } } -} \ No newline at end of file +} diff --git a/natural/natural.d.ts b/natural/natural.d.ts index ff519eeccf..009a1c9911 100644 --- a/natural/natural.d.ts +++ b/natural/natural.d.ts @@ -80,6 +80,20 @@ declare module "natural" { static restore(classifier: any, stemmer?: Stemmer): BayesClassifier; } + interface LogisticRegressionClassifierCallback { (err: any, classifier: any): void } + class LogisticRegressionClassifier { + events: events.EventEmitter; + addDocument(text: string, stem: string): void; + addDocument(text: string[], stem: string): void; + train(): void; + classify(observation: string): string; + getClassifications(observation: string): string[]; + save(filename: string, callback: LogisticRegressionClassifierCallback): void; + static load(filename: string, stemmer: Stemmer, callback: LogisticRegressionClassifierCallback): void; + static restore(classifier: any, stemmer?: Stemmer): LogisticRegressionClassifier; + } + + interface Phonetic { compare(stringA: string, stringB: string): boolean; process(token: string, maxLength?: number): string; diff --git a/node-usb/node-usb-tests.ts b/node-usb/node-usb-tests.ts index 8ae22cf0cc..9abef86ee8 100644 --- a/node-usb/node-usb-tests.ts +++ b/node-usb/node-usb-tests.ts @@ -9,6 +9,9 @@ device.busNumber = 1; device.deviceAddress = 1; device.portNumbers = [1, 2, 3]; +device.__open(); +device.__claimInterface(0); + device.open(true); device.close(); const xferDevice: usb.Device = device.controlTransfer(1, 1, 1, 1, 1, (error: string, buf: Buffer): usb.Device => new usb.Device()); diff --git a/node-usb/node-usb.d.ts b/node-usb/node-usb.d.ts index 0a52bdf127..b8d1611a51 100644 --- a/node-usb/node-usb.d.ts +++ b/node-usb/node-usb.d.ts @@ -16,6 +16,9 @@ declare module "usb" { public configDescriptor: ConfigDescriptor; public interfaces: Array; + __open(): void; + __claimInterface(addr: number): void; + open(defaultConfig?: boolean): void; close(): void; interface(addr: number): Interface; diff --git a/node-webkit/node-webkit.d.ts b/node-webkit/node-webkit.d.ts index 81129274dc..3a9533875b 100644 --- a/node-webkit/node-webkit.d.ts +++ b/node-webkit/node-webkit.d.ts @@ -156,7 +156,7 @@ declare module "nw.gui" { eval(frame: HTMLIFrameElement, script: string): void; } - export interface App { + export interface App extends EventEmitter { argv: any; fullArgv: any; dataPath: string; @@ -199,7 +199,7 @@ declare module "nw.gui" { menu?: Menu; } - export class Tray implements TrayOption { + export class Tray extends EventEmitter implements TrayOption { constructor(option: TrayOption); title: string; tooltip: string; diff --git a/node/node-4.d.ts b/node/node-4.d.ts index e0847bb5bc..02b37f8cb2 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -885,6 +885,14 @@ declare module "https" { export interface Agent extends http.Agent { } export interface AgentOptions extends http.AgentOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; maxCachedSessions?: number; } diff --git a/node/node.d.ts b/node/node.d.ts index bad534cdd7..6770d84632 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -301,6 +301,17 @@ declare namespace NodeJS { heapUsed: number; } + export interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + export interface Process extends EventEmitter { stdout: WritableStream; stderr: WritableStream; @@ -313,6 +324,7 @@ declare namespace NodeJS { cwd(): string; env: any; exit(code?: number): void; + exitCode: number; getgid(): number; setgid(id: number): void; setgid(id: string): void; @@ -320,16 +332,7 @@ declare namespace NodeJS { setuid(id: number): void; setuid(id: string): void; version: string; - versions: { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - }; + versions: ProcessVersions; config: { target_defaults: { cflags: any[]; @@ -605,6 +608,7 @@ declare module "http" { removeHeader(name: string): void; write(chunk: any, encoding?: string): any; addTrailers(headers: any): void; + finished: boolean; // Extended base methods end(): void; @@ -899,7 +903,7 @@ declare module "https" { requestCert?: boolean; rejectUnauthorized?: boolean; NPNProtocols?: any; - SNICallback?: (servername: string) => any; + SNICallback?: (servername: string, cb:(err:Error,ctx:tls.SecureContext)=>any) => any; } export interface RequestOptions extends http.RequestOptions { @@ -916,6 +920,14 @@ declare module "https" { export interface Agent extends http.Agent { } export interface AgentOptions extends http.AgentOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; maxCachedSessions?: number; } @@ -1983,7 +1995,7 @@ declare module "tls" { requestCert?: boolean; rejectUnauthorized?: boolean; NPNProtocols?: any; //array or Buffer; - SNICallback?: (servername: string) => any; + SNICallback?: (servername: string, cb:(err:Error,ctx:SecureContext)=>any) => any; } export interface ConnectionOptions { diff --git a/nunjucks/nunjucks.d.ts b/nunjucks/nunjucks.d.ts index f0f9b081f3..46542bed93 100644 --- a/nunjucks/nunjucks.d.ts +++ b/nunjucks/nunjucks.d.ts @@ -34,6 +34,7 @@ declare namespace nunjucks { export function configure(options: ConfigureOptions): Environment; export function configure(path: string, options?: ConfigureOptions): Environment; + export function configure(path: string[], options?: ConfigureOptions): Environment; export interface ConfigureOptions { autoescape?: boolean; diff --git a/openlayers/openlayers-3.14.2.d.ts b/openlayers/openlayers-3.14.2.d.ts index f8ca153820..5046e1fa8f 100644 --- a/openlayers/openlayers-3.14.2.d.ts +++ b/openlayers/openlayers-3.14.2.d.ts @@ -1070,6 +1070,25 @@ declare namespace olx { rightHanded?: boolean; } } + + namespace control { + interface ControlOptions { + /** + * The element is the control's container element. This only needs to be specified if you're developing a custom control. + */ + element?: Element; + + /** + * Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback. + */ + render?: any; + + /** + * Specify a target if you want the control to be rendered outside of the map's viewport. + */ + target?: Element | string; + } + } } /** @@ -2388,6 +2407,7 @@ declare namespace ol { } class Control { + constructor(options: olx.control.ControlOptions); } class FullScreen { diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index 243087c7b4..a70f3b115b 100644 --- a/openlayers/openlayers.d.ts +++ b/openlayers/openlayers.d.ts @@ -8,7 +8,7 @@ declare namespace olx { /** Attributions */ attributions?: Array - + /*** The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. */ crossOrigin?: string @@ -47,7 +47,7 @@ declare namespace olx { /*** The extent to zoom to. If undefined the validity extent of the view projection is used.*/ extent: ol.Extent; } - + interface AttributionOptions { /** HTML markup for this attribution. */ @@ -1220,7 +1220,7 @@ declare namespace ol { /** * Events emitted by ol.Collection instances are instances of this type. */ - class CollectionEvent { + class CollectionEvent extends ol.events.Event { /** * The element that is added to or removed from the collection. @@ -1279,7 +1279,7 @@ declare namespace ol { /** * Events emitted by ol.interaction.DragBox instances are instances of this type. */ - class DragBoxEvent { + class DragBoxEvent extends ol.events.Event { /** * The coordinate of the drag event. @@ -1935,7 +1935,7 @@ declare namespace ol { /** * Events emitted as map events are instances of this type. See ol.Map for which events trigger a map event. */ - class MapEvent { + class MapEvent extends ol.events.Event { /** * The frame state at the time of the event. @@ -2005,7 +2005,7 @@ declare namespace ol { /** * Events emitted by ol.Object instances are instances of this type. */ - class ObjectEvent { + class ObjectEvent extends ol.events.Event { /** * The name of the property whose value is changing. @@ -2045,7 +2045,7 @@ declare namespace ol { * @param ref The object to use as this in listener. * @returns Unique key for the listener. */ - on(type: string, listener: (event: MapBrowserEvent) => void, ref?: any): any; + on(type: string, listener: (event: ol.events.Event) => void, ref?: any): any; /** * Listen for a certain type of event. @@ -2054,7 +2054,7 @@ declare namespace ol { * @param ref The object to use as this in listener. * @returns Unique key for the listener. */ - on(type: Array, listener: (event: MapBrowserEvent) => void, ref?: any): any; + on(type: Array, listener: (event: ol.events.Event) => void, ref?: any): any; /** * Listen once for a certain type of event. @@ -2063,7 +2063,7 @@ declare namespace ol { * @param ref The object to use as this in listener. * @returns Unique key for the listener. */ - once(type: string, listener: (event: MapBrowserEvent) => void, ref?: any): any; + once(type: string, listener: (event: ol.events.Event) => void, ref?: any): any; /** * Listen once for a certain type of event. @@ -2072,7 +2072,7 @@ declare namespace ol { * @param ref The object to use as this in listener. * @returns Unique key for the listener. */ - once(type: Array, listener: (event: MapBrowserEvent) => void, ref?: any): any; + once(type: Array, listener: (event: ol.events.Event) => void, ref?: any): any; /** * Unlisten for a certain type of event. @@ -2081,7 +2081,7 @@ declare namespace ol { * @param ref The object to use as this in listener. * @returns Unique key for the listener. */ - un(type: Array, listener: (event: MapBrowserEvent) => void, ref?: any): any; + un(type: Array, listener: (event: ol.events.Event) => void, ref?: any): any; /** * Removes an event listener using the key returned by on() or once(). Note that using the ol.Observable.unByKey static function is to be preferred. @@ -2165,7 +2165,7 @@ declare namespace ol { /** * Events emitted by ol.interaction.Select instances are instances of this type. */ - class SelectEvent { + class SelectEvent extends ol.events.Event { /** * Deselected features array. @@ -2551,6 +2551,12 @@ declare namespace ol { function targetNotEditable(mapBrowserEvent: ol.MapBrowserEvent): boolean; } interface ConditionType { (mapBrowseEvent: ol.MapBrowserEvent): boolean; } + class Event { + target: any; + type: string; + preventDefault(): void; + stopPropagation(): void; + } } namespace extent { @@ -3601,7 +3607,7 @@ declare namespace ol { class DragAndDrop { } - class DragAndDropEvent { + class DragAndDropEvent extends ol.events.Event { } class DragBox { @@ -3623,7 +3629,7 @@ declare namespace ol { constructor(opt_options?: olx.interaction.DrawOptions) } - class DrawEvent { + class DrawEvent extends ol.events.Event { } class Interaction extends ol.Object { @@ -4129,7 +4135,7 @@ declare namespace ol { namespace render { - class Event { + class Event extends ol.events.Event { } class VectorContext { @@ -4167,7 +4173,7 @@ declare namespace ol { class ImageCanvas extends Image { } - class ImageEvent { + class ImageEvent extends ol.events.Event { } class ImageMapGuide extends Image { @@ -4216,7 +4222,7 @@ declare namespace ol { class TileDebug extends Tile { } - class TileEvent { + class TileEvent extends ol.events.Event { } class TileImage extends UrlTile { @@ -4301,7 +4307,7 @@ declare namespace ol { getFeaturesAtCoordinate(coordinate: ol.Coordinate): ol.Feature[]; } - class VectorEvent { + class VectorEvent extends ol.events.Event { } class VectorTile extends UrlTile { diff --git a/oracledb/oracledb-1.5.0-tests.ts b/oracledb/oracledb-1.5.0-tests.ts new file mode 100644 index 0000000000..19976034ea --- /dev/null +++ b/oracledb/oracledb-1.5.0-tests.ts @@ -0,0 +1,32 @@ +/// + +import * as OracleDB from 'oracledb' + +OracleDB.getConnection( + { + user: "hr", + password: "welcome", + connectString: "localhost/XE" + }, + function(err, connection) { + if (err) { + console.error(err.message) + return + } + connection.execute( + "SELECT department_id, department_name " + + "FROM departments " + + "WHERE manager_id < :id", + [110], // bind value for :id + function (err, result) { + if (err) { + console.error(err.message) + return + } + console.log(result.rows); + console.log(result.rows[0].department_id); // when outFormet is OBJECT + console.log(result.metaData[0].name); + } + ) + } +) diff --git a/oracledb/oracledb-1.5.0.d.ts b/oracledb/oracledb-1.5.0.d.ts new file mode 100644 index 0000000000..c57a8efaae --- /dev/null +++ b/oracledb/oracledb-1.5.0.d.ts @@ -0,0 +1,308 @@ +// Type definitions for oracledb v1.5.0 +// Project: https://github.com/oracle/node-oracledb +// Definitions by: Richard Natal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'oracledb' { + import * as stream from "stream"; + + export interface ILob { + chunkSize: number; + length: number; + pieceSize: number; + offset?: number; + type: string; + /** + * Release method on ILob class. + * @remarks The cleanup() called by Release() only frees OCI error handle and Lob + * locator. These calls acquire mutex on OCI environment handle very briefly. + */ + release?(): void; + /** + * Read method on ILob class. + * @param {(err : any, chunk: string | Buffer) => void} callback Callback to recive the data from lob. + * @remarks CLobs send strings while BLobs send Buffer object. + */ + read?(callback: (err: any, chunk: string | Buffer) => void): void; + /** + * Read method on ILob class. + * @param {Buffer} data Data write into Lob. + * @param {(err: any) => void} callback Callback executed when writ is finished or when some error occured. + * @remarks CLobs send strings while BLobs send Buffer object. + */ + write?(data: Buffer, callback: (err: any) => void): void; + } + + export interface Lob extends stream.Duplex { + iLob: ILob; + chunkSize: number; + length: number; + pieceSize: number; + type: string; + + /** + * Do not call this... used internally by node-oracledb + */ + constructor(iLob: ILob, opts: stream.DuplexOptions): Lob; + constructor(iLob: ILob): Lob; + + /** + * Closes the current LOB. + * @param {(err: any) => void} callback? When passed, is called after the release. + * @returns void + */ + close(callback: (err: any) => void): void; + close(): void; + } + + export interface IConnectionAttributes { + user?: string; + password?: string; + connectString: string; + stmtCacheSize?: number; + externalAuth?: boolean; + } + + export interface IPoolAttributes extends IConnectionAttributes { + poolMax?: number; + poolMin?: number; + poolIncrement?: number; + poolTimeout?: number; + } + + export interface IExecuteOptions { + /** Maximum number of rows that will be retrieved. Used when resultSet is false. */ + maxRows?: number; + /** Number of rows to be fetched in advance. */ + prefetchRows?: number; + /** Result format - ARRAY o OBJECT */ + outFormat?: number; + /** Should use ResultSet or not. */ + resultSet?: boolean; + /** Transaction should auto commit after each statement? */ + autoCommit?: boolean; + } + + export interface IExecuteReturn { + /** Number o rows affected by the statement (used for inserts / updates)*/ + rowsAffected?: number; + /** When the statement has out parameters, it comes here. */ + outBinds?: Array | Object; + /** Metadata information - just columns names for now. */ + metaData?: Array; + /** When not using ResultSet, query results comes here. */ + rows?: Array> | Array; + /** When using ResultSet, query results comes here. */ + resultSet?: IResultSet; + } + + export interface IMetaData { + /** Column name */ + name: string; + } + + export interface IResultSet { + /** Metadata information - just columns names for now. */ + metaData?: Array; + /** + * Closes the ResultSet. + * @param {(err:any)=>void} callback Callback called on finish or when some error occurs + * @returns void + * @remarks After using a resultSet, it must be closed to free the resources used by the driver. + */ + close(callback: (err: any) => void): void; + /** + * Fetch one row from ResultSet. + * @param {(err:any,row:Array|Object)=>void} callback Callback called when the row is available or when some error occurs. + * @returns void + */ + getRow(callback: (err: any, row: Array | Object) => void): void; + /** + * Fetch some rows from ResultSet. + * @param {number} rowCount Number of rows to be fetched. + * @param {(err:any,rows:Array>|Array)=>void} callback Callback called when the rows are available, or when some error occurs. + * @returns void + * @remarks When the number of rows passed to the callback is less than the rowCount, no more rows are available to be fetched. + */ + getRows(rowCount: number, callback: (err: any, rows: Array> | Array) => void): void; + } + + export interface IConnection { + /** Statement cache size in bytes (read-only)*/ + stmtCacheSize: number; + /** Client id (to be sent to database) (write-only)*/ + clientId: string; + /** Module (write-only) */ + module: string; + /** Action */ + action: string; + /** Oracle server version */ + oracleServerVersion: number; + + /** + * Execute method on Connection class. + * @param {string} sql SQL Statement. + * @param {Object|Array} Binds Binds Object/Array + * @param {IExecuteOptions} options Options object + * @param {(err: any, value: IExecuteReturn) => void} callback Callback function to receive the result. + */ + execute(sql: string, + binds: Object | Array, + options: IExecuteOptions, + callback: (err: any, value: IExecuteReturn) => void): void; + + /** + * Execute method on Connection class. + * @param {string} sql SQL Statement. + * @param {Object|Array} Binds Binds Object/Array + * @param {(err: any, value: IExecuteReturn) => void} callback Callback function to receive the result. + */ + execute(sql: string, + binds: Object | Array, + callback: (err: any, value: IExecuteReturn) => void): void; + + /** + * Execute method on Connection class. + * @param {string} sql SQL Statement. + * @param {IExecuteOptions} options Options object + * @param {(err: any, value: IExecuteReturn) => void} callback Callback function to receive the result. + */ + execute(sql: string, + options: IExecuteOptions, + callback: (err: any, value: IExecuteReturn) => void): void; + + /** + * Execute method on Connection class. + * @param {string} sql SQL Statement. + * @param {(err: any, value: IExecuteReturn) => void} callback Callback function to receive the result. + */ + execute(sql: string, + callback: (err: any, value: IExecuteReturn) => void): void; + + /** + * Release method on Connection class. + * @param {(err: any) => void} callback Callback function to be called when the connection has been released. + */ + release(callback: (err: any) => void): void; + + /** + * Send a commit requisition to the database. + * @param {(err: any) => void} callback Callback on commit done. + */ + commit(callback: (err: any) => void): void; + + /** + * Send a rollback requisition to database. + * @param {(err: any) => void} callback Callback on rollback done. + */ + rollback(callback: (err: any) => void): void; + + /** + * Send a break to the database. + * @param {(err: any) => void} callback Callback on break done. + */ + break(callback: (err: any) => void): void; + } + + export interface IConnectionPool { + poolMax: number; + poolMin: number; + poolIncrement: number; + poolTimeout: number; + connectionsOpen: number; + connectionsInUse: number; + stmtCacheSize: number; + /** + * Finalizes the connection pool. + * @param {(err:any)=>void} callback Callback called when the pool is terminated or when some error occurs + * @returns void + */ + terminate(callback: (err: any) => void): void; + /** + * Retrieve a connection from the pool. + * @param {(err:any,connection:IConnection)=>void} callback Callback called when the connection is available or when some error occurs. + * @returns void + * @see {@link https://jsao.io/2015/03/making-a-wrapper-module-for-the-node-js-driver-for-oracle-database/} + * @see {@link https://github.com/OraOpenSource/orawrap} + */ + getConnection(callback: (err: any, connection: IConnection) => void): void; + } + + export const DEFAULT: number; + /** Data type */ + export const STRING: number; + /** Data type */ + export const NUMBER: number; + /** Data type */ + export const DATE: number; + /** Data type */ + export const CURSOR: number; + /** Data type */ + export const BUFFER: number; + /** Data type */ + export const CLOB: number; + /** Data type */ + export const BLOB: number; + /** Bind direction */ + export const BIND_IN: number; + /** Bind direction */ + export const BIND_INOUT: number; + /** Bind direction */ + export const BIND_OUT: number; + /** outFormat */ + export const ARRAY: number; + /** outFormat */ + export const OBJECT: number; + + /** + * Do not use this method - used internally by node-oracledb. + */ + export function newLob(iLob: ILob): Lob; + + /** + * Creates a connection with the database. + * @param {IConnectionAttributes} connectionAttributes Parameters to stablish the connection. + * @param {(err:any,connection:IConnection)=>void} callback Callback to run when the connection gets stablished or when some error occurs. + * @returns void + */ + export function getConnection(connectionAttributes: IConnectionAttributes, callback: (err: any, connection: IConnection) => void): void; + + /** + * Creates a database managed connection pool. + * @param {IPoolAttributes} poolAttributes Parameters to stablish the connection pool. + * @param {(err:any,connection:IConnectionPool)=>void} callback Callback to run when the connection pool gets created or when some error occurs. + * @returns void + */ + export function createPool(poolAttributes: IPoolAttributes, callback: (err: any, connection: IConnectionPool) => void): void; + + /** Default maximum connections in created pools */ + export var poolMax: number; + /** Default minimum connections in created pools */ + export var poolMin: number; + /** Default number of connections to increment when available connections reach 0 in created pools. poolMax will be respected.*/ + export var poolIncrement: number; + /** Default timeout for unused connections in pool to be released. poolMin will be respected.*/ + export var poolTimeout: number; + /** Default size of statements cache. Used to speed up creating queries.*/ + export var stmtCacheSize: number; + /** Default number of rows that the driver will fetch in each query.*/ + export var prefetchRows: number; + /** Default transaction behaviour of auto commit for each statement. */ + export var autoCommit: boolean; + /** Default maximum number of rows to be fetched in statements not using ResultSets */ + export var maxRows: number; + /** Default format for returning rows. When ARRAY, it will return Array>. When OBJECT, it will return Array. */ + export var outFormat: number; + /** node-oracledb driver version. */ + export var version: number; + export var connectionClass: string; + /** Default authentication/authorization method. When true, the SO trusted user will be used. */ + export var externalAuth: boolean; + export var fetchAsString: any; + /** Default size in bytes that the driver will fetch from LOBs in advance. */ + export var lobPrefetchSize: number; + /** Version of OCI that is used. */ + export var oracleClientVersion: number; +} diff --git a/oracledb/oracledb-tests.ts b/oracledb/oracledb-tests.ts index 674775bd79..3757afd410 100644 --- a/oracledb/oracledb-tests.ts +++ b/oracledb/oracledb-tests.ts @@ -1,5 +1,4 @@ /// -/// import * as OracleDB from 'oracledb'; @@ -20,12 +19,39 @@ OracleDB.getConnection( [110], // bind value for :id function(err, result) { if (err) { - console.error(err.message); return; + console.error(err.message); + } else { + console.log(result.rows); + console.log(result.rows[0].department_id); // when outFormet is OBJECT + console.log(result.metaData[0].name); } - console.log(result.rows); - console.log(result.rows[0].department_id); // when outFormet is OBJECT - console.log(result.metaData[0].name); + connection.release(); } ); } ); + +OracleDB.getConnection( + { + user: "hr", + password: "welcome", + connectString: "localhost/XE" + } +).then((connection: OracleDB.IConnection) => { + return connection.execute( + "SELECT department_id, department_name " + + "FROM departments " + + "WHERE manager_id < :id", + [110] + ).then(result => { + console.log(result.rows); + console.log(result.rows[0].department_id); // when outFormet is OBJECT + console.log(result.metaData[0].name); + }).catch((err: any) => { + console.error(err.message); + }).then(() => { + return connection.release(); + }); +}).catch((err: any) => { + console.error(err.message); +}); diff --git a/oracledb/oracledb.d.ts b/oracledb/oracledb.d.ts index c57a8efaae..8101f8f471 100644 --- a/oracledb/oracledb.d.ts +++ b/oracledb/oracledb.d.ts @@ -1,4 +1,4 @@ -// Type definitions for oracledb v1.5.0 +// Type definitions for oracledb v1.10.0 // Project: https://github.com/oracle/node-oracledb // Definitions by: Richard Natal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,6 +8,14 @@ declare module 'oracledb' { import * as stream from "stream"; + export type TRet = T | IPromise; + export type TFunc = (value: T) => TRet; + + export interface IPromise { + catch(onReject: TFunc) : IPromise; + then(onResolve?: TFunc, onReject?: TFunc) : IPromise; + } + export interface ILob { chunkSize: number; length: number; @@ -37,10 +45,21 @@ declare module 'oracledb' { export interface Lob extends stream.Duplex { iLob: ILob; + /** This corresponds to the size used by the Oracle LOB layer when accessing or modifying the LOB value. */ chunkSize: number; + /** Length of a queried LOB in bytes (for BLOBs) or characters (for CLOBs). */ length: number; + /** + * he number of bytes (for BLOBs) or characters (for CLOBs) to read for each Stream 'data' event of a queried LOB. + * The default value is chunkSize. + * For efficiency, it is recommended that pieceSize be a multiple of chunkSize. + * The maximum value for pieceSize is limited to the value of UINT_MAX. + */ pieceSize: number; - type: string; + /** + * This read-only attribute shows the type of Lob being used. It will have the value of one of the constants Oracledb.BLOB or Oracledb.CLOB. The value is derived from the bind type when using LOB bind variables, or from the column type when a LOB is returned by a query. + */ + type: number; /** * Do not call this... used internally by node-oracledb @@ -73,119 +92,187 @@ declare module 'oracledb' { } export interface IExecuteOptions { - /** Maximum number of rows that will be retrieved. Used when resultSet is false. */ - maxRows?: number; - /** Number of rows to be fetched in advance. */ - prefetchRows?: number; - /** Result format - ARRAY o OBJECT */ - outFormat?: number; - /** Should use ResultSet or not. */ - resultSet?: boolean; - /** Transaction should auto commit after each statement? */ + /** + * Transaction should auto commit after each statement? + * Overrides Oracledb autoCommit. + */ autoCommit?: boolean; + /** + * Determines whether additional metadata is available for queries and for REF CURSORs returned from PL/SQL blocks. + * Overrides Oracledb extendedMetaData. + */ + extendedMetaData?: boolean; + /** + * Object defining how query column data should be represented in JavaScript. + * The fetchInfo property can be used to indicate that number or date columns in a query should be returned as strings instead of their native format. The property can be used in conjunction with, or instead of, the global setting fetchAsString. + * For example: + * + * fetchInfo: + * { + * "HIRE_DATE": { type : oracledb.STRING }, // return the date as a string + * "COMMISSION_PCT": { type : oracledb.DEFAULT } // override Oracledb.fetchAsString + * } + * + * Each column is specified by name, using Oracle's standard naming convention. + * The valid values for type are STRING and DEFAULT. The former indicates that the given column should be returned as a string. The latter can be used to override any global mapping given by fetchAsString and allow the column data for this query to be returned in native format. + * The maximum length of a string created by type mapping is 200 bytes. However, if a database column that is already of type STRING is specified in fetchInfo, then the actual database metadata will be used to determine the maximum length. + * Columns fetched from REF CURSORS are not mapped by fetchInfo settings in the execute() call. Use the global fetchAsString instead. + */ + fetchInfo?: Object; + /** + * Maximum number of rows that will be retrieved. Used when resultSet is false. + * Overrides Oracledb maxRows. + */ + maxRows?: number; + /** + * Result format - ARRAY o OBJECT + * Overrides Oracledb outFormat. + */ + outFormat?: number; + /** + * Number of rows to be fetched in advance. + * Overrides Oracledb prefetchRows. + */ + prefetchRows?: number; + /** + * Determines whether query results should be returned as a ResultSet object or directly. The default is false. + */ + resultSet?: boolean; } export interface IExecuteReturn { - /** Number o rows affected by the statement (used for inserts / updates)*/ - rowsAffected?: number; - /** When the statement has out parameters, it comes here. */ - outBinds?: Array | Object; - /** Metadata information - just columns names for now. */ + /** Metadata information - column names is always given. If the Oracledb extendedMetaData or execute() option extendedMetaData are true then additional information is included. */ metaData?: Array; - /** When not using ResultSet, query results comes here. */ - rows?: Array> | Array; - /** When using ResultSet, query results comes here. */ + /** This is either an array or an object containing OUT and IN OUT bind values. If bindParams is passed as an array, then outBinds is returned as an array. If bindParams is passed as an object, then outBinds is returned as an object. */ + outBinds?: Array | Object; + /** For SELECT statements when the resultSet option is true, use the resultSet object to fetch rows. See ResultSet Class. */ resultSet?: IResultSet; + /** For SELECT statements where the resultSet option is false or unspecified, rows contains an array of fetched rows. It will be NULL if there is an error or the SQL statement was not a SELECT statement. By default, the rows are in an array of column value arrays, but this can be changed to arrays of objects by setting outFormat to OBJECT. If a single row is fetched, then rows is an array that contains one single row. The number of rows returned is limited to the maxRows configuration property of the Oracledb object, although this may be overridden in any execute() call. */ + rows?: Array> | Array; + /** For DML statements (including SELECT FOR UPDATE) this contains the number of rows affected, for example the number of rows inserted. For non-DML statements such as queries, or if no rows are affected, then rowsAffected will be zero. */ + rowsAffected?: number; } export interface IMetaData { - /** Column name */ + /** The column name follows Oracle's standard name-casing rules. It will commonly be uppercase, since most applications create tables using unquoted, case-insensitive names. */ name: string; + /** one of the Node-oracledb Type Constant values. */ + fetchType?: number; + /** one of the Node-oracledb Type Constant values. */ + dbType?: number; + /** the database byte size. This is only set for DB_TYPE_VARCHAR, DB_TYPE_CHAR and DB_TYPE_RAW column types. */ + byteSize?: number; + /** set only for DB_TYPE_NUMBER, DB_TYPE_TIMESTAMP, DB_TYPE_TIMESTAMP_TZ and DB_TYPE_TIMESTAMP_LTZ columns. */ + precision?: number; + /** set only for DB_TYPE_NUMBER columns. */ + scale: number; + /** indicates whether NULL values are permitted for this column. */ + nullable?: boolean; } export interface IResultSet { - /** Metadata information - just columns names for now. */ - metaData?: Array; /** - * Closes the ResultSet. - * @param {(err:any)=>void} callback Callback called on finish or when some error occurs + * Contains an array of objects with metadata about the query or REF CURSOR columns. + * Each column's name is always given. If the Oracledb extendedMetaData or execute() option extendedMetaData are true then additional information is included. + */ + metaData?: Array; + + /** + * Closes a ResultSet. Applications should always call this at the end of fetch or when no more rows are needed. + * @param {(err:any)=>void} callback Callback called on finish or when some error occurs. * @returns void - * @remarks After using a resultSet, it must be closed to free the resources used by the driver. + * @remarks Applications should always call this at the end of fetch or when no more rows are needed. */ close(callback: (err: any) => void): void; + /** - * Fetch one row from ResultSet. + * Closes a ResultSet. Applications should always call this at the end of fetch or when no more rows are needed. + * @returns A void Promise on finish or when some error occurs. + * @remarks Applications should always call this at the end of fetch or when no more rows are needed. + */ + close(): IPromise; + + /** + * This call fetches one row of the result set as an object or an array of column values, depending on the value of outFormat. + * At the end of fetching, the ResultSet should be freed by calling close(). * @param {(err:any,row:Array|Object)=>void} callback Callback called when the row is available or when some error occurs. * @returns void */ getRow(callback: (err: any, row: Array | Object) => void): void; + /** - * Fetch some rows from ResultSet. - * @param {number} rowCount Number of rows to be fetched. - * @param {(err:any,rows:Array>|Array)=>void} callback Callback called when the rows are available, or when some error occurs. - * @returns void - * @remarks When the number of rows passed to the callback is less than the rowCount, no more rows are available to be fetched. + * This call fetches one row of the result set as an object or an array of column values, depending on the value of outFormat. + * At the end of fetching, the ResultSet should be freed by calling close(). + * @returns Promise when the row is available or when some error occurs. */ - getRows(rowCount: number, callback: (err: any, rows: Array> | Array) => void): void; + getRow(): IPromise | Object>; + + /** + * This synchronous method converts a ResultSet into a stream. + * It can be used to make ResultSets from top-level queries or from REF CURSOR bind variables streamable. To make top-level queries streamable, the alternative connection.queryStream() method may be easier to use. + * @returns synchronous stream of result set. + */ + toQueryStream(): stream.Readable; } export interface IConnection { - /** Statement cache size in bytes (read-only)*/ - stmtCacheSize: number; - /** Client id (to be sent to database) (write-only)*/ - clientId: string; - /** Module (write-only) */ - module: string; - /** Action */ + /** + * The action attribute for end-to-end application tracing. + * This is a write-only property. Displaying a Connection object will show a value of null for this attribute. See End-to-end Tracing, Mid-tier Authentication, and Auditing. + */ action: string; - /** Oracle server version */ + /** + * The client identifier for end-to-end application tracing, use with mid-tier authentication, and with Virtual Private Databases. + * This is a write-only property. Displaying a Connection object will show a value of null for this attribute. See End-to-end Tracing, Mid-tier Authentication, and Auditing. + */ + clientId: string; + /** + * The module attribute for end-to-end application tracing. + * This is a write-only property. Displaying a Connection object will show a value of null for this attribute. See End-to-end Tracing, Mid-tier Authentication, and Auditing. + */ + module: string; + /** + * This readonly property gives a numeric representation of the Oracle database version. For version a.b.c.d.e, this property gives the number: (100000000 * a) + (1000000 * b) + (10000 * c) + (100 * d) + e + */ oracleServerVersion: number; + /** + * The number of statements to be cached in the statement cache of the connection. The default value is the stmtCacheSize property in effect in the Pool object when the connection is created in the pool. + */ + stmtCacheSize: number; /** - * Execute method on Connection class. - * @param {string} sql SQL Statement. - * @param {Object|Array} Binds Binds Object/Array - * @param {IExecuteOptions} options Options object - * @param {(err: any, value: IExecuteReturn) => void} callback Callback function to receive the result. + * This call stops the currently running operation on the connection. + * If there is no operation in progress or the operation has completed by the time the break is issued, the break() is effectively a no-op. + * If the running asynchronous operation is interrupted, its callback will return an error. + * @param {(err: any) => void} callback Callback on break done. */ - execute(sql: string, - binds: Object | Array, - options: IExecuteOptions, - callback: (err: any, value: IExecuteReturn) => void): void; + break(callback: (err: any) => void): void; /** - * Execute method on Connection class. - * @param {string} sql SQL Statement. - * @param {Object|Array} Binds Binds Object/Array - * @param {(err: any, value: IExecuteReturn) => void} callback Callback function to receive the result. + * This call stops the currently running operation on the connection. + * If there is no operation in progress or the operation has completed by the time the break is issued, the break() is effectively a no-op. + * If the running asynchronous operation is interrupted, its callback will return an error. + * @returns A void promise when break is done. */ - execute(sql: string, - binds: Object | Array, - callback: (err: any, value: IExecuteReturn) => void): void; + break(): IPromise; /** - * Execute method on Connection class. - * @param {string} sql SQL Statement. - * @param {IExecuteOptions} options Options object - * @param {(err: any, value: IExecuteReturn) => void} callback Callback function to receive the result. + * Releases a connection. If the connection was obtained from the pool, the connection is returned to the pool and is available for reuse. + * Note: calling close() when connections are no longer required is strongly encouraged. Releasing helps avoid resource leakage and can improve system efficiency. + * When a connection is released, any ongoing transaction on the connection is rolled back. + * After releasing a connection to a pool, there is no guarantee a subsequent getConnection() call gets back the same database connection. The application must redo any ALTER SESSION statements on the new connection object, as required. + * @param {(err: any) => void} callback Callback on close done. */ - execute(sql: string, - options: IExecuteOptions, - callback: (err: any, value: IExecuteReturn) => void): void; + close(callback: (err: any) => void): void; /** - * Execute method on Connection class. - * @param {string} sql SQL Statement. - * @param {(err: any, value: IExecuteReturn) => void} callback Callback function to receive the result. + * Releases a connection. If the connection was obtained from the pool, the connection is returned to the pool and is available for reuse. + * Note: calling close() when connections are no longer required is strongly encouraged. Releasing helps avoid resource leakage and can improve system efficiency. + * When a connection is released, any ongoing transaction on the connection is rolled back. + * After releasing a connection to a pool, there is no guarantee a subsequent getConnection() call gets back the same database connection. The application must redo any ALTER SESSION statements on the new connection object, as required. + * @returns A void Promise on close done. */ - execute(sql: string, - callback: (err: any, value: IExecuteReturn) => void): void; - - /** - * Release method on Connection class. - * @param {(err: any) => void} callback Callback function to be called when the connection has been released. - */ - release(callback: (err: any) => void): void; + close(): IPromise; /** * Send a commit requisition to the database. @@ -193,6 +280,99 @@ declare module 'oracledb' { */ commit(callback: (err: any) => void): void; + /** + * Send a commit requisition to the database. + * @returns A void Promise on commit done. + */ + commit(): IPromise; + + /** + * This call executes a SQL or PL/SQL statement. See SQL Execution for examples. + * The statement to be executed may contain IN binds, OUT or IN OUT bind values or variables, which are bound using either an object or an array. + * A callback function returns a result object, containing any fetched rows, the values of any OUT and IN OUT bind variables, and the number of rows affected by the execution of DML statements. + * @param {string} sql SQL Statement. + * @param {Object|Array} bindParams Binds Object/Array + * @param {IExecuteOptions} options Options object + * @param {(err: any, value: IExecuteReturn) => void} callback Callback function to receive the result. + */ + execute(sql: string, + bindParams: Object | Array, + options: IExecuteOptions, + callback: (err: any, value: IExecuteReturn) => void): void; + + /** + * This call executes a SQL or PL/SQL statement. See SQL Execution for examples. + * The statement to be executed may contain IN binds, OUT or IN OUT bind values or variables, which are bound using either an object or an array. + * A callback function returns a result object, containing any fetched rows, the values of any OUT and IN OUT bind variables, and the number of rows affected by the execution of DML statements. + * @param {string} sql SQL Statement. + * @param {Object|Array} bindParams Binds Object/Array + * @param {(err: any, value: IExecuteReturn) => void} callback Callback function to receive the result. + */ + execute(sql: string, + bindParams: Object | Array, + callback: (err: any, value: IExecuteReturn) => void): void; + + /** + * This call executes a SQL or PL/SQL statement. See SQL Execution for examples. + * The statement to be executed may contain IN binds, OUT or IN OUT bind values or variables, which are bound using either an object or an array. + * A callback function returns a result object, containing any fetched rows, the values of any OUT and IN OUT bind variables, and the number of rows affected by the execution of DML statements. + * @param {string} sql SQL Statement. + * @param {IExecuteOptions} options Options object + * @param {(err: any, value: IExecuteReturn) => void} callback Callback function to receive the result. + */ + execute(sql: string, + options: IExecuteOptions, + callback: (err: any, value: IExecuteReturn) => void): void; + + /** + * This call executes a SQL or PL/SQL statement. See SQL Execution for examples. + * The statement to be executed may contain IN binds, OUT or IN OUT bind values or variables, which are bound using either an object or an array. + * A callback function returns a result object, containing any fetched rows, the values of any OUT and IN OUT bind variables, and the number of rows affected by the execution of DML statements. + * @param {string} sql SQL Statement. + * @param {(err: any, value: IExecuteReturn) => void} callback Callback function to receive the result. + */ + execute(sql: string, + callback: (err: any, value: IExecuteReturn) => void): void; + + /** + * This call executes a SQL or PL/SQL statement. See SQL Execution for examples. + * The statement to be executed may contain IN binds, OUT or IN OUT bind values or variables, which are bound using either an object or an array. + * @param {string} sql SQL Statement. + * @param {Object|Array} bindParams Binds Object/Array + * @param {IExecuteOptions} options Options object + * @returns A Promise of a result object, containing any fetched rows, the values of any OUT and IN OUT bind variables, and the number of rows affected by the execution of DML statements. + */ + execute(sql: string, + bindParams?: Object | Array, + options?: IExecuteOptions): IPromise; + + /** + * This function provides query streaming support. The parameters are the same as execute() except a callback is not used. Instead this function returns a stream used to fetch data. + * Each row is returned as a data event. Query metadata is available via a metadata event. The end event indicates the end of the query results. + * Query results must be fetched to completion to avoid resource leaks. + * The connection must remain open until the stream is completely read. + * For tuning purposes the oracledb.maxRows property can be used to size an internal buffer used by queryStream(). Note it does not limit the number of rows returned by the stream. The oracledb.prefetchRows value will also affect performance. + * @param {string} sql SQL Statement. + * @param {Object|Array} bindParams Binds Object/Array + * @param {IExecuteOptions} options Options object + * @returns Readable Stream for queries. + */ + queryStream(sql: string, + bindParams?: Object | Array, + options?: IExecuteOptions): stream.Readable; + + /** + * An alias for Connection.close(). + * @param {(err: any) => void} callback Callback on close done. + */ + release(callback: (err: any) => void): void; + + /** + * An alias for Connection.close(). + * @returns A void Promise on close done. + */ + release(): IPromise; + /** * Send a rollback requisition to database. * @param {(err: any) => void} callback Callback on rollback done. @@ -200,34 +380,94 @@ declare module 'oracledb' { rollback(callback: (err: any) => void): void; /** - * Send a break to the database. - * @param {(err: any) => void} callback Callback on break done. + * Send a rollback requisition to database. + * @returns A void Promise on rollback done. */ - break(callback: (err: any) => void): void; + rollback(): IPromise } export interface IConnectionPool { - poolMax: number; - poolMin: number; - poolIncrement: number; - poolTimeout: number; - connectionsOpen: number; + /** + * The number of currently active connections in the connection pool i.e. the number of connections currently checked-out using getConnection(). + */ connectionsInUse: number; + /** + * The number of currently open connections in the underlying connection pool. + */ + connectionsOpen: number; + /** + * The number of connections that are opened whenever a connection request exceeds the number of currently open connections. + */ + poolIncrement: number; + /** + * The maximum number of connections that can be open in the connection pool. + */ + poolMax: number; + /** + * The minimum number of connections a connection pool maintains, even when there is no activity to the target database. + */ + poolMin: number; + /** + * The time (in seconds) after which the pool terminates idle connections (unused in the pool). The number of connections does not drop below poolMin. + */ + poolTimeout: number; + /** + * Determines whether requests for connections from the pool are queued when the number of connections "checked out" from the pool has reached the maximum number specified by poolMax. + */ + queueRequests: number; + /** + * The time (in milliseconds) that a connection request should wait in the queue before the request is terminated. + */ + queueTimeout: number; + /** + * The number of statements to be cached in the statement cache of each connection. + */ stmtCacheSize: number; + /** * Finalizes the connection pool. * @param {(err:any)=>void} callback Callback called when the pool is terminated or when some error occurs * @returns void */ - terminate(callback: (err: any) => void): void; + close(callback: (err: any) => void): void; + /** - * Retrieve a connection from the pool. + * Finalizes the connection pool. + * @returns Promise to when the close finishes. + */ + close(): IPromise; + + /** + * This method obtains a connection from the connection pool. + * If a previously opened connection is available in the pool, that connection is returned. If all connections in the pool are in use, a new connection is created and returned to the caller, as long as the number of connections does not exceed the specified maximum for the pool. If the pool is at its maximum limit, the getConnection() call results in an error, such as ORA-24418: Cannot open further sessions. * @param {(err:any,connection:IConnection)=>void} callback Callback called when the connection is available or when some error occurs. * @returns void * @see {@link https://jsao.io/2015/03/making-a-wrapper-module-for-the-node-js-driver-for-oracle-database/} * @see {@link https://github.com/OraOpenSource/orawrap} */ getConnection(callback: (err: any, connection: IConnection) => void): void; + + /** + * This method obtains a connection from the connection pool. + * If a previously opened connection is available in the pool, that connection is returned. If all connections in the pool are in use, a new connection is created and returned to the caller, as long as the number of connections does not exceed the specified maximum for the pool. If the pool is at its maximum limit, the getConnection() call results in an error, such as ORA-24418: Cannot open further sessions. + * @returns An IConnection Promise to when the connection is available or when some error occurs. + * @see {@link https://jsao.io/2015/03/making-a-wrapper-module-for-the-node-js-driver-for-oracle-database/} + * @see {@link https://github.com/OraOpenSource/orawrap} + */ + getConnection(): IPromise; + + /** + * An alias for IConnectionPool.close(). + * @param {(err:any)=>void} callback Callback called when the pool is terminated or when some error occurs + * @returns void + */ + terminate(callback: (err: any) => void): void; + + /** + * An alias for IConnectionPool.close(). + * @returns Promise to when the close finishes. + */ + terminate(): IPromise; } export const DEFAULT: number; @@ -261,13 +501,62 @@ declare module 'oracledb' { */ export function newLob(iLob: ILob): Lob; + /** Default transaction behaviour of auto commit for each statement. */ + export var autoCommit: boolean; /** - * Creates a connection with the database. - * @param {IConnectionAttributes} connectionAttributes Parameters to stablish the connection. - * @param {(err:any,connection:IConnection)=>void} callback Callback to run when the connection gets stablished or when some error occurs. - * @returns void + * The user-chosen Connection class value defines a logical name for connections. Most single purpose applications should set connectionClass when using a connection pool or DRCP. + * When a pooled session has a connection class, Oracle ensures that the session is not shared outside of that connection class. */ - export function getConnection(connectionAttributes: IConnectionAttributes, callback: (err: any, connection: IConnection) => void): void; + export var connectionClass: string; + /** + * Determines whether additional metadata is available for queries and for REF CURSORs returned from PL/SQL blocks. + * The default value for extendedMetaData is false. With this value, the result.metaData result.resultSet.metaData objects only include column names. + */ + export var extendedMetaData: boolean; + /** Default authentication/authorization method. When true, the SO trusted user will be used. */ + export var externalAuth: boolean; + /** + * An array of node-oracledb types. When any column having the specified type is queried with execute(), the column data is returned as a string instead of the native representation. For column types not specified in fetchAsString, native types will be returned. + * By default all columns are returned as native types. + */ + export var fetchAsString: Array; + /** Default size in bytes that the driver will fetch from LOBs in advance. */ + export var lobPrefetchSize: number; + /** Default maximum number of rows to be fetched in statements not using ResultSets */ + export var maxRows: number; + /** Version of OCI that is used. */ + export var oracleClientVersion: number; + /** Default format for returning rows. When ARRAY, it will return Array>. When OBJECT, it will return Array. */ + export var outFormat: number; + /** Default number of connections to increment when available connections reach 0 in created pools. poolMax will be respected.*/ + export var poolIncrement: number; + /** Default maximum connections in created pools */ + export var poolMax: number; + /** Default minimum connections in created pools */ + export var poolMin: number; + /** Default timeout for unused connections in pool to be released. poolMin will be respected.*/ + export var poolTimeout: number; + /** Default number of rows that the driver will fetch in each query.*/ + export var prefetchRows: number; + /** + * Node-oracledb supports Promises on all methods. The standard Promise library is used in Node 0.12 and greater. Promise support is not enabled by default in Node 0.10. + */ + export var Promise: any; + /** + * If this property is true and the number of connections "checked out" from the pool has reached the number specified by poolMax, then new requests for connections are queued until in-use connections are released. + * If this property is false and a request for a connection is made from a pool where the number of "checked out" connections has reached poolMax, then an ORA-24418 error indicating that further sessions cannot be opened will be returned. + * The default value is true. + */ + export var queueRequests: boolean; + /** + * The number of milliseconds after which connection requests waiting in the connection request queue are terminated. If queueTimeout is 0, then queued connection requests are never terminated. + * The default value is 60000. + */ + export var queueTimeout: number; + /** Default size of statements cache. Used to speed up creating queries.*/ + export var stmtCacheSize: number; + /** node-oracledb driver version. */ + export var version: number; /** * Creates a database managed connection pool. @@ -277,32 +566,25 @@ declare module 'oracledb' { */ export function createPool(poolAttributes: IPoolAttributes, callback: (err: any, connection: IConnectionPool) => void): void; - /** Default maximum connections in created pools */ - export var poolMax: number; - /** Default minimum connections in created pools */ - export var poolMin: number; - /** Default number of connections to increment when available connections reach 0 in created pools. poolMax will be respected.*/ - export var poolIncrement: number; - /** Default timeout for unused connections in pool to be released. poolMin will be respected.*/ - export var poolTimeout: number; - /** Default size of statements cache. Used to speed up creating queries.*/ - export var stmtCacheSize: number; - /** Default number of rows that the driver will fetch in each query.*/ - export var prefetchRows: number; - /** Default transaction behaviour of auto commit for each statement. */ - export var autoCommit: boolean; - /** Default maximum number of rows to be fetched in statements not using ResultSets */ - export var maxRows: number; - /** Default format for returning rows. When ARRAY, it will return Array>. When OBJECT, it will return Array. */ - export var outFormat: number; - /** node-oracledb driver version. */ - export var version: number; - export var connectionClass: string; - /** Default authentication/authorization method. When true, the SO trusted user will be used. */ - export var externalAuth: boolean; - export var fetchAsString: any; - /** Default size in bytes that the driver will fetch from LOBs in advance. */ - export var lobPrefetchSize: number; - /** Version of OCI that is used. */ - export var oracleClientVersion: number; + /** + * Creates a database managed connection pool. + * @param {IPoolAttributes} poolAttributes Parameters to stablish the connection pool. + * @returns Promise {(connection:IConnectionPool)=>any} Promise with the connection pool. + */ + export function createPool(poolAttributes: IPoolAttributes): IPromise< IConnectionPool >; + + /** + * Creates a connection with the database. + * @param {IConnectionAttributes} connectionAttributes Parameters to stablish the connection. + * @param {(err:any,connection:IConnection)=>void} callback Callback to run when the connection gets stablished or when some error occurs. + * @returns void + */ + export function getConnection(connectionAttributes: IConnectionAttributes, callback: (err: any, connection: IConnection) => void): void; + + /** + * Creates a connection with the database. + * @param {IConnectionAttributes} connectionAttributes Parameters to stablish the connection. + * @returns {(connection:IConnection)=>any} Promise with the connection. + */ + export function getConnection(connectionAttributes: IConnectionAttributes): IPromise< IConnection >; } diff --git a/phoenix/phoenix-tests.ts b/phoenix/phoenix-tests.ts new file mode 100644 index 0000000000..6724fc6434 --- /dev/null +++ b/phoenix/phoenix-tests.ts @@ -0,0 +1,72 @@ +/// + +import { Socket, Channel, Presence } from 'phoenix'; + +function test_socket() { + const socket = new Socket("/ws", {params: {userToken: "123"}}); + socket.connect(); +} + +function test_channel() { + const socket = new Socket("/ws", {params: {userToken: "123"}}); + socket.connect(); + + const channel = socket.channel("room:123", {token: '123'}); + + channel.on("new_msg", msg => console.log("Got message", msg)); + + channel.push("new_msg", {body: 'some value'}, 10000) + .receive("ok", (msg) => console.log("created message", msg)) + .receive("error", (reasons) => console.log("create failed", reasons)) + .receive("timeout", () => console.log("Networking issue...")); + + channel.join() + .receive("ok", ({messages}) => console.log("catching up", messages)) + .receive("error", ({reason}) => console.log("failed join", reason)) + .receive("timeout", () => console.log("Networking issue. Still waiting...")); +} + +function test_hooks() { + const socket = new Socket("/ws", {params: {userToken: "123"}}); + socket.connect(); + + socket.onError(() => console.log("there was an error with the connection!")); + socket.onClose(() => console.log("the connection dropped")); + + const channel = socket.channel("room:123", {token: '123'}); + + channel.onError(() => console.log("there was an error!")); + channel.onClose(() => console.log("the channel has gone away gracefully")) +} + +function test_presence() { + let state = {}; + const stateFromServer = {}; + + const onJoin = (id: string, current: any, newPres: any) => { + if(!current){ + console.log("user has entered for the first time", newPres) + } else { + console.log("user additional presence", newPres) + } + }; + + const onLeave = (id: string, current: any, leftPres: any) => { + if(current.metas.length === 0){ + console.log("user has left from all devices", leftPres) + } else { + console.log("user left from a device", leftPres) + } + }; + + state = Presence.syncState(state, stateFromServer, onJoin, onLeave); + + const listBy = (id: string, {metas: [first, ...rest]} : {metas: any[]}) => { + first.count = rest.length + 1; + first.id = id; + + return first; + }; + + const onlineUsers = Presence.list(state, listBy); +} diff --git a/phoenix/phoenix.d.ts b/phoenix/phoenix.d.ts new file mode 100644 index 0000000000..5f8956bee5 --- /dev/null +++ b/phoenix/phoenix.d.ts @@ -0,0 +1,143 @@ +// Type definitions for phoenix +// Project: https://github.com/phoenixframework/phoenix +// Definitions by: Mirosław Ciastek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "phoenix" { + class Push { + constructor(channel: Channel, event: string, payload: any, timeout: number); + + resend(timeout: number): void; + send(): void; + + receive(status: string, callback: (response?: any) => void): Push; + } + + export class Channel { + constructor(topic: string, params?: Object, socket?: Socket); + + rejoinUntilConnected(): void; + + join(timeout?: number): Push; + leave(timeout?: number): Push; + + onClose(callback: Function): void; + onError(callback: (reason?: any) => void): void; + onMessage(event: string, payload: any, ref: any): any; + + on(event: string, callback: (response?: any) => void): void; + off(event: string): void; + + canPush(): boolean; + + push(event: string, payload: Object, timeout?: number): Push; + } + + export class Socket { + constructor(endPoint: string, opts?: Object); + + protocol(): string; + endPointURL(): string; + + disconnect(callback?: Function, code?: string, reason?: any): void; + connect(params?: any): void; + + log(kind: string, msg: string, data: any): void; + + onOpen(callback: Function): void; + onClose(callback: Function): void; + onError(callback: Function): void; + onMessage(callback: Function): void; + + onConnOpen(): void; + onConnClose(event: any): void; + onConnError(error: any): void; + + triggerChanError(): void; + + connectionState(): string; + + isConnected(): boolean; + + remove(channel: Channel): void; + channel(topic: string, chanParams?: Object): Channel; + + push(data: any): void; + + makeRef(): string; + sendHeartbeat(): void; + flushSendBuffer(): void; + + onConnMessage(rawMessage: any): void; + } + + export class LongPoll { + constructor(endPoint: string); + + normalizeEndpoint(endPoint: string): string; + endpointURL(): string; + + closeAndRetry(): void; + ontimeout(): void; + + poll(): void; + + send(body: any): void; + close(code?: any, reason?: any): void; + } + + export class Ajax { + request( + method: string, + endPoint: string, + accept: string, + body: any, + timeout?: number, + ontimeout?: any, + callback?: (response?: any) => void + ): void; + + xdomainRequest( + req: any, + method: string, + endPoint: string, + body: any, + timeout?: number, + ontimeout?: any, + callback?: (response?: any) => void + ): void; + + xhrRequest( + req: any, + method: string, + endPoint: string, + accept: string, + body: any, + timeout?: number, + ontimeout?: any, + callback?: (response?: any) => void + ): void; + + parseJSON(resp: string): JSON; + serialize(obj: any, parentKey: string): string; + appendParams(url: string, params: any): string; + } + + export var Presence: { + syncState( + currentState: any, + newState: any, + onJoin?: (key?: string, currentPresence?: any, newPresence?: any) => void, + onLeave?: (key?: string, currentPresence?: any, newPresence?: any) => void + ): any; + + syncDiff( + currentState: any, + newState: any, + onJoin?: (key?: string, currentPresence?: any, newPresence?: any) => void, + onLeave?: (key?: string, currentPresence?: any, newPresence?: any) => void + ): any; + + list(presences: any, chooser?: Function): any; + } +} diff --git a/pkcs11js/pkcs11js-tests.ts b/pkcs11js/pkcs11js-tests.ts new file mode 100644 index 0000000000..26ef317ba1 --- /dev/null +++ b/pkcs11js/pkcs11js-tests.ts @@ -0,0 +1,47 @@ +/// + +import * as pkcs11js from "pkcs11js"; + +const libPath = "C:\\tmp\\rtpkcs11ecp.dll"; + +let pkcs11 = new pkcs11js.PKCS11(); +pkcs11.load(libPath); + +pkcs11.C_Initialize(); + +try { + // Getting info about PKCS11 Module + let module_info = pkcs11.C_GetInfo(); + + // Getting list of slots + let slots = pkcs11.C_GetSlotList(true); + let slot = slots[0]; + + // Getting info about slot + let slot_info = pkcs11.C_GetSlotInfo(slot); + // Getting info about token + let token_info = pkcs11.C_GetTokenInfo(slot); + + // Getting info about Mechanism + let mechs = pkcs11.C_GetMechanismList(slot); + let mech_info = pkcs11.C_GetMechanismInfo(slot, mechs[0]); + + let session = pkcs11.C_OpenSession(slot, pkcs11js.CKF_RW_SESSION | pkcs11js.CKF_SERIAL_SESSION); + + // Getting info about Session + let info = pkcs11.C_GetSessionInfo(session); + pkcs11.C_Login(session, 1, "12345678"); + + /** + * Your app code here + */ + + pkcs11.C_Logout(session); + pkcs11.C_CloseSession(session); +} +catch (e) { + console.error(e); +} +finally { + pkcs11.C_Finalize(); +} \ No newline at end of file diff --git a/pkcs11js/pkcs11js.d.ts b/pkcs11js/pkcs11js.d.ts new file mode 100644 index 0000000000..c340ca2112 --- /dev/null +++ b/pkcs11js/pkcs11js.d.ts @@ -0,0 +1,1226 @@ +// Type definitions for pkcs11js v1.0.3 +// Project: https://github.com/PeculiarVentures/pkcs11js +// Definitions by: Stepan Miroshin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** + * A Node.js implementation of the PKCS#11 2.3 interface + * v1.0.3 + */ + +declare module "pkcs11js" { + + type Handle = Buffer; + + + interface Version { + major: number; + minor: number; + } + + interface ModuleInfo { + cryptokiVersion: Version; + manufacturerID: string; + flags: number; + libraryDescription: string; + libraryVersion: Version; + } + + interface SlotInfo { + slotDescription: string; + manufacturerID: string; + flags: number; + hardwareVersion: Version; + firmwareVersion: Version + } + + interface TokenInfo { + label: string; + manufacturerID: string; + model: string; + serialNumber: string; + flags: number; + maxSessionCount: number; + sessionCount: number; + maxRwSessionCount: number; + rwSessionCount: number; + maxPinLen: number; + minPinLen: number; + hardwareVersion: Version; + firmwareVersion: Version; + utcTime: string + totalPublicMemory: number; + freePublicMemory: number; + totalPrivateMemory: number; + freePrivateMemory: number; + } + + interface MechanismInfo { + minKeySize: number; + maxKeySize: number; + flags: number; + } + + interface SessionInfo { + slotID: number; + state: number; + flags: number; + deviceError: number; + } + + type Template = Attribute[]; + + interface Attribute { + type: number; + value?: number | boolean | string | Buffer; + } + + interface Mechanism { + mechanism: number; + parameter: Buffer | IParapms; + } + + // Crpto parameters + + interface IParapms { + /** + * Type of crypto param. Uses consts CK_PARAMS_* + * + * @type {number} + */ + type: number; + } + + interface ECDH1 extends IParapms { + kdf: number; + sharedData?: Buffer; + publicData: Buffer; + } + + interface AesCBC extends IParapms { + iv: Buffer; + data?: Buffer; + } + + interface AesCCM extends IParapms { + dataLen: number; + nonce?: Buffer; + aad?: Buffer; + macLen: number; + } + + interface AesGCM extends IParapms { + iv?: Buffer; + aad?: Buffer; + ivBits: number; + tagBits: number; + } + + interface RsaOAEP extends IParapms { + hashAlg: number; + mgf: number; + source: number; + sourceData?: Buffer; + } + + interface RsaPSS extends IParapms { + hashAlg: number; + mgf: number; + saltLen: number; + } + + interface KeyPair { + privateKey: Handle, + publicKey: Handle, + } + + export class PKCS11 { + /** + * Loads dynamic library with PKCS#11 interface + * + * @param {string} path + */ + load(path: string): void; + /** + * Initializes the Cryptoki library + */ + C_Initialize(): void; + /** + * Indicates that an application is done with the Cryptoki library + */ + C_Finalize(): void; + /** + * Returns general information about Cryptoki + * + * @returns {ModuleInfo} + */ + C_GetInfo(): ModuleInfo; + + /* Slot and token management */ + + /** + * obtains a list of slots in the system + * + * @param {boolean} [tokenPresent] Only slots with tokens? + * @returns {Handle[]} Array of slot IDs + */ + C_GetSlotList(tokenPresent?: boolean): Handle[]; + /** + * Obtains information about a particular slot in the system + * + * @param {Handle} slot The ID of the slot + * @returns {SlotInfo} Receives the slot information + */ + C_GetSlotInfo(slot: Handle): SlotInfo; + /** + * Obtains information about a particular token in the system + * + * @param {Handle} slot ID of the token's slot + * @returns {TokenInfo} Receives the token information + */ + C_GetTokenInfo(slot: Handle): TokenInfo; + /** + * Initializes a token + * + * @param {Handle} slot ID of the token's slot + * @param {string} [pin] The SO's initial PIN + * @returns {string} 32-byte token label (blank padded) + */ + C_InitToken(slot: Handle, pin?: string): string; + /** + * Initializes the normal user's PIN + * + * @param {Handle} session The session's handle + * @param {string} [pin] The normal user's PIN + */ + C_InitPIN(session: Handle, pin?: string): void; + /** + * Modifies the PIN of the user who is logged in + * + * @param {Handle} session The session's handle + * @param {string} oldPin The old PIN + * @param {string} newPin The new PIN + */ + C_SetPIN(session: Handle, oldPin: string, newPin: string): void; + /** + * Obtains a list of mechanism types supported by a token + * + * @param {Handle} slot ID of token's slot + * @returns {Handle[]} Gets mech. array + */ + C_GetMechanismList(slot: Handle): Handle[]; + /** + * Obtains information about a particular mechanism possibly supported by a token + * + * @param {Handle} slot ID of the token's slot + * @param {Handle} mech Type of mechanism + * @returns {MechanismInfo} Receives mechanism info + */ + C_GetMechanismInfo(slot: Handle, mech: Handle): MechanismInfo; + + /* Session management */ + + /** + * Opens a session between an application and a token + * + * @param {Handle} slot The slot's ID + * @param {number} flags From CK_SESSION_INFO + * @returns {Handle} Gets session handle + */ + C_OpenSession(slot: Handle, flags: number): Handle; + /** + * Closes a session between an application and a token + * + * @param {Handle} session The session's handle + */ + C_CloseSession(session: Handle): void; + /** + * Сloses all sessions with a token + * + * @param {Handle} slot The token's slot + */ + C_CloseAllSessions(slot: Handle): void; + /** + * Obtains information about the session + * + * @param {Handle} session The session's handle + * @returns {SessionInfo} Receives session info + */ + C_GetSessionInfo(session: Handle): SessionInfo; + /** + * Logs a user into a token + * + * @param {Handle} session The session's handle + * @param {number} userType The user type + * @param {string} [pin] The user's PIN + */ + C_Login(session: Handle, userType: number, pin?: string): void; + /** + * Logs a user out from a token + * + * @param {Handle} session The session's handle + */ + C_Logout(session: Handle): void; + + /* Object management */ + + /** + * Creates a new object + * + * @param {Handle} session The session's handle + * @param {Template} template The object's template + * @returns {Handle} Gets new object's handle + */ + C_CreateObject(session: Handle, template: Template): Handle; + /** + * Copies an object, creating a new object for the copy + * + * @param {Handle} session The session's handle + * @param {Handle} object The object's handle + * @param {Template} template Template for new object + * @returns {Handle} Receives handle of copy + */ + C_CopyObject(session: Handle, object: Handle, template: Template): Handle; + /** + * Destroys an object + * + * @param {Handle} session The session's handle + * @param {Handle} object The object's handle + */ + C_DestroyObject(session: Handle, object: Handle): void; + /** + * Gets the size of an object in bytes + * + * @param {Handle} session The session's handle + * @param {Handle} object The object's handle + * @returns {number} Receives size of object + */ + C_GetObjectSize(session: Handle, object: Handle): number; + /** + * Initializes a search for token and session objects that match a template + * + * @param {Handle} session The session's handle + * @param {Template} template Attribute values to match + */ + C_FindObjectsInit(session: Handle, template: Template): void; + /** + * Continues a search for token and session + * objects that match a template, obtaining additional object + * handles + * + * @param {Handle} session Session's handle + * @returns {Handle} gets Object's handle. If Object is not found + * the result is 0 + */ + C_FindObjects(session: Handle): Handle; + /** + * Finishes a search for token and session objects + * + * @param {Handle} session The session's handle + */ + C_FindObjectsFinal(session: Handle): void; + /** + * Obtains the value of one or more object attributes + * + * @param {Handle} session The session's handle + * @param {Handle} object The object's handle + * @param {Template} template Specifies attrs; gets vals + * @returns {Template} Receives attributes with values + */ + C_GetAttributeValue(session: Handle, object: Handle, template: Template): Template; + /** + * Modifies the value of one or more object attributes + * + * @param {Handle} session The session's handle + * @param {Handle} object The object's handle + * @param {Template} template Specifies attrs and values + */ + C_SetAttributeValue(session: Handle, object: Handle, template: Template): void; + + /* Encryption and decryption */ + + /** + * Initializes an encryption operation + * + * @param {Handle} session The session's handle + * @param {Mechanism} mechanism The encryption mechanism + * @param {Handle} key Handle of encryption key + */ + C_EncryptInit(session: Handle, mechanism: Mechanism, key: Handle): void; + /** + * Encrypts single-part data + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Comming data + * @returns {Buffer} + */ + C_Encrypt(session: Handle, inData: Buffer, outData: Buffer): Buffer; + /** + * Encrypts single-part data + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Comming data + * @param {(error: Error, data: Buffer) => void} cb Async callback with sliced comming data + */ + C_Encrypt(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; + /** + * Continues a multiple-part encryption operation + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_EncryptUpdate(session: Handle, inData: Buffer, outData: Buffer): Buffer; + /** + * Finishes a multiple-part encryption operation + * + * @param {Handle} session Session's handle + * @param {Buffer} outData Last coming data + * @returns {Buffer} Sliced coming data + */ + C_EncryptFinal(session: Handle, outData: Buffer): Buffer; + /** + * Initializes a decryption operation + * + * @param {Handle} session The session's handle + * @param {Mechanism} mechanism The decryption mechanism + * @param {Handle} key Handle of decryption key + */ + C_DecryptInit(session: Handle, mechanism: Mechanism, key: Handle): void; + /** + * Decrypts encrypted data in a single part + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_Decrypt(session: Handle, inData: Buffer, outData: Buffer): Buffer; + /** + * Decrypts encrypted data in a single part + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @param {(error: Error, data: Buffer) => void} cb Async callback with sliced coming data + */ + C_Decrypt(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; + /** + * continues a multiple-part decryption operation + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_DecryptUpdate(session: Handle, inData: Buffer, outData: Buffer): Buffer; + /** + * Finishes a multiple-part decryption operation + * + * @param {Handle} session Session's handle + * @param {Buffer} outData Last part of coming data + * @returns {Buffer} Coming data + */ + C_DecryptFinal(session: Handle, outData: Buffer): Buffer; + + /* Message digesting */ + + /** + * Initializes a message-digesting operation + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Digesting mechanism + */ + C_DigestInit(session: Handle, mechanism: Mechanism): void; + /** + * Digests data in a single part + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_Digest(session: Handle, inData: Buffer, outData: Buffer): Buffer; + /** + * Digests data in a single part + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @param {(error: Error, data: Buffer) => void} cb Async callback with sliced coming data + + */ + C_Digest(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; + /** + * continues a multiple-part message-digesting operation + * operation, by digesting the value of a secret key as part of + * the data already digested + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + */ + C_DigestUpdate(session: Handle, inData: Buffer): void; + /** + * Finishes a multiple-part message-digesting operation + * + * @param {Handle} session Session's handle + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_DigestFinal(session: Handle, outData: Buffer): Buffer; + // C_DigestKey(); + + /* Signing and MACing */ + + /** + * initializes a signature (private key encryption) + * operation, where the signature is (will be) an appendix to + * the data, and plaintext cannot be recovered from the + *signature + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Signature mechanism + * @param {Handle} key Handle of signature key + */ + C_SignInit(session: Handle, mechanism: Mechanism, key: Handle): void; + /** + * Signs (encrypts with private key) data in a single + * part, where the signature is (will be) an appendix to the + * data, and plaintext cannot be recovered from the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_Sign(session: Handle, inData: Buffer, outData: Buffer): Buffer; + /** + * Signs (encrypts with private key) data in a single + * part, where the signature is (will be) an appendix to the + * data, and plaintext cannot be recovered from the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} outData Coming data + * @param {(error: Error, data: Buffer) => void} cb Async callback with sliced coming data + */ + C_Sign(session: Handle, inData: Buffer, outData: Buffer, cb: (error: Error, data: Buffer) => void): void; + /** + * continues a multiple-part signature operation, + * where the signature is (will be) an appendix to the data, + * and plaintext cannot be recovered from the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + */ + C_SignUpdate(session: Handle, inData: Buffer): void; + /** + * Finishes a multiple-part signature operation, + * returning the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} outData Coming data + * @returns {Buffer} Sliced coming data + */ + C_SignFinal(session: Handle, outData: Buffer): Buffer; + // C_SignRecoverInit(); + // C_SignRecover(); + + /* Verifying signatures and MACs */ + + /** + * initializes a verification operation, where the + * signature is an appendix to the data, and plaintext cannot + * cannot be recovered from the signature (e.g. DSA) + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Verification mechanism + * @param {Handle} key Verification key + */ + C_VerifyInit(session: Handle, mechanism: Mechanism, key: Handle): void; + /** + * Verifies a signature in a single-part operation, + * where the signature is an appendix to the data, and plaintext + * cannot be recovered from the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} signature Signature to verify + * @returns {boolean} Verification result + */ + C_Verify(session: Handle, inData: Buffer, signature: Buffer): boolean; + /** + * Verifies a signature in a single-part operation, + * where the signature is an appendix to the data, and plaintext + * cannot be recovered from the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + * @param {Buffer} signature Signature to verify + * @param {(error: Error, verify: boolean) => void} cb Async callback with verification result + */ + C_Verify(session: Handle, inData: Buffer, signature: Buffer, cb: (error: Error, verify: boolean) => void): void; + /** + * Continues a multiple-part verification + * operation, where the signature is an appendix to the data, + * and plaintext cannot be recovered from the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} inData Incoming data + */ + C_VerifyUpdate(session: Handle, inData: Buffer): void; + /** + * Finishes a multiple-part verification + * operation, checking the signature + * + * @param {Handle} session Session's handle + * @param {Buffer} signature Signature to verify + * @returns {boolean} + */ + C_VerifyFinal(session: Handle, signature: Buffer): boolean; + // C_VerifyRecoverInit(); + // C_VerifyRecover(); + + /* Key management */ + + /** + * Generates a secret key, creating a new key object + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Key generation mechanism + * @param {Template} template Template for new key + * @returns {Handle} Gets handle of new key + */ + C_GenerateKey(session: Handle, mechanism: Mechanism, template: Template): Handle; + /** + * Generates a secret key, creating a new key object + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Key generation mechanism + * @param {Template} template Template for new key + * @param {(error: Error, key: Handle) => void} cb Async callback with handle of ne key + */ + C_GenerateKey(session: Handle, mechanism: Mechanism, template: Template, cb: (error: Error, key: Handle) => void): void; + /** + * Generates a public-key/private-key pair, + * creating new key objects + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Key generation mechanism + * @param {Template} publicTmpl Template for public key + * @param {Template} privateTmpl Template for private key + * @returns {KeyPair} Get handles for private and public keys + */ + C_GenerateKeyPair(session: Handle, mechanism: Mechanism, publicTmpl: Template, privateTmpl: Template): KeyPair; + /** + * Generates a public-key/private-key pair, + * creating new key objects + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Key generation mechanism + * @param {Template} publicTmpl Template for public key + * @param {Template} privateTmpl Template for private key + * @param {(error: Error, keys: KeyPair) => void} cb Async callback with handles for private and public keys + */ + C_GenerateKeyPair(session: Handle, mechanism: Mechanism, publicTmpl: Template, privateTmpl: Template, cb: (error: Error, keys: KeyPair) => void): void; + /** + * Wraps (i.e., encrypts) a key + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Wrapping mechanism + * @param {Handle} wrappingKey Wrapping key + * @param {Handle} key Key to be wrapped + * @param {Buffer} wrappedKey Init buffer for wrapped key + * @returns {Buffer} Sliced wrapped key + */ + C_WrapKey(session: Handle, mechanism: Mechanism, wrappingKey: Handle, key: Handle, wrappedKey: Buffer): Buffer; + /** + * Wraps (i.e., encrypts) a key + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Wrapping mechanism + * @param {Handle} wrappingKey Wrapping key + * @param {Handle} key Key to be wrapped + * @param {Buffer} wrappedKey Init buffer for wrapped key + * @param {(error: Error, wrappedKey: Buffer) => void} cb Async callback with sliced wrapped key + */ + C_WrapKey(session: Handle, mechanism: Mechanism, wrappingKey: Handle, key: Handle, wrappedKey: Buffer, cb: (error: Error, wrappedKey: Buffer) => void): void; + /** + * Unwraps (decrypts) a wrapped key, creating a new key object + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Unwrapping mechanism + * @param {Handle} unwrappingKey Unwrapping key + * @param {Buffer} wrappedKey Wrapped key + * @param {Template} template New key template + * @returns {Handle} Gets new handle + */ + C_UnwrapKey(session: Handle, mechanism: Mechanism, unwrappingKey: Handle, wrappedKey: Buffer, template: Template): Handle; + /** + * Unwraps (decrypts) a wrapped key, creating a new key object + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Unwrapping mechanism + * @param {Handle} unwrappingKey Unwrapping key + * @param {Buffer} wrappedKey Wrapped key + * @param {Template} template New key template + * @param {(error: Error, key: Handle) => void} cb Async callback with new key handle + */ + C_UnwrapKey(session: Handle, mechanism: Mechanism, unwrappingKey: Handle, wrappedKey: Buffer, template: Template, cb: (error: Error, key: Handle) => void): void; + /** + * Derives a key from a base key, creating a new key object + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Key derivation mechanism + * @param {Handle} key Base key + * @param {Template} template new key template + * @returns {Handle} Get new key handle + */ + C_DeriveKey(session: Handle, mechanism: Mechanism, key: Handle, template: Template): Handle; + /** + * Derives a key from a base key, creating a new key object + * + * @param {Handle} session Session's handle + * @param {Mechanism} mechanism Key derivation mechanism + * @param {Handle} key Base key + * @param {Template} template new key template + * @param {(error: Error, hKey: Handle) => void} cb Async callback woth new key handle + */ + C_DeriveKey(session: Handle, mechanism: Mechanism, key: Handle, template: Template, cb: (error: Error, hKey: Handle) => void): void; + /** + * Mixes additional seed material into the token's random number generator + * + * @param {Handle} session Session's handle + * @param {Buffer} buf The seed material + * @returns {Buffer} Seeded data + */ + C_SeedRandom(session: Handle, buf: Buffer): Buffer; + /** + * Generates random data + * + * @param {Handle} session Session's handle + * @param {Buffer} buf Init buffer + * @returns {Buffer} Receives the random data + */ + C_GenerateRandom(session: Handle, buf: Buffer): Buffer; + } + + // Attributes + const CKA_CLASS: number; + const CKA_TOKEN: number; + const CKA_PRIVATE: number; + const CKA_LABEL: number; + const CKA_APPLICATION: number; + const CKA_VALUE: number; + const CKA_OBJECT_ID: number; + const CKA_CERTIFICATE_TYPE: number; + const CKA_ISSUER: number; + const CKA_SERIAL_NUMBER: number; + const CKA_AC_ISSUER: number; + const CKA_OWNER: number; + const CKA_ATTR_TYPES: number; + const CKA_TRUSTED: number; + const CKA_CERTIFICATE_CATEGORY: number; + const CKA_JAVA_MIDP_SECURITY_DOMAIN: number; + const CKA_URL: number; + const CKA_HASH_OF_SUBJECT_PUBLIC_KEY: number; + const CKA_HASH_OF_ISSUER_PUBLIC_KEY: number; + const CKA_CHECK_VALUE: number; + const CKA_KEY_TYPE: number; + const CKA_SUBJECT: number; + const CKA_ID: number; + const CKA_SENSITIVE: number; + const CKA_ENCRYPT: number; + const CKA_DECRYPT: number; + const CKA_WRAP: number; + const CKA_UNWRAP: number; + const CKA_SIGN: number; + const CKA_SIGN_RECOVER: number; + const CKA_VERIFY: number; + const CKA_VERIFY_RECOVER: number; + const CKA_DERIVE: number; + const CKA_START_DATE: number; + const CKA_END_DATE: number; + const CKA_MODULUS: number; + const CKA_MODULUS_BITS: number; + const CKA_PUBLIC_EXPONENT: number; + const CKA_PRIVATE_EXPONENT: number; + const CKA_PRIME_1: number; + const CKA_PRIME_2: number; + const CKA_EXPONENT_1: number; + const CKA_EXPONENT_2: number; + const CKA_COEFFICIENT: number; + const CKA_PRIME: number; + const CKA_SUBPRIME: number; + const CKA_BASE: number; + const CKA_PRIME_BITS: number; + const CKA_SUBPRIME_BITS: number; + const CKA_SUB_PRIME_BITS: number; + const CKA_VALUE_BITS: number; + const CKA_VALUE_LEN: number; + const CKA_EXTRACTABLE: number; + const CKA_LOCAL: number; + const CKA_NEVER_EXTRACTABLE: number; + const CKA_ALWAYS_SENSITIVE: number; + const CKA_KEY_GEN_MECHANISM: number; + const CKA_MODIFIABLE: number; + const CKA_ECDSA_PARAMS: number; + const CKA_EC_PARAMS: number; + const CKA_EC_POINT: number; + const CKA_SECONDARY_AUTH: number; + const CKA_AUTH_PIN_FLAGS: number; + const CKA_ALWAYS_AUTHENTICATE: number; + const CKA_WRAP_WITH_TRUSTED: number; + const CKA_WRAP_TEMPLATE: number; + const CKA_UNWRAP_TEMPLATE: number; + const CKA_DERIVE_TEMPLATE: number; + const CKA_OTP_FORMAT: number; + const CKA_OTP_LENGTH: number; + const CKA_OTP_TIME_INTERVAL: number; + const CKA_OTP_USER_FRIENDLY_MODE: number; + const CKA_OTP_CHALLENGE_REQUIREMENT: number; + const CKA_OTP_TIME_REQUIREMENT: number; + const CKA_OTP_COUNTER_REQUIREMENT: number; + const CKA_OTP_PIN_REQUIREMENT: number; + const CKA_OTP_COUNTER: number; + const CKA_OTP_TIME: number; + const CKA_OTP_USER_IDENTIFIER: number; + const CKA_OTP_SERVICE_IDENTIFIER: number; + const CKA_OTP_SERVICE_LOGO: number; + const CKA_OTP_SERVICE_LOGO_TYPE: number; + const CKA_GOSTR3410_PARAMS: number; + const CKA_GOSTR3411_PARAMS: number; + const CKA_GOST28147_PARAMS: number; + const CKA_HW_FEATURE_TYPE: number; + const CKA_RESET_ON_INIT: number; + const CKA_HAS_RESET: number; + const CKA_PIXEL_X: number; + const CKA_PIXEL_Y: number; + const CKA_RESOLUTION: number; + const CKA_CHAR_ROWS: number; + const CKA_CHAR_COLUMNS: number; + const CKA_COLOR: number; + const CKA_BITS_PER_PIXEL: number; + const CKA_CHAR_SETS: number; + const CKA_ENCODING_METHODS: number; + const CKA_MIME_TYPES: number; + const CKA_MECHANISM_TYPE: number; + const CKA_REQUIRED_CMS_ATTRIBUTES: number; + const CKA_DEFAULT_CMS_ATTRIBUTES: number; + const CKA_SUPPORTED_CMS_ATTRIBUTES: number; + const CKA_ALLOWED_MECHANISMS: number; + const CKA_VENDOR_DEFINED: number; + + // Objects + const CKO_DATA: number; + const CKO_CERTIFICATE: number; + const CKO_PUBLIC_KEY: number; + const CKO_PRIVATE_KEY: number; + const CKO_SECRET_KEY: number; + const CKO_HW_FEATURE: number; + const CKO_DOMAIN_PARAMETERS: number; + const CKO_MECHANISM: number; + const CKO_OTP_KEY: number; + const CKO_VENDOR_DEFINED: number; + + // Key types + const CKK_RSA: number; + const CKK_DSA: number; + const CKK_DH: number; + const CKK_ECDSA: number; + const CKK_EC: number; + const CKK_X9_42_DH: number; + const CKK_KEA: number; + const CKK_GENERIC_SECRET: number; + const CKK_RC2: number; + const CKK_RC4: number; + const CKK_DES: number; + const CKK_DES2: number; + const CKK_DES3: number; + const CKK_CAST: number; + const CKK_CAST3: number; + const CKK_CAST5: number; + const CKK_CAST128: number; + const CKK_RC5: number; + const CKK_IDEA: number; + const CKK_SKIPJACK: number; + const CKK_BATON: number; + const CKK_JUNIPER: number; + const CKK_CDMF: number; + const CKK_AES: number; + const CKK_BLOWFISH: number; + const CKK_TWOFISH: number; + const CKK_SECURID: number; + const CKK_HOTP: number; + const CKK_ACTI: number; + const CKK_CAMELLIA: number; + const CKK_ARIA: number; + const CKK_MD5_HMAC: number; + const CKK_SHA_1_HMAC: number; + const CKK_RIPEMD128_HMAC: number; + const CKK_RIPEMD160_HMAC: number; + const CKK_SHA256_HMAC: number; + const CKK_SHA384_HMAC: number; + const CKK_SHA512_HMAC: number; + const CKK_SHA224_HMAC: number; + const CKK_SEED: number; + const CKK_GOSTR3410: number; + const CKK_GOSTR3411: number; + const CKK_GOST28147: number; + const CKK_VENDOR_DEFINED: number; + + // Mechanism + const CKM_RSA_PKCS_KEY_PAIR_GEN: number; + const CKM_RSA_PKCS: number; + const CKM_RSA_9796: number; + const CKM_RSA_X_509: number; + const CKM_MD2_RSA_PKCS: number; + const CKM_MD5_RSA_PKCS: number; + const CKM_SHA1_RSA_PKCS: number; + const CKM_RIPEMD128_RSA_PKCS: number; + const CKM_RIPEMD160_RSA_PKCS: number; + const CKM_RSA_PKCS_OAEP: number; + const CKM_RSA_X9_31_KEY_PAIR_GEN: number; + const CKM_RSA_X9_31: number; + const CKM_SHA1_RSA_X9_31: number; + const CKM_RSA_PKCS_PSS: number; + const CKM_SHA1_RSA_PKCS_PSS: number; + const CKM_DSA_KEY_PAIR_GEN: number; + const CKM_DSA: number; + const CKM_DSA_SHA1: number; + const CKM_DSA_SHA224: number; + const CKM_DSA_SHA256: number; + const CKM_DSA_SHA384: number; + const CKM_DSA_SHA512: number; + const CKM_DH_PKCS_KEY_PAIR_GEN: number; + const CKM_DH_PKCS_DERIVE: number; + const CKM_X9_42_DH_KEY_PAIR_GEN: number; + const CKM_X9_42_DH_DERIVE: number; + const CKM_X9_42_DH_HYBRID_DERIVE: number; + const CKM_X9_42_MQV_DERIVE: number; + const CKM_SHA256_RSA_PKCS: number; + const CKM_SHA384_RSA_PKCS: number; + const CKM_SHA512_RSA_PKCS: number; + const CKM_SHA256_RSA_PKCS_PSS: number; + const CKM_SHA384_RSA_PKCS_PSS: number; + const CKM_SHA512_RSA_PKCS_PSS: number; + const CKM_SHA224_RSA_PKCS: number; + const CKM_SHA224_RSA_PKCS_PSS: number; + const CKM_RC2_KEY_GEN: number; + const CKM_RC2_ECB: number; + const CKM_RC2_CBC: number; + const CKM_RC2_MAC: number; + const CKM_RC2_MAC_GENERAL: number; + const CKM_RC2_CBC_PAD: number; + const CKM_RC4_KEY_GEN: number; + const CKM_RC4: number; + const CKM_DES_KEY_GEN: number; + const CKM_DES_ECB: number; + const CKM_DES_CBC: number; + const CKM_DES_MAC: number; + const CKM_DES_MAC_GENERAL: number; + const CKM_DES_CBC_PAD: number; + const CKM_DES2_KEY_GEN: number; + const CKM_DES3_KEY_GEN: number; + const CKM_DES3_ECB: number; + const CKM_DES3_CBC: number; + const CKM_DES3_MAC: number; + const CKM_DES3_MAC_GENERAL: number; + const CKM_DES3_CBC_PAD: number; + const CKM_DES3_CMAC_GENERAL: number; + const CKM_DES3_CMAC: number; + const CKM_CDMF_KEY_GEN: number; + const CKM_CDMF_ECB: number; + const CKM_CDMF_CBC: number; + const CKM_CDMF_MAC: number; + const CKM_CDMF_MAC_GENERAL: number; + const CKM_CDMF_CBC_PAD: number; + const CKM_DES_OFB64: number; + const CKM_DES_OFB8: number; + const CKM_DES_CFB64: number; + const CKM_DES_CFB8: number; + const CKM_MD2: number; + const CKM_MD2_HMAC: number; + const CKM_MD2_HMAC_GENERAL: number; + const CKM_MD5: number; + const CKM_MD5_HMAC: number; + const CKM_MD5_HMAC_GENERAL: number; + const CKM_SHA_1: number; + const CKM_SHA_1_HMAC: number; + const CKM_SHA_1_HMAC_GENERAL: number; + const CKM_RIPEMD128: number; + const CKM_RIPEMD128_HMAC: number; + const CKM_RIPEMD128_HMAC_GENERAL: number; + const CKM_RIPEMD160: number; + const CKM_RIPEMD160_HMAC: number; + const CKM_RIPEMD160_HMAC_GENERAL: number; + const CKM_SHA256: number; + const CKM_SHA256_HMAC: number; + const CKM_SHA256_HMAC_GENERAL: number; + const CKM_SHA224: number; + const CKM_SHA224_HMAC: number; + const CKM_SHA224_HMAC_GENERAL: number; + const CKM_SHA384: number; + const CKM_SHA384_HMAC: number; + const CKM_SHA384_HMAC_GENERAL: number; + const CKM_SHA512: number; + const CKM_SHA512_HMAC: number; + const CKM_SHA512_HMAC_GENERAL: number; + const CKM_SECURID_KEY_GEN: number; + const CKM_SECURID: number; + const CKM_HOTP_KEY_GEN: number; + const CKM_HOTP: number; + const CKM_ACTI: number; + const CKM_ACTI_KEY_GEN: number; + const CKM_CAST_KEY_GEN: number; + const CKM_CAST_ECB: number; + const CKM_CAST_CBC: number; + const CKM_CAST_MAC: number; + const CKM_CAST_MAC_GENERAL: number; + const CKM_CAST_CBC_PAD: number; + const CKM_CAST3_KEY_GEN: number; + const CKM_CAST3_ECB: number; + const CKM_CAST3_CBC: number; + const CKM_CAST3_MAC: number; + const CKM_CAST3_MAC_GENERAL: number; + const CKM_CAST3_CBC_PAD: number; + const CKM_CAST5_KEY_GEN: number; + const CKM_CAST128_KEY_GEN: number; + const CKM_CAST5_ECB: number; + const CKM_CAST128_ECB: number; + const CKM_CAST5_CBC: number; + const CKM_CAST128_CBC: number; + const CKM_CAST5_MAC: number; + const CKM_CAST128_MAC: number; + const CKM_CAST5_MAC_GENERAL: number; + const CKM_CAST128_MAC_GENERAL: number; + const CKM_CAST5_CBC_PAD: number; + const CKM_CAST128_CBC_PAD: number; + const CKM_RC5_KEY_GEN: number; + const CKM_RC5_ECB: number; + const CKM_RC5_CBC: number; + const CKM_RC5_MAC: number; + const CKM_RC5_MAC_GENERAL: number; + const CKM_RC5_CBC_PAD: number; + const CKM_IDEA_KEY_GEN: number; + const CKM_IDEA_ECB: number; + const CKM_IDEA_CBC: number; + const CKM_IDEA_MAC: number; + const CKM_IDEA_MAC_GENERAL: number; + const CKM_IDEA_CBC_PAD: number; + const CKM_GENERIC_SECRET_KEY_GEN: number; + const CKM_CONCATENATE_BASE_AND_KEY: number; + const CKM_CONCATENATE_BASE_AND_DATA: number; + const CKM_CONCATENATE_DATA_AND_BASE: number; + const CKM_XOR_BASE_AND_DATA: number; + const CKM_EXTRACT_KEY_FROM_KEY: number; + const CKM_SSL3_PRE_MASTER_KEY_GEN: number; + const CKM_SSL3_MASTER_KEY_DERIVE: number; + const CKM_SSL3_KEY_AND_MAC_DERIVE: number; + const CKM_SSL3_MASTER_KEY_DERIVE_DH: number; + const CKM_TLS_PRE_MASTER_KEY_GEN: number; + const CKM_TLS_MASTER_KEY_DERIVE: number; + const CKM_TLS_KEY_AND_MAC_DERIVE: number; + const CKM_TLS_MASTER_KEY_DERIVE_DH: number; + const CKM_TLS_PRF: number; + const CKM_SSL3_MD5_MAC: number; + const CKM_SSL3_SHA1_MAC: number; + const CKM_MD5_KEY_DERIVATION: number; + const CKM_MD2_KEY_DERIVATION: number; + const CKM_SHA1_KEY_DERIVATION: number; + const CKM_SHA256_KEY_DERIVATION: number; + const CKM_SHA384_KEY_DERIVATION: number; + const CKM_SHA512_KEY_DERIVATION: number; + const CKM_SHA224_KEY_DERIVATION: number; + const CKM_PBE_MD2_DES_CBC: number; + const CKM_PBE_MD5_DES_CBC: number; + const CKM_PBE_MD5_CAST_CBC: number; + const CKM_PBE_MD5_CAST3_CBC: number; + const CKM_PBE_MD5_CAST5_CBC: number; + const CKM_PBE_MD5_CAST128_CBC: number; + const CKM_PBE_SHA1_CAST5_CBC: number; + const CKM_PBE_SHA1_CAST128_CBC: number; + const CKM_PBE_SHA1_RC4_128: number; + const CKM_PBE_SHA1_RC4_40: number; + const CKM_PBE_SHA1_DES3_EDE_CBC: number; + const CKM_PBE_SHA1_DES2_EDE_CBC: number; + const CKM_PBE_SHA1_RC2_128_CBC: number; + const CKM_PBE_SHA1_RC2_40_CBC: number; + const CKM_PKCS5_PBKD2: number; + const CKM_PBA_SHA1_WITH_SHA1_HMAC: number; + const CKM_WTLS_PRE_MASTER_KEY_GEN: number; + const CKM_WTLS_MASTER_KEY_DERIVE: number; + const CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC: number; + const CKM_WTLS_PRF: number; + const CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE: number; + const CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE: number; + const CKM_KEY_WRAP_LYNKS: number; + const CKM_KEY_WRAP_SET_OAEP: number; + const CKM_CAMELLIA_KEY_GEN: number; + const CKM_CAMELLIA_ECB: number; + const CKM_CAMELLIA_CBC: number; + const CKM_CAMELLIA_MAC: number; + const CKM_CAMELLIA_MAC_GENERAL: number; + const CKM_CAMELLIA_CBC_PAD: number; + const CKM_CAMELLIA_ECB_ENCRYPT_DATA: number; + const CKM_CAMELLIA_CBC_ENCRYPT_DATA: number; + const CKM_CAMELLIA_CTR: number; + const CKM_ARIA_KEY_GEN: number; + const CKM_ARIA_ECB: number; + const CKM_ARIA_CBC: number; + const CKM_ARIA_MAC: number; + const CKM_ARIA_MAC_GENERAL: number; + const CKM_ARIA_CBC_PAD: number; + const CKM_ARIA_ECB_ENCRYPT_DATA: number; + const CKM_ARIA_CBC_ENCRYPT_DATA: number; + const CKM_SEED_KEY_GEN: number; + const CKM_SEED_ECB: number; + const CKM_SEED_CBC: number; + const CKM_SEED_MAC: number; + const CKM_SEED_MAC_GENERAL: number; + const CKM_SEED_CBC_PAD: number; + const CKM_SEED_ECB_ENCRYPT_DATA: number; + const CKM_SEED_CBC_ENCRYPT_DATA: number; + const CKM_SKIPJACK_KEY_GEN: number; + const CKM_SKIPJACK_ECB64: number; + const CKM_SKIPJACK_CBC64: number; + const CKM_SKIPJACK_OFB64: number; + const CKM_SKIPJACK_CFB64: number; + const CKM_SKIPJACK_CFB32: number; + const CKM_SKIPJACK_CFB16: number; + const CKM_SKIPJACK_CFB8: number; + const CKM_SKIPJACK_WRAP: number; + const CKM_SKIPJACK_PRIVATE_WRAP: number; + const CKM_SKIPJACK_RELAYX: number; + const CKM_KEA_KEY_PAIR_GEN: number; + const CKM_KEA_KEY_DERIVE: number; + const CKM_FORTEZZA_TIMESTAMP: number; + const CKM_BATON_KEY_GEN: number; + const CKM_BATON_ECB128: number; + const CKM_BATON_ECB96: number; + const CKM_BATON_CBC128: number; + const CKM_BATON_COUNTER: number; + const CKM_BATON_SHUFFLE: number; + const CKM_BATON_WRAP: number; + const CKM_ECDSA_KEY_PAIR_GEN: number; + const CKM_EC_KEY_PAIR_GEN: number; + const CKM_ECDSA: number; + const CKM_ECDSA_SHA1: number; + const CKM_ECDSA_SHA224: number; + const CKM_ECDSA_SHA256: number; + const CKM_ECDSA_SHA384: number; + const CKM_ECDSA_SHA512: number; + const CKM_ECDH1_DERIVE: number; + const CKM_ECDH1_COFACTOR_DERIVE: number; + const CKM_ECMQV_DERIVE: number; + const CKM_JUNIPER_KEY_GEN: number; + const CKM_JUNIPER_ECB128: number; + const CKM_JUNIPER_CBC128: number; + const CKM_JUNIPER_COUNTER: number; + const CKM_JUNIPER_SHUFFLE: number; + const CKM_JUNIPER_WRAP: number; + const CKM_FASTHASH: number; + const CKM_AES_KEY_GEN: number; + const CKM_AES_ECB: number; + const CKM_AES_CBC: number; + const CKM_AES_MAC: number; + const CKM_AES_MAC_GENERAL: number; + const CKM_AES_CBC_PAD: number; + const CKM_AES_CTR: number; + const CKM_AES_CTS: number; + const CKM_AES_CMAC: number; + const CKM_AES_CMAC_GENERAL: number; + const CKM_BLOWFISH_KEY_GEN: number; + const CKM_BLOWFISH_CBC: number; + const CKM_TWOFISH_KEY_GEN: number; + const CKM_TWOFISH_CBC: number; + const CKM_AES_GCM: number; + const CKM_AES_CCM: number; + const CKM_AES_KEY_WRAP: number; + const CKM_AES_KEY_WRAP_PAD: number; + const CKM_BLOWFISH_CBC_PAD: number; + const CKM_TWOFISH_CBC_PAD: number; + const CKM_DES_ECB_ENCRYPT_DATA: number; + const CKM_DES_CBC_ENCRYPT_DATA: number; + const CKM_DES3_ECB_ENCRYPT_DATA: number; + const CKM_DES3_CBC_ENCRYPT_DATA: number; + const CKM_AES_ECB_ENCRYPT_DATA: number; + const CKM_AES_CBC_ENCRYPT_DATA: number; + const CKM_GOSTR3410_KEY_PAIR_GEN: number; + const CKM_GOSTR3410: number; + const CKM_GOSTR3410_WITH_GOSTR3411: number; + const CKM_GOSTR3410_KEY_WRAP: number; + const CKM_GOSTR3410_DERIVE: number; + const CKM_GOSTR3411: number; + const CKM_GOSTR3411_HMAC: number; + const CKM_GOST28147_KEY_GEN: number; + const CKM_GOST28147_ECB: number; + const CKM_GOST28147: number; + const CKM_GOST28147_MAC: number; + const CKM_GOST28147_KEY_WRAP: number; + const CKM_DSA_PARAMETER_GEN: number; + const CKM_DH_PKCS_PARAMETER_GEN: number; + const CKM_X9_42_DH_PARAMETER_GEN: number; + const CKM_AES_OFB: number; + const CKM_AES_CFB64: number; + const CKM_AES_CFB8: number; + const CKM_AES_CFB128: number; + const CKM_RSA_PKCS_TPM_1_1: number; + const CKM_RSA_PKCS_OAEP_TPM_1_1: number; + const CKM_VENDOR_DEFINED: number; + + // Session flags + const CKF_RW_SESSION: number; + const CKF_SERIAL_SESSION: number; + + // Follows + const CKF_HW: number; + const CKF_ENCRYPT: number; + const CKF_DECRYPT: number; + const CKF_DIGEST: number; + const CKF_SIGN: number; + const CKF_SIGN_RECOVER: number; + const CKF_VERIFY: number; + const CKF_VERIFY_RECOVER: number; + const CKF_GENERATE: number; + const CKF_GENERATE_KEY_PAIR: number; + const CKF_WRAP: number; + const CKF_UNWRAP: number; + const CKF_DERIVE: number; + + // Certificates + const CKC_X_509: number; + const CKC_X_509_ATTR_CERT: number; + const CKC_WTLS: number; + + // MGFs + const CKG_MGF1_SHA1: number; + const CKG_MGF1_SHA256: number; + const CKG_MGF1_SHA384: number; + const CKG_MGF1_SHA512: number; + const CKG_MGF1_SHA224: number; + + // KDFs + const CKD_NULL: number; + const CKD_SHA1_KDF: number; + const CKD_SHA1_KDF_ASN1: number; + const CKD_SHA1_KDF_CONCATENATE: number; + const CKD_SHA224_KDF: number; + const CKD_SHA256_KDF: number; + const CKD_SHA384_KDF: number; + const CKD_SHA512_KDF: number; + const CKD_CPDIVERSIFY_KDF: number; + + // Mech params + const CK_PARAMS_AES_CBC: number; + const CK_PARAMS_AES_CCM: number; + const CK_PARAMS_AES_GCM: number; + const CK_PARAMS_RSA_OAEP: number; + const CK_PARAMS_RSA_PSS: number; + const CK_PARAMS_EC_DH: number; +} \ No newline at end of file diff --git a/protobufjs/protobufjs-tests.ts b/protobufjs/protobufjs-tests.ts index 94afba0a8e..fd29685f15 100644 --- a/protobufjs/protobufjs-tests.ts +++ b/protobufjs/protobufjs-tests.ts @@ -44,7 +44,7 @@ function testProtoBufJs() { assertIsNamespace(protoFile.ns, "protoFile.ns"); assertIsNamespace(protoFile.ptr, "protoFile.ptr"); - assertIsProtoBuf(protoFile.build(), "protoFile.build()"); + assertIsMetaMessage(protoFile.build(), "protoFile.build()"); assertIsProtoBuf(protoFile.result, "protoFile.result"); assertIsProtoBuilder(protoFile.create(), "protoFile.create()"); @@ -117,11 +117,12 @@ function assertIsProtoBuf(pb: ProtoBuf.ProtoBuf, name: string) { } } -function assertIsMetaMessage(mm: ProtoBuf.MetaMessage, name: string) { +function assertIsMetaMessage(mm: ProtoBuf.MetaMessage, name: string) { assert.ok("decode" in mm, name + " should contain property decode"); assert.ok("decodeDelimited" in mm, name + " should contain property decodeDelimited"); assert.ok("decode64" in mm, name + " should contain property decode64"); assert.ok("decodeHex" in mm, name + " should contain property decodeHex"); + assert.ok("decodeJSON" in mm, name + " should contain property decodeJSON"); } function assertIsDotProto(dp: ProtoBuf.DotProto, name: string) { diff --git a/protobufjs/protobufjs.d.ts b/protobufjs/protobufjs.d.ts index 77d457fbbf..fac34be103 100644 --- a/protobufjs/protobufjs.d.ts +++ b/protobufjs/protobufjs.d.ts @@ -1,8 +1,9 @@ -// Type definitions for ProtoBuf.js +// Type definitions for ProtoBuf.js 5.0.1 // Project: https://github.com/dcodeIO/ProtoBuf.js // Definitions by: Panu Horsmalahti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// /// declare namespace ProtoBuf { @@ -10,25 +11,24 @@ declare namespace ProtoBuf { // protobufjs/src/ProtoBuf.js var Builder: Builder; - var ByteBuffer: Buffer; var Long: LongStatic; var DotProto: DotProto; var Reflect: Reflect; + var Util: Util; // var Lang: Lang; TODO: implement interface Lang - // var Util: Util; TODO: implement interface Util - export function loadJson(json: string, builder?: ProtoBuilder, - filename?: string): ProtoBuilder; + export function loadJson(json: string, builder?: ProtoBuilder | string | {}, + filename?: string | {}): ProtoBuilder; - export function loadJsonFile(filename: string, + export function loadJsonFile(filename: string | {}, callback?: (error: any, builder: ProtoBuilder) => void, builder?: ProtoBuilder): ProtoBuilder; - export function loadProto(proto: string, builder?: ProtoBuilder, - filename?: string): ProtoBuilder; + export function loadProto(proto: string, builder?: ProtoBuilder | string | {}, + filename?: string | {}): ProtoBuilder; - export function loadProtoFile(filePath: string, + export function loadProtoFile(filePath: string | {}, callback?: (error: any, builder: ProtoBuilder) => void, builder?: ProtoBuilder): ProtoBuilder; @@ -117,6 +117,26 @@ declare namespace ProtoBuf { */ export interface Message { new(values?: {[key: string]: any}, var_args?: string[]): Message; + $add(key: string, value: any, noAssert?: boolean): Message; + $get(key: string): T; + $set(key: string | {[key: string]: any}, value?: any | boolean, noAssert?: boolean): void; + add(key: string, value: any, noAssert?: boolean): Message; + calculate(): number; + encode(buffer?: ByteBuffer | boolean, noVerify?: boolean): ByteBuffer; + encode64(): string; + encodeAB(): ArrayBuffer; + encodeNB(): Buffer; + encodeHex(): string; + encodeJSON(): string; + encodeDelimited(buffer?: ByteBuffer | boolean, noVerify?: boolean): ByteBuffer; + get(key: string, noAssert?: boolean): T; + set(key: string | {[key: string]: any}, value?: any | boolean, noAssert?: boolean): void; + toArrayBuffer(): ArrayBuffer; + toBase64(): string; + toBuffer(): Buffer; + toHex(): string; + toRaw(binaryAsBase64?: boolean, longsAsStrings?: boolean): {[key: string]: any}; + toString(): string; [field: string]: any; } @@ -144,20 +164,22 @@ declare namespace ProtoBuf { define(pkg: string, options?: {[key: string]: any}): ProtoBuilder; create(defs?: {[key: string]: any}[]): ProtoBuilder; resolveAll(): void; - build(path?: string): ProtoBuf; + build(path?: string | [string]): MetaMessage; + build(path?: string | [string]): MetaMessage; lookup(path?: string): ReflectT; } export interface ProtoBuf { - [package: string]: {[key: string]: MetaMessage | any}; + [package: string]: {[key: string]: MetaMessage | any}; } - export interface MetaMessage { - new(values?: {[key: string]: any}, var_args?: string[]): Message; - decode(buffer?: Buffer, enc?: string): Message; - decodeDelimited(buffer?: Buffer, enc?: string): Message; - decode64(str: string): Message; - decodeHex(str: string): Message; + export interface MetaMessage { + new(values?: {[key: string]: any}, var_args?: string[]): T & Message; + decode(buffer: ArrayBuffer | ByteBuffer | Buffer | string, length?: number | string, enc?: string): T & Message; + decodeDelimited(buffer: ByteBuffer | ArrayBuffer | Buffer | string, enc?: string): T & Message; + decode64(str: string): T & Message; + decodeHex(str: string): T & Message; + decodeJSON(str: string): T & Message; } // ========== @@ -242,6 +264,16 @@ declare namespace ProtoBuf { options: {[key: string]: any}; } + // ========== + // protobufjs/src/ProtoBuf/Util.js + + export interface Util { + IS_NODE: boolean + fetch(path: string, callback?: (data: string) => any): string; + toCamelCase(str: string): string; + XHR(): XMLHttpRequest; + } + // ========== // protobufjs/src/ProtoBuf/Reflect.js @@ -288,9 +320,10 @@ declare namespace ProtoBuf { // new ProtoBuf.Reflect.Message.ExtensionField(); OneOf: ReflectOneOf; // NOTE: only for new ProtoBuf.Reflect.Message.OneOf(); extensions: number[]; - clazz(): MetaMessage; + clazz(): MetaMessage; isGroup: boolean; - build(rebuild?: boolean): MetaMessage|any; + build(rebuild?: boolean): MetaMessage|any; + build(rebuild?: boolean): MetaMessage|any; encode(message: Message, buffer: Buffer, noVerify?: boolean): Buffer; calculate(message: Message): number; decode(buffer: Buffer, length?: number, expectedGroupEndId?: number): Message; diff --git a/react-bootstrap/react-bootstrap-tests.tsx b/react-bootstrap/react-bootstrap-tests.tsx index 2712853f28..c6976d8a05 100644 --- a/react-bootstrap/react-bootstrap-tests.tsx +++ b/react-bootstrap/react-bootstrap-tests.tsx @@ -7,7 +7,20 @@ // -------------------------------------------------------------------------------- import * as React from 'react'; import { Component, CSSProperties } from 'react'; -import { Button, ButtonToolbar, Modal, Well, ButtonGroup, DropdownButton, MenuItem, Panel, ListGroup, ListGroupItem, Accordion, Tooltip, OverlayTrigger, Popover, ProgressBar, Nav, NavItem, Navbar, NavDropdown, Tabs, Tab, Pager, PageItem, Pagination, Alert, Carousel, CarouselItem, Grid, Row, Col, Thumbnail, Image, Label, Badge, Jumbotron, PageHeader, Glyphicon, Table, Input, ButtonInput, Form, FormGroup, ControlLabel, FormControl, HelpBlock, Radio, Checkbox, Media } from 'react-bootstrap'; +import { + Button, ButtonToolbar, Modal, Well, ButtonGroup, + DropdownButton, MenuItem, Panel, ListGroup, + ListGroupItem, Accordion, Tooltip, + OverlayTrigger, Popover, ProgressBar, + Nav, NavItem, Navbar, NavDropdown, + Tabs, Tab, Pager, PageItem, + Pagination, Alert, Carousel, + Grid, Row, Col, Thumbnail, Image, + Label, Badge, Jumbotron, PageHeader, + Glyphicon, Table, Form, FormGroup, + ControlLabel, FormControl, HelpBlock, + Radio, Checkbox, Media, InputGroup +} from 'react-bootstrap'; export class ReactBootstrapTest extends Component { @@ -116,87 +129,87 @@ export class ReactBootstrapTest extends Component { // TODO: Start here
- - - - - - + + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + +
- - - - - Dropdown link - Dropdown link - - - - - Dropdown link - Dropdown link - - - Dropdown link - Dropdown link - - + + + + + Dropdown link + Dropdown link + + + + + Dropdown link + Dropdown link + + + Dropdown link + Dropdown link + +
- - Action - Another action - Active Item - - Separated link - + + Action + Another action + Active Item + + Separated link +
-
-
    - Header - link - - Header - link - disabled - - link with title - - - link that alerts - -
-
+
+
    + Header + link + + Header + link + disabled + + link with title + + + link that alerts + +
+
@@ -206,520 +219,568 @@ export class ReactBootstrapTest extends Component {
-
- - Panel content - - - Panel content - -
+
+ + Panel content + + + Panel content + +
- - Panel content - + + Panel content +
-
- - Panel content - +
+ + Panel content + - - Panel content - + + Panel content + - - Panel content - + + Panel content + - - Panel content - + + Panel content + - - Panel content - + + Panel content + - - Panel content - -
+ + Panel content + +
- - Some default panel content here. - - Item 1 - Item 2 - … - - Some more panel content here. - + + Some default panel content here. + + Item 1 + Item 2 + … + + Some more panel content here. +
- - - Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer - farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. - - - Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer - farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. - - - Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer - farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. - - + + + Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer + farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. + + + Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer + farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. + + + Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer + farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. + +
-
- - - Modal title - +
+ + + Modal title + - - One fine body... - + + One fine body... + - - - - + + + + + +
+
- -
+
+ ({})} style={style}> + + Modal heading + + +

Text in a modal

+

Duis mollis, est non commodo luctus, nisi erat porttitor ligula.

+ +

Popover in a modal

+

there is a popover here

+ +

Tooltips in a modal

+

there is a tooltip here

+ +
+ +

Overflowing text to show scroll behavior

+

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

+

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

+

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

+

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

+

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

+

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

+

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

+

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

+

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

+
+ + + +
-
- - Tooltip right - +
+ + Tooltip right + - - Tooltip top - + + Tooltip top + - - Tooltip left - + + Tooltip left + - - Tooltip bottom - -
+ + Tooltip bottom + +
- - - - + + + + - - - + + + - - - + + + - - - - + + + +
-
- - And here's some amazing content. It's very engaging. right? - -
+
+ + And here's some amazing content. It's very engaging. right? + +
- - Holy guacamole! Check this info.}> - - - Holy guacamole! Check this info.}> - - - Holy guacamole! Check this info.}> - - - Holy guacamole! Check this info.}> - - - + + Holy guacamole! Check this info.}> + + + Holy guacamole! Check this info.}> + + + Holy guacamole! Check this info.}> + + + Holy guacamole! Check this info.}> + + +
- - Holy guacamole! Check this info.}> - - - Holy guacamole! Check this info.}> - - - Holy guacamole! Check this info.}> - - - Holy guacamole! Check this info.}> - - - Holy guacamole! Check this info.}> - - - + + Holy guacamole! Check this info.}> + + + Holy guacamole! Check this info.}> + + + Holy guacamole! Check this info.}> + + + Holy guacamole! Check this info.}> + + + Holy guacamole! Check this info.}> + + +
- +
- +
-
- - - - -
+
+ + + + +
-
- - - - -
+
+ + + + +
- +
- - - - - + + + + +
- -
- -
- -
- -
-
-
+ +
+ -
- - - - React-Bootstrap - - - - - - - -
- -
- - - -
- -
- - Previous - Next - -
- -
- - Tab 1 content - Tab 2 content - Tab 3 content - -
- -
- - - -
- - Previous - Next - + + + + React-Bootstrap + + + + + + +
- - ← Previous Page - Next Page → - + + +
- - ← Previous - Next → - + + Previous + {' '} + Next +
-
- -
- -
- - -
+ + ← Previous Page + Next Page → +
- - Holy guacamole! Best check yo self, you're not looking too good. - + + ← Previous + Next → +
- - - 900x500 -
-

First slide label

-

Nulla vitae elit libero, a pharetra augue mollis interdum.

-
-
- - 900x500 -
-

Second slide label

-

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

-
-
- - 900x500 -
-

Third slide label

-

Praesent commodo cursus magna, vel scelerisque nisl consectetur.

-
-
-
+ + Tab 1 content + Tab 2 content + Tab 3 content +
- - - <{'Col xs={12} md={8}'} /> - <{'Col xs={6} md={4}'} /> - - - - <{'Col xs={6} md={4}'} /> - <{'Col xs={6} md={4}'} /> - <{'Col xs={6} md={4}'} /> - - - - <{'Col xs={6} xsOffset={6}'} /> - - - - <{'Col md={6} mdPush={6}'} /> - <{'Col md={6} mdPull={6}'} /> - - + + + + + + + + + Tab 1 content + + + Tab 2 content + + + + +
- - - - - - - - - - - - - + + Previous + Next +
- - Item 1 - Item 2 - ... - + + ← Previous Page + Next Page → +
- - Link 1 - Link 2 - - Trigger an alert - - + + ← Previous + Next → +
- - Link 1 - Link 2 - Link 3 - +
+ +
+ +
+ + +
- - Success - Info - Warning - Danger - + + Holy guacamole! Best check yo self, you're not looking too good. +
- - Some body text - Linked item - Danger styling - + + + 900x500 + +

First slide label

+

Nulla vitae elit libero, a pharetra augue mollis interdum.

+
+
+ + 900x500 + +

Second slide label

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

+
+
+ + 900x500 + +

Third slide label

+

Praesent commodo cursus magna, vel scelerisque nisl consectetur.

+
+
+
-
-

Label

-

Label

-

Label

-

Label

-
Label
-

Label

-
+ + + <{'Col xs={12} md={8}'} /> + <{'Col xs={6} md={4}'} /> + + + + <{'Col xs={6} md={4}'} /> + <{'Col xs={6} md={4}'} /> + <{'Col xs={6} md={4}'} /> + + + + <{'Col xs={6} xsOffset={6}'} /> + + + + <{'Col md={6} mdPush={6}'} /> + <{'Col md={6} mdPull={6}'} /> + +
-
-   -   -   -   -   - -
+ + + + + + + + + + + + +
-

Badges 42

+ + Item 1 + Item 2 + ... +
- -

Hello, world!

-

This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.

-

-
+ + Link 1 + Link 2 + + Trigger an alert + + +
+ +
+ + Link 1 + Link 2 + Link 3 + +
+ +
+ + Success + Info + Warning + Danger + +
+ +
+ + Some body text + Linked item + Danger styling + +
+ +
+
+

Label

+

Label

+

Label

+

Label

+
Label
+

Label

+
+
+ +
+
+   +   +   +   +   + +
+
+ +
+

Badges 42

+
+ +
+ +

Hello, world!

+

This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.

+

+
@@ -727,7 +788,7 @@ export class ReactBootstrapTest extends Component {
- Example page header Subtext for header + Example page header Subtext for header
@@ -735,247 +796,407 @@ export class ReactBootstrapTest extends Component {
-
- Look I'm in a large well! - Look I'm in a small well! -
+
+ Look I'm in a large well! + Look I'm in a small well! +
-
- - - - - - - - - - - - - - - - -
+
+ + + + + + + + + + + + + + + + +
- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NumberFirst NameLast NameUsername
1MarkOtto@mdo
2JacobThornton@fat
3Larry the Bird@twitter
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NumberFirst NameLast NameUsername
1MarkOtto@mdo
2JacobThornton@fat
3Larry the Bird@twitter
- - - - - - - - - + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + +
NumberTable headingTable headingTable headingTable headingTable headingTable heading
NumberTable headingTable headingTable headingTable headingTable headingTable heading
1Table cellTable cellTable cellTable cellTable cellTable cell
2Table cellTable cellTable cellTable cellTable cellTable cell
3Table cellTable cellTable cellTable cellTable cellTable cell
1Table cellTable cellTable cellTable cellTable cellTable cell
2Table cellTable cellTable cellTable cellTable cellTable cell
3Table cellTable cellTable cellTable cellTable cellTable cell
- + + Working example with validation + + + Validation is based on string length. +
-
- - - - - - - - - - - - - - - - - - - -
- -
-
- - Child Text - - + + + Text + + + + Email address + + + + Pass + + + + File + + [Optional] Block level help text + + + Checkbox + + + Radio + + + Select + + + + + + + Textarea + +
-
- - - - - - - - -
+
+ + + @ + + + + + + + .00 + + + + + $ + + .00 + + + + + + + + + + + + + + + + + + + + + + + + + Item + + + + + + + + + + + + + + + + + + + + +
-
- - - -
+
+ + + + + + + + + +
-
- - - -
+
+ + Input with success + + Help text with validation state. + + + + Input with warning + + + + + Input with error + + + + + Input with success and feedback icon + + + + + + Input with warning and feedback icon + + + + + + Input with error and feedback icon + + + + + + Input with success and custom feedback icon + + + + + + + + Input group with warning + + @ + + + + + + + + + Input with error + + + + + + + + + + Input group with success + + + + @ + + + + + +
+ +
+ + Input with warning + {' '} + + + + {' '} + + Input group with error + {' '} + + @ + + + + +
+ + + Checkbox with success + + + Radio with warning + + + Checkbox with error + + + {/* This requires React 15's -less spaces to be exactly correct. */} + + + Checkbox + + {' '} + + with + + {' '} + + success + + +
-
- - - -
+
+ + Control Label + + + Help block message. + + + + 1 + {' '} + 2 + {' '} + 3 + + + 1 + {' '} + 2 + {' '} + 3 + +
- - - - - - - - - - -
- -
-
- - Control Label - - - Help block message. - - - - 1 - {' '} - 2 - {' '} - 3 - - - 1 - {' '} - 2 - {' '} - 3 - -
-
- -
- - Image - - - Top aligned media -

Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

-

Donec sed odio dui. Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

-
+ + Image + + + Top aligned media +

Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

+

Donec sed odio dui. Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

+
diff --git a/react-bootstrap/react-bootstrap.d.ts b/react-bootstrap/react-bootstrap.d.ts index 0473057b04..8c9d50a304 100644 --- a/react-bootstrap/react-bootstrap.d.ts +++ b/react-bootstrap/react-bootstrap.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-bootstrap // Project: https://github.com/react-bootstrap/react-bootstrap -// Definitions by: Walker Burgin , Vincent Siao , Danilo Barros +// Definitions by: Walker Burgin , Vincent Siao , Danilo Barros , Batbold Gansukh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -27,12 +27,12 @@ declare namespace ReactBootstrap { interface TransitionCallbacks { - onEnter?: Function; - onEntered?: Function; - onEntering?: Function; - onExit?: Function; - onExited?: Function; - onExiting?: Function; + onEnter?: Function; + onEntered?: Function; + onEntering?: Function; + onExit?: Function; + onExited?: Function; + onExiting?: Function; } @@ -52,14 +52,10 @@ declare namespace ReactBootstrap { // - interface BreadcrumbProps - extends React.Props - { + interface BreadcrumbProps extends React.Props { bsClass?: string; } - interface BreadcrumbClass - extends React.ClassicComponentClass - { + interface BreadcrumbClass extends React.ClassicComponentClass { Item: typeof BreadcrumbItem; } type Breadcrumb = React.ClassicComponent; @@ -67,12 +63,9 @@ declare namespace ReactBootstrap { // - interface BreadcrumbItemProps - extends React.Props - { + interface BreadcrumbItemProps extends React.Props { active?: boolean; id?: string | number; - linkId?: string | number; href?: string; title?: React.ReactNode; target?: string; @@ -82,15 +75,11 @@ declare namespace ReactBootstrap { // + + + ); + } +} diff --git a/react-file-reader-input/react-file-reader-input.d.ts b/react-file-reader-input/react-file-reader-input.d.ts new file mode 100644 index 0000000000..094e690aa1 --- /dev/null +++ b/react-file-reader-input/react-file-reader-input.d.ts @@ -0,0 +1,20 @@ +// Type definitions for react-file-reader-input +// Project: https://www.npmjs.com/package/react-file-reader-input +// Definitions by: Dmitry Rogozhny +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "react-file-reader-input" { + import React = __React; + + interface FileInputProps { + as?: string; + onChange?: (event: React.SyntheticEvent, results: any) => void; + } + + class FileInput extends React.Component { + } + + export = FileInput; +} diff --git a/react-i18next/react-i18next-tests.tsx b/react-i18next/react-i18next-tests.tsx new file mode 100644 index 0000000000..d9faea8ac2 --- /dev/null +++ b/react-i18next/react-i18next-tests.tsx @@ -0,0 +1,95 @@ +/// +/// +/// +/// + + +import * as ReactDOM from 'react-dom'; +import * as React from 'react'; +import * as i18n from 'i18next'; +import { translate, I18nextProvider, Interpolate, InjectedTranslateProps } from 'react-i18next'; + + +i18n + .init({ + fallbackLng: 'en', + + // have a common namespace used around the full app + ns: ['common'], + defaultNS: 'common', + + debug: true, + + interpolation: { + escapeValue: false // not needed for react!! + } + }); + + +interface InnerAnotherComponentProps extends InjectedTranslateProps { +} + +class InnerAnotherComponent extends React.Component { + render() { + const { t } = this.props; + + return

{t('content.text', { /* options t options */ })}

; + } +} + +const AnotherComponent = translate('view', { wait: true })(InnerAnotherComponent); + + + +interface InnerYetAnotherComponentProps extends InjectedTranslateProps { +} + +class InnerYetAnotherComponent extends React.Component { + render() { + const { t } = this.props; + + return

{t('usingDefaultNS', { /* options t options */ })}

; + } +} +const YetAnotherComponent = translate()(InnerYetAnotherComponent); + + +interface TranslatableViewProps extends InjectedTranslateProps { +} + +@translate(['view', 'nav'], { wait: true }) +class TranslatableView extends React.Component { + render() { + const { t } = this.props; + + let interpolateComponent = "a interpolated component"; + + return ( +
+

{t('common:appName')}

+ + + + {t('nav:link1')} +
+ ) + } +} + +class App extends React.Component<{}, {}> { + render() { + return ( +
+
+ +
+
+ ); + } +} + + +ReactDOM.render( + , + document.getElementById('app') +); diff --git a/react-i18next/react-i18next.d.ts b/react-i18next/react-i18next.d.ts new file mode 100644 index 0000000000..0720e6e4ed --- /dev/null +++ b/react-i18next/react-i18next.d.ts @@ -0,0 +1,56 @@ +// Type definitions for react-i18next 1.6.3 +// Project: https://github.com/i18next/react-i18next +// Definitions by: Kostya Esmukov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + + +declare namespace ReactI18next { + import React = __React; + + // Extend your component's Prop interface with this one to get access to `this.props.t` + // + // interface MyComponentProps extends ReactI18next.InjectedTranslateProps {} + export interface InjectedTranslateProps { + t?: I18next.TranslationFunction; + } + + interface I18nextProviderProps { + i18n: I18next.I18n; + children?: React.ReactElement; + } + + export class I18nextProvider extends React.Component { } + + + type InterpolateValue = string | JSX.Element; + + interface InterpolateProps { + i18nKey: string; + + parent?: string; + regexp?: RegExp; + options?: I18next.TranslationOptions; + + [regexKey: string]: InterpolateValue | RegExp | I18next.TranslationOptions; + } + + export class Interpolate extends React.Component { } + + interface TranslateOptions { + withRef?: boolean; + wait?: boolean; + } + + export function translate(namespaces?: string[] | string, options?: TranslateOptions): (WrappedComponent: C) => C; + + export function loadNamespaces({ components, i18n }: { components: ReactRouter.RouteComponent[], i18n: I18next.I18n }): Promise; + +} + +declare module 'react-i18next' { + export = ReactI18next; +} diff --git a/react-native/react-native-tests.tsx b/react-native/react-native-tests.tsx index d33918dbd6..c9d6ec779a 100644 --- a/react-native/react-native-tests.tsx +++ b/react-native/react-native-tests.tsx @@ -78,14 +78,36 @@ var styles = StyleSheet.create( } ) +//alternative declaration of styles (inline typings) +const stylesAlt = StyleSheet.create( + { + container: { + flex: 1, + justifyContent: 'center', + alignItems: 'center', + backgroundColor: '#F5FCFF', + } as React.ViewStyle, + welcome: { + fontSize: 20, + textAlign: 'center', + margin: 10, + } as React.TextStyle, + instructions: { + textAlign: 'center', + color: '#333333', + marginBottom: 5, + } as React.TextStyle + } +) + class Welcome extends React.Component { - + refs: { [key: string]: any rootView: View } - + testNativeMethods() { // this.setNativeProps({}); diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index 0c8e96599e..cc71452ae4 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -8,9 +8,9 @@ // USING: these definitions are meant to be used with the TSC compiler target set to ES6 // // USAGE EXAMPLES: check the RNTSExplorer project at https://github.com/bgrieder/RNTSExplorer +// Warning: the project currently uses and older version of react-native // -// CONTRIBUTING: please open pull requests and make sure that the changes do not break RNTSExplorer (they should not) -// Do not hesitate to open a pull request against RNTSExplorer to provide an example for a case not covered by the current App +// CONTRIBUTING: please open pull requests // // CREDITS: This work is based on an original work made by Bernd Paradies: https://github.com/bparadie // @@ -340,11 +340,15 @@ declare namespace __React { borderWidth?: number bottom?: number flex?: number - flexDirection?: "row" | "column" + flexDirection?: "row" | "column" | "row-reverse" | "column-reverse" flexWrap?: "wrap" | "nowrap" height?: number justifyContent?: FlexJustifyType left?: number + minWidth?: number + maxWidth?: number + minHeight?: number + maxHeight?: number margin?: number marginBottom?: number marginHorizontal?: number @@ -363,6 +367,11 @@ declare namespace __React { right?: number top?: number width?: number + + /** + * @platform ios + */ + zIndex?: number } /** @@ -509,6 +518,12 @@ declare namespace __React { */ allowFontScaling?: boolean + /** + * Line Break mode. Works only with numberOfLines. + * clip is working only for iOS + */ + lineBreakMode?: 'head' | 'middle' | 'tail' | 'clip' + /** * 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. */ @@ -1279,6 +1294,23 @@ declare namespace __React { setPageWithoutAnimation: (selectedPage: number) => void } + export interface KeyboardAvoidingViewStatic extends React.ComponentClass { + + } + + export interface KeyboardAvoidingViewProps extends ViewProperties, React.Props { + + behavior?: 'height' | 'position' | 'padding' + + /** + * This is the distance between the top of the user screen and the react native view, + * may be non-zero in some use cases. + */ + keyboardVerticalOffset: number + + ref?: Ref + } + /** * //FIXME: No documentation extracted from code comment on WebView.ios.js */ @@ -1307,6 +1339,17 @@ declare namespace __React { domStorageEnabled?: boolean } + export interface WebViewIOSLoadRequestEvent { + target: number + canGoBack: boolean + lockIdentifier: number + loading: boolean + title: string + canGoForward: boolean + navigationType: 'other' | 'click' + url: string + } + export interface WebViewPropertiesIOS { /** @@ -1336,7 +1379,7 @@ declare namespace __React { * Return true or false from this method to continue loading the * request. */ - onShouldStartLoadWithRequest?: () => boolean + onShouldStartLoadWithRequest?: (event: WebViewIOSLoadRequestEvent) => boolean scrollEnabled?: boolean } @@ -1431,12 +1474,12 @@ declare namespace __React { /** * view to show if there's an error */ - renderError?: () => ViewStatic + renderError?: () => React.ReactElement /** * loading indicator to show */ - renderLoading?: () => ViewStatic + renderLoading?: () => React.ReactElement scrollEnabled?: boolean @@ -1459,7 +1502,7 @@ declare namespace __React { * sets whether the webpage scales to fit the view and the user can change the scale */ scalesPageToFit?: boolean - + ref?: Ref } @@ -1728,7 +1771,7 @@ declare namespace __React { /** * @Deprecated since version 0.28.0 - */ + */ export interface ActivityIndicatorIOSStatic extends React.ComponentClass { } @@ -2134,7 +2177,7 @@ declare namespace __React { * Size of the refresh indicator, see RefreshControl.SIZE. */ size?: number - + /** * Progress view top offset * @platform android @@ -2155,7 +2198,7 @@ declare namespace __React { * Whether the view should be indicating an active refresh. */ refreshing?: boolean - + ref?: Ref } @@ -3281,6 +3324,16 @@ declare namespace __React { */ popToTop(): void; + /** + * Replace the previous scene and pop to it. + */ + replacePreviousAndPop( route: Route ): void; + + /** + * Navigate to a new scene and reset route stack. + */ + resetTo( route: Route ): void; + } namespace NavigatorStatic { @@ -3354,7 +3407,99 @@ declare namespace __React { } export interface StyleSheetStatic extends React.ComponentClass { + + /** + * Creates a StyleSheet style reference from the given object. + */ create( styles: T ): T; + + /** + * Flattens an array of style objects, into one aggregated style object. + * Alternatively, this method can be used to lookup IDs, returned by + * StyleSheet.register. + * + * > **NOTE**: Exercise caution as abusing this can tax you in terms of + * > optimizations. + * > + * > IDs enable optimizations through the bridge and memory in general. Refering + * > to style objects directly will deprive you of these optimizations. + * + * Example: + * ``` + * var styles = StyleSheet.create({ + * listItem: { + * flex: 1, + * fontSize: 16, + * color: 'white' + * }, + * selectedListItem: { + * color: 'green' + * } + * }); + * + * StyleSheet.flatten([styles.listItem, styles.selectedListItem]) + * // returns { flex: 1, fontSize: 16, color: 'green' } + * ``` + * Alternative use: + * ``` + * StyleSheet.flatten(styles.listItem); + * // return { flex: 1, fontSize: 16, color: 'white' } + * // Simply styles.listItem would return its ID (number) + * ``` + * This method internally uses `StyleSheetRegistry.getStyleByID(style)` + * to resolve style objects represented by IDs. Thus, an array of style + * objects (instances of StyleSheet.create), are individually resolved to, + * their respective objects, merged as one and then returned. This also explains + * the alternative use. + */ + flatten(style: Object): Object + + /** + * This is defined as the width of a thin line on the platform. It can be + * used as the thickness of a border or division between two elements. + * Example: + * ``` + * { + * borderBottomColor: '#bbb', + * borderBottomWidth: StyleSheet.hairlineWidth + * } + * ``` + * + * This constant will always be a round number of pixels (so a line defined + * by it look crisp) and will try to match the standard width of a thin line + * on the underlying platform. However, you should not rely on it being a + * constant size, because on different platforms and screen densities its + * value may be calculated differently. + */ + hairlineWidth: number + + /** + * A very common pattern is to create overlays with position absolute and zero positioning, + * so `absoluteFill` can be used for convenience and to reduce duplication of these repeated + * styles. + */ + absoluteFill: number + + + /** + * Sometimes you may want `absoluteFill` but with a couple tweaks - `absoluteFillObject` can be + * used to create a customized entry in a `StyleSheet`, e.g.: + * + * const styles = StyleSheet.create({ + * wrapper: { + * ...StyleSheet.absoluteFillObject, + * top: 10, + * backgroundColor: 'transparent', + * }, + * }); + */ + absoluteFillObject: { + position: string + left: number + right: number + top: number + bottom: number + } } /** @@ -3516,12 +3661,12 @@ declare namespace __React { * A Boolean value that indicates whether the tab bar is translucent */ translucent?: boolean - + /** * Color of text on unselected tabs */ unselectedTintColor?: string - + ref?: Ref } @@ -3596,8 +3741,10 @@ declare namespace __React { export interface PlatformStatic { OS: PlatformOSType, - // only documented in PlatformSpecificInformation.md - select({PlatformOSType: any}): any + /** + * @see https://facebook.github.io/react-native/docs/platform-specific-code.html#content + */ + select( specifics: { ios?: T, android?: T} ): T; } export interface DeviceEventSubscriptionStatic { @@ -3606,6 +3753,21 @@ declare namespace __React { export interface DeviceEventEmitterStatic { addListener( type: string, onReceived: ( data: T ) => void ): DeviceEventSubscription; + + /** + * Removes the given listener for event of specific type. + * + * @param {string} eventType - Name of the event to emit + * @param {function} listener - Function to invoke when the specified event is + * emitted + * + * @example + * emitter.removeListener('someEvent', function(message) { + * console.log(message); + * }); // removes the listener if already registered + * + */ + removeListener( eventType: String, listener: Function): void } // Used by Dimensions below @@ -3666,9 +3828,11 @@ declare namespace __React { /** * Schedule a function to run after all interactions have completed. + * Returns a cancellable * @param fn */ - runAfterInteractions( fn: () => void | PromiseTask): Promise + runAfterInteractions( fn: () => void | PromiseTask): + {then: Function, done: Function, cancel: Function} /** * Notify manager that an interaction has started. @@ -3950,7 +4114,7 @@ declare namespace __React { * The frequency of the events can be contolled using the scrollEventThrottle prop. */ onScroll?: (event?: { nativeEvent: NativeScrollEvent }) => 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 @@ -3985,7 +4149,7 @@ declare namespace __React { * A RefreshControl component, used to provide pull-to-refresh * functionality for the ScrollView. */ - refreshControl?: RefreshControl + refreshControl?: React.ReactElement ref?: Ref } @@ -4055,7 +4219,7 @@ declare namespace __React { layoutMeasurement: NativeScrollSize; zoomScale: number; } - + // Deduced from // https://github.com/facebook/react-native/commit/052cd7eb8afa7a805ef13e940251be080499919c @@ -4075,18 +4239,18 @@ declare namespace __React { getOpenRowID(): string setOpenRowID(rowID: string): ListViewDataSource } - + export interface SwipeableListViewProps extends React.Props { dataSource: SwipeableListViewDataSource maxSwipeDistance?: number - + // Callback method to render the swipeable view renderRow: ( rowData: any, sectionID: string | number, rowID: string | number, highlightRow?: boolean ) => React.ReactElement - + // Callback method to render the view that will be unveiled on swipe renderQuickActions(rowData: Object, sectionID: string, rowID: string): React.ReactElement } - + export interface SwipeableListViewStatic extends React.ComponentClass { getNewDataSource(): SwipeableListViewDataSource } @@ -4399,9 +4563,27 @@ declare namespace __React { * assets-library tag * a tag not maching any of the above, which means the image data will be stored in memory (and consume memory as long as the process is alive) * + * @deprecated use saveToCameraRoll instead + * */ saveImageWithTag( tag: string ): Promise + /** + * Saves the photo or video to the camera roll / gallery. + * + * On Android, the tag must be a local image or video URI, such as `"file:///sdcard/img.png"`. + * + * On iOS, the tag can be any image URI (including local, remote asset-library and base64 data URIs) + * or a local video file URI (remote or data URIs are not supported for saving video at this time). + * + * If the tag has a file extension of .mov or .mp4, it will be inferred as a video. Otherwise + * it will be treated as a photo. To override the automatic choice, you can pass an optional + * `type` parameter that must be one of 'photo' or 'video'. + * + * Returns a Promise which will resolve with the new URI. + */ + saveToCameraRoll(tag: string, type?: 'photo' | 'video'): Promise + /** * Invokes callback with photo identifier objects from the local camera roll of the device matching shape defined by getPhotosReturnChecker. * @@ -4858,7 +5040,7 @@ declare namespace __React { * Requests all notification permissions from iOS, prompting the user's * dialog box. */ - requestPermissions( permissions?: PushNotificationPermissions[] ): void + requestPermissions( permissions?: PushNotificationPermissions[] ): Promise /** * Unregister for all remote notifications received via Apple Push @@ -4970,17 +5152,10 @@ declare namespace __React { /** - * //FIXME: No documentation is available (although this is self explanatory) - * - * @see https://facebook.github.io/react-native/docs/statusbarios.html#content + * StatusBarIOS is being deprecated. + * @see https://github.com/facebook/react-native/commit/4de616b4c1a9d3556632a93504828f0539fa4fa5 */ export interface StatusBarIOSStatic { - - setStyle(style: StatusBarStyle, animated?: boolean): void - - setHidden(hidden: boolean, animation?: StatusBarAnimation): void - - setNetworkActivityIndicatorVisible(visible: boolean): void } type TimePickerAndroidOpenOptions = { @@ -5072,7 +5247,7 @@ declare namespace __React { * Default value is false. */ value?: boolean - + style?: ViewStyle ref?: Ref @@ -5494,26 +5669,25 @@ declare namespace __React { type: string; } - export interface NavigationState { + export interface NavigationRoute { key: string; } - export interface NavigationParentState extends NavigationState { + export interface NavigationState extends NavigationRoute { index: number; - children: NavigationState[]; + routes: NavigationRoute[]; } export type NavigationRenderer = ( - navigationState: NavigationParentState, + route: NavigationState, onNavigate: (action: NavigationAction) => boolean ) => JSX.Element; // Definitions for NavigationExperimental feature are deduced // from code examples export interface NavigationAnimatedViewStaticProps { - navigationState?: any + route?: any style?: ViewStyle - onNavigate?(action: Object): boolean renderOverlay?(props: Object): JSX.Element applyAnimation(pos: any, navState: Object): void // TODO: what's pos? renderScene?(props: Object): JSX.Element @@ -5521,24 +5695,25 @@ declare namespace __React { export interface NavigationAnimatedViewStatic extends React.ComponentClass { } - + export interface NavigationHeaderProps { renderTitleComponent?(props: Object): JSX.Element + onNavigateBack(): void } - + export interface NavigationHeaderStatic extends React.ComponentClass { Title: JSX.Element HEIGHT: number } - + export interface NavigationCardStackProps { direction?: 'horizontal' | 'vertical' style?: ViewStyle - navigationState?: any - onNavigate(action: Object): boolean + route?: any renderScene?(props: any /* undocumented on 0.27 */): JSX.Element + onNavigateBack(): void } - + export interface NavigationCardStackStatic extends React.ComponentClass { } @@ -5548,7 +5723,7 @@ declare namespace __React { Header: NavigationHeaderStatic; Reducer: NavigationReducerStatic; } - + export interface NavigationContainerProps { tabs: NavigationTab[]; index: number; @@ -5569,6 +5744,27 @@ declare namespace __React { handleNavigation( action: NavigationAction ): boolean; } + // + // Interfacing with Native Modules + // https://facebook.github.io/react-native/docs/native-modules-ios.html + // + + export interface NativeEventSubscription { + /** + * Call this method to un-subscribe from a native-event + */ + remove(): void; + } + + /** + * Receive events from native-code + * @see https://facebook.github.io/react-native/docs/native-modules-ios.html#sending-events-to-javascript + */ + export interface NativeAppEventEmitterStatic { + addListener(event: string, handler: (data: any) => void): NativeEventSubscription; + } + + ////////////////////////////////////////////////////////////////////////// // // R E - E X P O R T S @@ -5639,7 +5835,7 @@ declare namespace __React { export var StyleSheet: StyleSheetStatic export type StyleSheet = StyleSheetStatic - + export var SwipeableListView: SwipeableListViewStatic export type SwipeableListView = SwipeableListViewStatic @@ -5720,6 +5916,9 @@ declare namespace __React { export var IntentAndroid: IntentAndroidStatic export type IntentAndroid = IntentAndroidStatic + export var KeyboardAvoidingView: KeyboardAvoidingViewStatic + export type KeyboardAvoidingView = KeyboardAvoidingViewStatic + export var Linking: LinkingStatic export type Linking = LinkingStatic @@ -5768,6 +5967,16 @@ declare namespace __React { export type Easing = EasingStatic; export var Easing: EasingStatic; + //Native Modules written in ObjectiveC/Swift/Java exposed via the RCTBridge + //See https://facebook.github.io/react-native/docs/native-modules-ios.html + + /** + * Use: + * const MyModule = NativeModules.ModuleName + */ + export var NativeModules: any + export var NativeAppEventEmitter: NativeAppEventEmitterStatic + // // /TODO: BGR: These are leftovers of the initial port that must be revisited // @@ -5831,3 +6040,12 @@ declare module "react-native" { declare var global: __React.GlobalStatic declare function require( name: string ): any + +/** + * This variable is set to true when react-native is running in Dev mode + * Typical usage: + * if (__DEV__) console.log('Running in dev mode') + */ +declare var __DEV__: boolean + + diff --git a/react-relay/react-relay-test.tsx b/react-relay/react-relay-test.tsx new file mode 100644 index 0000000000..e6632e76f9 --- /dev/null +++ b/react-relay/react-relay-test.tsx @@ -0,0 +1,46 @@ +/// +/// + +import * as React from "react" +import * as Relay from "react-relay" + +interface Props { + text: string + userId: string +} + +interface Response { +} + +export default class AddTweetMutation extends Relay.Mutation { + + getMutation () { + return Relay.QL`mutation{addTweet}` + } + + getFatQuery () { + return Relay.QL` + fragment on AddTweetPayload { + tweetEdge + user + } + ` + } + + getConfigs () { + return [{ + type: "RANGE_ADD", + parentName: "user", + parentID: this.props.userId, + connectionName: "tweets", + edgeName: "tweetEdge", + rangeBehaviors: { + "": "append", + }, + }] + } + + getVariables () { + return this.props + } +} diff --git a/react-relay/react-relay.d.ts b/react-relay/react-relay.d.ts new file mode 100644 index 0000000000..1a0ae89069 --- /dev/null +++ b/react-relay/react-relay.d.ts @@ -0,0 +1,112 @@ +// Type definitions for react-relay 0.9.2 +// Project: https://github.com/facebook/relay +// Definitions by: Johannes Schickling +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "react-relay" { + import * as React from "react"; + + /** Fragments are a hash of functions */ + interface Fragments { + [query: string]: ((variables?: RelayVariables) => string) + } + + interface CreateContainerOpts { + initialVariables?: Object + fragments: Fragments + prepareVariables?(prevVariables: RelayVariables): RelayVariables + } + + interface RelayVariables { + [name: string]: any + } + + /** add static getFragment method to the component constructor */ + interface RelayContainerClass extends React.ComponentClass { + getFragment: ((q: string) => string) + } + + interface RelayQueryRequestResolve { + response: any + } + + interface RelayMutationRequest { + getQueryString(): string + getVariables(): RelayVariables + resolve(result: RelayQueryRequestResolve): any + reject(errors: any): any + } + + interface RelayQueryRequest { + resolve(result: RelayQueryRequestResolve): any + reject(errors: any): any + + getQueryString(): string + getVariables(): RelayVariables + getID(): string + getDebugName(): string + } + + interface RelayNetworkLayer { + supports(...options: string[]): boolean + } + + class DefaultNetworkLayer implements RelayNetworkLayer { + constructor(host: string, options: any) + supports(...options: string[]): boolean + } + + function createContainer(component: React.ComponentClass, params?: CreateContainerOpts): RelayContainerClass + function injectNetworkLayer(networkLayer: RelayNetworkLayer): any + function isContainer(component: React.ComponentClass): boolean + function QL(...args: any[]): string + + class Route { + constructor(params?: RelayVariables) + } + + /** + * Relay Mutation class, where T are the props it takes and S is the returned payload from Relay.Store.update. + * S is typically dynamic as it depends on the data the app is currently using, but it's possible to always + * return some data in the payload using REQUIRED_CHILDREN which is where specifying S is the most useful. + */ + class Mutation { + props: T + + constructor(props: T) + static getFragment(q: string): string + } + + interface Transaction { + getError(): Error + Status(): number + } + + interface StoreUpdateCallbacks { + onFailure?(transaction: Transaction): any + onSuccess?(response: T): any + } + + interface Store { + commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any + } + + var Store: Store + + class RootContainer extends React.Component {} + + interface RootContainerProps extends React.Props{ + Component: RelayContainerClass + route: Route + renderLoading?(): JSX.Element + renderFetched?(data: any): JSX.Element + renderFailure?(error: Error, retry: Function): JSX.Element + } + + interface RelayProp { + variables: any + setVariables(variables: Object): void + } +} diff --git a/react-select/react-select-tests.tsx b/react-select/react-select-tests.tsx index 7b8027123d..de45b52d32 100644 --- a/react-select/react-select-tests.tsx +++ b/react-select/react-select-tests.tsx @@ -141,6 +141,25 @@ class SelectTest extends React.Component, {}> { } } +class SelectWithStringValueTest extends React.Component, {}> { + + render() { + const options: Option[] = [{ label: "Foo", value: "bar" }]; + const onChange = (value: any) => console.log(value); + + const selectProps: ReactSelectProps = { + name: "test-select-with-string-value", + value: "bar", + options: options, + onChange: onChange + }; + + return
+