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/alexa-sdk/alexa-sdk-tests.ts b/alexa-sdk/alexa-sdk-tests.ts new file mode 100644 index 0000000000..e161c5bf38 --- /dev/null +++ b/alexa-sdk/alexa-sdk-tests.ts @@ -0,0 +1,25 @@ +/// +/// + +import * as Alexa from "alexa-sdk"; + +exports.handler = function(event: Alexa.RequestBody, context: Alexa.Context, callback: Function) { + let alexa = Alexa.handler(event, context); + alexa.registerHandlers(handlers); + alexa.execute(); +}; + +let handlers: Alexa.Handlers = { + 'LaunchRequest': function () { + var self: Alexa.Handler = this; + self.emit('SayHello'); + }, + 'HelloWorldIntent': function () { + var self: Alexa.Handler = this; + self.emit('SayHello'); + }, + 'SayHello': function () { + var self: Alexa.Handler = this; + self.emit(':tell', 'Hello World!'); + } +}; diff --git a/alexa-sdk/alexa-sdk.d.ts b/alexa-sdk/alexa-sdk.d.ts new file mode 100644 index 0000000000..5866d8c4ee --- /dev/null +++ b/alexa-sdk/alexa-sdk.d.ts @@ -0,0 +1,132 @@ +// Type definitions for Alexa SDK for Node.js v1.0.3 +// Project: https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs +// Definitions by: Pete Beegle +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'alexa-sdk' { + export function handler(event: RequestBody, context: Context, callback?: Function): AlexaObject; + export function CreateStateHandler(state: string, obj: any): any; + export var StateString: string; + + interface AlexaObject { + _event: any; + _context: any; + _callback: any; + state: any; + appId: any; + response: any; + dynamoDBTableName: any; + saveBeforeResponse: boolean; + registerHandlers: (...handlers: Handlers[]) => any; + execute: () => void; + } + + interface Handlers { + [intent: string]: () => void; + } + + interface Handler { + on: any; + emit(event: string, ...args: any[]): boolean; + emitWithState: any; + state: any; + handler: any; + event: RequestBody; + attributes: any; + context: any; + name: any; + isOverriden: any; + } + + interface Context { + callbackWaitsForEmptyEventLoop: boolean; + logGroupName: string; + logStreamName: string; + functionName: string; + memoryLimitInMB: string; + functionVersion: string; + invokeid: string; + awsRequestId: string; + } + + interface RequestBody { + version: string; + session: Session; + request: LaunchRequest | IntentRequest | SessionEndedRequest; + } + + interface Session { + new: boolean; + sessionId: string; + attributes: any; + application: SessionApplication; + user: SessionUser; + } + + interface SessionApplication { + applicationId: string; + } + + interface SessionUser { + userId: string; + accessToken: string; + } + + interface LaunchRequest extends IRequest {} + + interface IntentRequest extends IRequest { + intent: Intent; + } + + interface Intent { + name: string; + slots: any; + } + + interface SessionEndedRequest extends IRequest{ + reason: string; + } + + interface IRequest { + type: "LaunchRequest" | "IntentRequest" | "SessionEndedRequest"; + requestId: string; + timeStamp: string; + } + + interface ResponseBody { + version: string; + sessionAttributes?: any; + response: Response; + } + + interface Response { + outputSpeech?: OutputSpeech; + card?: Card; + reprompt?: Reprompt; + shouldEndSession: boolean; + } + + interface OutputSpeech { + type: "PlainText" | "SSML"; + text?: string; + ssml?: string; + } + + interface Card { + type: "Simple" | "Standard" | "LinkAccount"; + title?: string; + content?: string; + text?: string; + image?: Image; + } + + interface Image { + smallImageUrl: string; + largeImageUrl: string; + } + + interface Reprompt { + outputSpeech: OutputSpeech; + } +} + 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..27998956b8 100644 --- a/amcharts/AmCharts.d.ts +++ b/amcharts/AmCharts.d.ts @@ -26,6 +26,19 @@ 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; + + /** Set a method to be called before initializing the chart. + * When the method is called, the chart instance is passed as an attribute. + * You can use this feature to preprocess chart data or do some other things you need + * before initializing the chart. + * @param {Function} handler - The method to be called. + * @param {string[]} types - Which chart types should call this method. Defaults to all + * if none is passed. + */ + function addInitHandler(handler: Function, types: string[]); /** 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 @@ -1003,7 +1016,7 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val bold - specifies if text is bold (true/false), url - url */ - addLabel(x: number, y: number, text: string, align: string, size: number, color: string, rotation: number, alpha: number, bold: boolean, url: string); + addLabel(x: number|string, y: number|string, text: string, align: string, size?: number, color?: string, rotation?: number, alpha?: number, bold?: boolean, url?: string); /** Adds a legend to the chart. By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. (NOTE: This method will not work on StockPanel.) diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 5e780fe005..23da7bceb2 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 { @@ -298,6 +299,7 @@ declare namespace angular.material { locals?: {[index: string]: any}; resolve?: {[index: string]: angular.IPromise} attachTo?: string|JQuery|Element; + propagateContainerEvents?: boolean; panelClass?: string; zIndex?: number; // default: 80 position?: IPanelPosition; @@ -330,16 +332,18 @@ declare namespace angular.material { addClass(newClass: string): void; removeClass(oldClass: string): void; toggleClass(toggleClass: string): void; - focusOnOpen(): void; + updatePosition(position: IPanelPosition): void; } interface IPanelPosition { absolute(): IPanelPosition; relativeTo(someElement: string|JQuery|Element): IPanelPosition; - top(opt_top: string): IPanelPosition; // default: '0' - bottom(opt_bottom: string): IPanelPosition; // default: '0' - left(opt_left: string): IPanelPosition; // default: '0' - right(opt_right: string): IPanelPosition; // default: '0' + top(top?: string): IPanelPosition; // default: '0' + bottom(bottom?: string): IPanelPosition; // default: '0' + start(start?: string): IPanelPosition; // default: '0' + end(end?: string): IPanelPosition; // default: '0' + left(left?: string): IPanelPosition; // default: '0' + right(right?: string): IPanelPosition; // default: '0' centerHorizontally(): IPanelPosition; centerVertically(): IPanelPosition; center(): IPanelPosition; @@ -359,5 +363,24 @@ declare namespace angular.material { open(opt_config: IPanelConfig): angular.IPromise; newPanelPosition(): IPanelPosition; newPanelAnimation(): IPanelAnimation; + xPosition: { + CENTER: string, + ALIGN_START: string, + ALIGN_END: string, + OFFSET_START: string, + OFFSET_END: string, + }; + yPosition: { + CENTER: string, + ALIGN_TOPS: string, + ALIGN_BOTTOMS: string, + ABOVE: string, + BELOW: string, + }; + animation: { + SLIDE: string, + SCALE: string, + FADE: string, + }; } } 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/angular-ui-router/angular-ui-router-tests.ts b/angular-ui-router/angular-ui-router-tests.ts index 9c5db1754a..a588faa448 100644 --- a/angular-ui-router/angular-ui-router-tests.ts +++ b/angular-ui-router/angular-ui-router-tests.ts @@ -1,6 +1,7 @@ /// -var myApp = angular.module('testModule'); +import uiRouterModule from "angular-ui-router"; +var myApp = angular.module("testModule", [uiRouterModule]); interface MyAppScope extends ng.IScope { items: string[]; @@ -141,7 +142,7 @@ class UrlLocatorTestService implements IUrlLocatorTestService { private $state: ng.ui.IStateService ) { $rootScope.$on("$locationChangeSuccess", (event: ng.IAngularEvent) => this.onLocationChangeSuccess(event)); - $rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) => + $rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) => this.onStateNotFound(event, unfoundState, fromState, fromParams)); } @@ -164,14 +165,14 @@ class UrlLocatorTestService implements IUrlLocatorTestService { }); } } - + private onStateNotFound(event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) { var unfoundTo: string = unfoundState.to; var unfoundToParams: {} = unfoundState.toParams; - var unfoundOptions: ng.ui.IStateOptions = unfoundState.options + var unfoundOptions: ng.ui.IStateOptions = unfoundState.options } private stateServiceTest() { diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 0f0ac8caa3..7e4f097c8c 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -7,13 +7,7 @@ // Support for AMD require and CommonJS declare module 'angular-ui-router' { - // Since angular-ui-router adds providers for a bunch of - // injectable dependencies, it doesn't really return any - // actual data except the plain string 'ui.router'. - // - // As such, I don't think anybody will ever use the actual - // default value of the module. So I've only included the - // the types. (@xogeny) + export default "ui.router"; export type IState = angular.ui.IState; export type IStateProvider = angular.ui.IStateProvider; export type IUrlMatcher = angular.ui.IUrlMatcher; @@ -109,7 +103,7 @@ declare namespace angular.ui { toParams: {}, options: IStateOptions } - + interface IStateProvider extends angular.IServiceProvider { state(name:string, config:IState): IStateProvider; state(config:IState): IStateProvider; 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/auth0.lock/auth0.lock-tests.ts b/auth0.lock/auth0.lock-tests.ts index fd646ee1bb..07a7cf8323 100644 --- a/auth0.lock/auth0.lock-tests.ts +++ b/auth0.lock/auth0.lock-tests.ts @@ -1,13 +1,165 @@ /// /// -var lock: Auth0LockStatic = new Auth0Lock("dsa7d77dsa7d7", "mine.auth0.com"); +const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; +const DOMAIN = "YOUR_DOMAIN_AT.auth0.com"; -lock.showSignin({ - connections: ["facebook", "google-oauth2", "twitter", "Username-Password-Authentication"], - icon: "https://contoso.com/logo-32.png", - socialBigButtons: true - }, - () => { - // The Auth0 Widget is now loaded. +var lock: Auth0LockStatic = new Auth0Lock(CLIENT_ID, DOMAIN); + +lock.show(); +lock.hide(); +lock.logout(() => {}); + +// The examples below are lifted from auth0-lock documentation on Github + +// "on" event-driven example + +lock.on("authenticated", function(authResult : any) { + lock.getProfile(authResult.idToken, function(error, profile) { + if (error) { + // Handle error + return; + } + + localStorage.setItem("idToken", authResult.idToken); + localStorage.setItem("profile", JSON.stringify(profile)); + }); }); + + +// test theme + +var themeOptions : Auth0LockConstructorOptions = { + theme: { + logo: "https://example.com/assets/logo.png", + primaryColor: "green" + } +}; + +new Auth0Lock(CLIENT_ID, DOMAIN, themeOptions); + +// test authentication + +var authOptions : Auth0LockConstructorOptions = { + auth: { + params: { state: "foo" }, + redirect: true, + redirectUrl: "some url", + responseType: "token", + sso: true + } +}; + +new Auth0Lock(CLIENT_ID, DOMAIN, authOptions); + +// test multi-variant example + +var multiVariantOptions : Auth0LockConstructorOptions = { + container: "myContainer", + closable: false, + languageDictionary: { + signUpTerms: "I agree to the terms of service ...", + title: "My Company", + }, + autofocus: false +}; + +new Auth0Lock(CLIENT_ID, DOMAIN, multiVariantOptions); + +// test text-field additional sign up field + +var textFieldOptions : Auth0LockConstructorOptions = { + additionalSignUpFields: [{ + name: "address", + placeholder: "enter your address", + // The following properties are optional + icon: "https://example.com/assests/address_icon.png", + prefill: "street 123", + validator: function(input : string) { + return { + valid: input.length >= 10, + hint: "Must have 10 or more chars" // optional + }; + } + }] +}; + +new Auth0Lock(CLIENT_ID, DOMAIN, textFieldOptions); + +// test select-field additional sign up field + +var selectFieldOptions : Auth0LockConstructorOptions = { + additionalSignUpFields: [{ + type: "select", + name: "location", + placeholder: "choose your location", + options: [ + {value: "us", label: "United States"}, + {value: "fr", label: "France"}, + {value: "ar", label: "Argentina"} + ], + // The following properties are optional + icon: "https://example.com/assests/location_icon.png", + prefill: "us" + }] +}; + +new Auth0Lock(CLIENT_ID, DOMAIN, selectFieldOptions); + +// test select-field additional sign up field with callbacks for + +var selectFieldOptionsWithCallbacks : Auth0LockConstructorOptions = { + additionalSignUpFields: [{ + type: "select", + name: "location", + placeholder: "choose your location", + options: function(cb) { + // obtain options, in case of error you call cb with the error in the + // first arg instead of null + + let options = [ + {value: "us", label: "United States"}, + {value: "fr", label: "France"}, + {value: "ar", label: "Argentina"} + ]; + + cb(null, options); + }, + icon: "https://example.com/assests/location_icon.png", + prefill: function(cb) { + // obtain prefill, in case of error you call cb with the error in the + // first arg instead of null + + let prefill = "us"; + + cb(null, prefill); + } + }] +} + +new Auth0Lock(CLIENT_ID, DOMAIN, selectFieldOptionsWithCallbacks); + +// test Avatar options + +var avatarOptions : Auth0LockConstructorOptions = { + avatar: { + url: (email : string, cb : Auth0LockAvatarUrlCallback) => { + // obtain url for email, in case of error you call cb with the error in + // the first arg instead of null + + let url = "url"; + + cb(null, url); + }, + displayName: (email : string, cb : Auth0LockAvatarDisplayNameCallback) => { + // obtain displayName for email, in case of error you call cb with the + // error in the first arg instead of null + + let displayName = "displayName"; + + cb(null, displayName); + } + } +}; + +new Auth0Lock(CLIENT_ID, DOMAIN, avatarOptions); diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts index 15f767984b..7a459afd97 100644 --- a/auth0.lock/auth0.lock.d.ts +++ b/auth0.lock/auth0.lock.d.ts @@ -1,10 +1,70 @@ -// Type definitions for Auth0Widget.js +// Type definitions for auth0-lock v10.0.1 // Project: http://auth0.com -// Definitions by: Robert McLaws +// Definitions by: Brian Caruso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +interface Auth0LockAdditionalSignUpFieldOption { + value: string; + label: string; +} + +type Auth0LockAdditionalSignUpFieldOptionsCallback = + (error: Auth0Error, options: Auth0LockAdditionalSignUpFieldOption[]) => void; + +type Auth0LockAdditionalSignUpFieldOptionsFunction = + (callback: Auth0LockAdditionalSignUpFieldOptionsCallback) => void; + +type Auth0LockAdditionalSignUpFieldPrefillCallback = + (error: Auth0Error, prefill: string) => void; + +type Auth0LockAdditionalSignUpFieldPrefillFunction = + (callback: Auth0LockAdditionalSignUpFieldPrefillCallback) => void; + +interface Auth0LockAdditionalSignUpField { + icon?: string; + name: string; + options?: Auth0LockAdditionalSignUpFieldOption[] | Auth0LockAdditionalSignUpFieldOptionsFunction; + placeholder: string; + prefill?: string | Auth0LockAdditionalSignUpFieldPrefillFunction; + type?: "select" | "text"; + validator?: (input: string) => { valid: boolean; hint?: string }; +} + +type Auth0LockAvatarUrlCallback = (error: Auth0Error, url: string) => void; +type Auth0LockAvatarDisplayNameCallback = (error: Auth0Error, displayName: string) => void; + +interface Auth0LockAvatarOptions { + url: (email: string, callback: Auth0LockAvatarUrlCallback) => void; + displayName: (email: string, callback: Auth0LockAvatarDisplayNameCallback) => void; +} + +interface Auth0LockThemeOptions { + logo?: string; + primaryColor?: string; +} + +// https://auth0.com/docs/libraries/lock/v10/sending-authentication-parameters +interface Auth0LockAuthParamsOptions { + access_token?: any; + connection_scopes?: any; + device?: any; + nonce?: any; + protocol?: any; + request_id?: any; + scope?: string; + state?: string; +} + +interface Auth0LockAuthOptions { + params?: Auth0LockAuthParamsOptions; + redirect?: boolean; + redirectUrl?: string; + responseType?: string; + sso?: boolean; +} + interface Auth0LockPopupOptions { width: number; height: number; @@ -12,68 +72,51 @@ interface Auth0LockPopupOptions { top: number; } -interface Auth0LockOptions { - authParams?: any; - callbackURL?: string; - connections?: string[]; - container?: string; - closable?: boolean; - dict?: any; - defaultUserPasswordConnection?: string; - defaultADUsernameFromEmailPrefix?: boolean; - disableResetAction?: boolean; - disableSignupAction?: boolean; - focusInput?: boolean; - forceJSONP?: boolean; - gravatar?: boolean; - integratedWindowsLogin?: boolean; - icon?: string; - loginAfterSignup?: boolean; - popup?: boolean; - popupOptions?: Auth0LockPopupOptions; - rememberLastLogin?: boolean; - resetLink?: string; - responseType?: string; - signupLink?: string; - socialBigButtons?: boolean; - sso?: boolean; - theme?: string; - usernameStyle?: any; -} - interface Auth0LockConstructorOptions { - cdn?: string; + additionalSignUpFields?: Auth0LockAdditionalSignUpField[]; + allowedConnections?: string[]; + allowForgotPassword?: boolean; + allowLogin?: boolean; + allowSignUp?: boolean; assetsUrl?: string; - useCordovaSocialPlugins?: boolean; + auth?: Auth0LockAuthOptions; + autoclose?: boolean; + autofocus?: boolean; + avatar?: Auth0LockAvatarOptions; + closable?: boolean; + container?: string; + defaultADUsernameFromEmailPrefix?: string; + defaultDatabaseConnection?: string; + defaultEnterpriseConnection?: string; + forgotPasswordLink?: string; + initialScreen?: "login" | "signUp" | "forgotPassword"; + language?: string; + languageDictionary?: any; + loginAfterSignup?: boolean; + mustAcceptTerms?: boolean; + popupOptions?: Auth0LockPopupOptions; + prefill?: { email?: string, username?: string}; + rememberLastLogin?: boolean; + signupLink?: string; + socialButtonStyle?: "big" | "small"; + theme?: Auth0LockThemeOptions; + usernameStyle?: string; } interface Auth0LockStatic { new (clientId: string, domain: string, options?: Auth0LockConstructorOptions): Auth0LockStatic; + getProfile(token: string, callback: (error: Auth0Error, profile: Auth0UserProfile) => void) : void; show(): void; - show(options: Auth0LockOptions): void; - show(callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; - show(options: Auth0LockOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; + hide(): void; + logout(query: any): void; - showSignin(): void; - showSignin(options: Auth0LockOptions): void; - showSignin(callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; - showSignin(options: Auth0LockOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; - - showSignup(): void; - showSignup(options: Auth0LockOptions): void; - showSignup(callback: (error?: Auth0Error) => void) : void; - showSignup(options: Auth0LockOptions, callback: (error?: Auth0Error) => void) : void; - - showReset(): void; - showReset(options: Auth0LockOptions): void; - showReset(callback: (error?: Auth0Error) => void) : void; - showReset(options: Auth0LockOptions, callback: (error?: Auth0Error) => void) : void; - - hide(callback: () => void): void; - logout(callback: () => void): void; - - getClient(): Auth0Static; + on(event: "show", callback: () => void) : void; + on(event: "hide", callback: () => void) : void; + on(event: "unrecoverable_error", callback: (error: Auth0Error) => void) : void; + on(event: "authorization_error", callback: (error: Auth0Error) => void) : void; + on(event: "authenticated", callback: (authResult: any) => void) : void; + on(event: string, callback: (...args: any[]) => void) : void; } declare var Auth0Lock: Auth0LockStatic; 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/autosize/autosize-tests.ts b/autosize/autosize-tests.ts new file mode 100644 index 0000000000..23686fbd88 --- /dev/null +++ b/autosize/autosize-tests.ts @@ -0,0 +1,10 @@ +/// + +// from a NodeList +autosize(document.querySelectorAll('textarea')); + +// from a single Node +autosize(document.querySelector('textarea')); + +// from a single element +autosize(document.getElementById('my-textarea')); diff --git a/autosize/autosize.d.ts b/autosize/autosize.d.ts new file mode 100644 index 0000000000..0a8a696c3d --- /dev/null +++ b/autosize/autosize.d.ts @@ -0,0 +1,17 @@ +// Type definitions for jquery.autosize 3.0.7 +// Project: http://www.jacklmoore.com/autosize/ +// Definitions by: Aaron T. King +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace autosize { + interface AutosizeStatic { + (el: Element): void; + (el: NodeList): void; + } +} + +declare var autosize: autosize.AutosizeStatic; + +declare module 'autosize' { + export = autosize; +} 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..cb35f34e97 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -9,1496 +9,1805 @@ 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; + createTable(params: any, next: (err: any, data: any) => void): void; + deleteTable(params: any, next: (err: any, data: any) => void): void; + } + + // ========================================================== + + export module DynamoDB { + + interface _DDBDC_Generic { + TableName: string; + ExpressionAttributeNames?: { [someKey: string]: 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/backbone/backbone-global.d.ts b/backbone/backbone-global.d.ts index d86305ee3d..3dca269eb0 100644 --- a/backbone/backbone-global.d.ts +++ b/backbone/backbone-global.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Backbone 1.0.0 +// Type definitions for Backbone 1.3.3 // Project: http://backbonejs.org/ // Definitions by: Boris Yankov , Natan Vivo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -109,9 +109,15 @@ declare namespace Backbone { attributes: any; changed: any[]; + cidPrefix: string; cid: string; collection: Collection; + private _changing: boolean; + private _previousAttributes : any; + private _pending: boolean; + + /** * Default attributes for the model. It can be an object hash or a method returning an object hash. * For assigning an object hash, do it like this: this.defaults = { attribute: value, ... }; @@ -147,7 +153,14 @@ declare namespace Backbone { /*private*/ set(attributeName: string, value: any, options?: ModelSetOptions): Model; set(obj: any, options?: ModelSetOptions): Model; - changedAttributes(attributes?: any): any[]; + /** + * Return an object containing all the attributes that have changed, or + * false if there are no changed attributes. Useful for determining what + * parts of a view need to be updated and/or what attributes need to be + * persisted to the server. Unset attributes will be set to undefined. + * You can also pass an attributes object to diff against the model, + * determining if there *would be* a change. */ + changedAttributes(attributes?: any): any; clear(options?: Silenceable): any; clone(): Model; destroy(options?: ModelDestroyOptions): any; @@ -178,6 +191,7 @@ declare namespace Backbone { omit(fn: (value: any, key: any, object: any) => any): any; chain(): any; isEmpty(): boolean; + matches(attrs: any): boolean; } class Collection extends ModelBase { @@ -208,6 +222,7 @@ declare namespace Backbone { * Get a model from a collection, specified by an id, a cid, or by passing in a model. **/ get(id: number|string|Model): TModel; + has(key: number|string|Model): boolean; create(attributes: any, options?: ModelSaveOptions): TModel; pluck(attribute: string): any[]; push(model: TModel, options?: AddOptions): TModel; @@ -221,10 +236,12 @@ declare namespace Backbone { unshift(model: TModel, options?: AddOptions): TModel; where(properties: any): TModel[]; findWhere(properties: any): TModel; + modelId(attrs: any) : any private _prepareModel(attributes?: any, options?: any): any; private _removeReference(model: TModel): void; private _onModelEvent(event: string, model: TModel, collection: Collection, options: any): void; + private _isModel(obj: any) : obj is Model; /** * Return a shallow copy of this collection's models, using the same options as native Array#slice. @@ -314,6 +331,8 @@ declare namespace Backbone { navigate(fragment: string, options?: NavigateOptions): Router; navigate(fragment: string, trigger?: boolean): Router; + execute(callback: Function, args: any[], name: string) : void; + private _bindRoutes(): void; private _routeToRegExp(route: string): RegExp; private _extractParameters(route: RegExp, fragment: string): string[]; @@ -330,9 +349,14 @@ declare namespace Backbone { getHash(window?: Window): string; getFragment(fragment?: string): string; + decodeFragment(fragment: string): string; + getSearch(): string; stop(): void; route(route: string, callback: Function): number; checkUrl(e?: any): void; + getPath(): string; + matchRoot(): boolean; + atRoot(): boolean; loadUrl(fragmentOverride?: string): boolean; navigate(fragment: string, options?: any): boolean; static started: boolean; diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 65e273a61f..d3887b4176 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Backbone 1.0.0 +// Type definitions for Backbone 1.3.3 // Project: http://backbonejs.org/ // Definitions by: Boris Yankov , Natan Vivo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped 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/c3/c3.d.ts b/c3/c3.d.ts index f5159090d2..2838ba2675 100644 --- a/c3/c3.d.ts +++ b/c3/c3.d.ts @@ -747,7 +747,7 @@ declare namespace c3 { /** * The radius size of each point. */ - r?: number; + r?: number | ((d: any) => number); focus?: { expand: { diff --git a/cassandra-driver/cassandra-driver.d.ts b/cassandra-driver/cassandra-driver.d.ts index 0da40f2081..9a4184b62e 100644 --- a/cassandra-driver/cassandra-driver.d.ts +++ b/cassandra-driver/cassandra-driver.d.ts @@ -16,10 +16,10 @@ declare module "cassandra-driver" { namespace policies { namespace addressResolution { - var EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic; + var EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic; interface AddressTranslator { - translate(address: string, port: number, callback: Callback): void; + translate(address: string, port: number, callback: Callback): void; } interface EC2MultiRegionTranslatorStatic { @@ -141,7 +141,7 @@ declare module "cassandra-driver" { var Tuple: TupleStatic; var Uuid: UuidStatic; - enum consistencies { + enum consistencies { any = 0, one, two, @@ -154,7 +154,7 @@ declare module "cassandra-driver" { localSerial, localOne } - + enum dataTypes { custom = 0, ascii, @@ -204,7 +204,7 @@ declare module "cassandra-driver" { fromString(value: string): BigDecimal; fromNumber(value: number): BigDecimal; } - + interface BigDecimal { equals(other: BigDecimal): boolean; inspect(): string; @@ -239,7 +239,7 @@ declare module "cassandra-driver" { interface IntegerStatic { new(bits: Array, sign: number): Integer; - + fromInt(value: number): Integer; fromNumber(value: number): Integer; fromBits(bits: Array): Integer; @@ -295,7 +295,7 @@ declare module "cassandra-driver" { fromString(value: string): LocalDate; fromBuffer(buffer: Buffer): LocalDate; } - + interface LocalDate { _value: number; year: number; @@ -384,7 +384,7 @@ declare module "cassandra-driver" { interface TimeUuidStatic { new (value?: Date, ticks?: number, nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid; - + fromDate(date: Date, ticks?: number, nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid; fromString(value: string): TimeUuid; min(date: Date, ticks?: number): TimeUuid; @@ -408,7 +408,7 @@ declare module "cassandra-driver" { interface Tuple { elements: Array; length: number; - + get(index: number): any; toString(): string; toJSON(): string; @@ -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; @@ -513,7 +513,7 @@ declare module "cassandra-driver" { execute(query: string, params?: any, options?: QueryOptions, callback?: ResultCallback): void; getReplicas(keyspace: string, token: Buffer): Array; // TODO: Should this be a more explicit return? shutdown(callback?: Callback): void; - stream(query: string, params?: any, options?: QueryOptions, callback?: Callback): void; + stream(query: string, params?: any, options?: QueryOptions, callback?: Callback): NodeJS.ReadableStream; } interface HostStatic { @@ -549,7 +549,7 @@ declare module "cassandra-driver" { } interface EncoderStatic { - new(protocolVersion: number, options: ClientOptions) : Encoder; + new(protocolVersion: number, options: ClientOptions) : Encoder; } interface Encoder { @@ -590,29 +590,29 @@ declare module "cassandra-driver" { } class ArgumentError extends DriverError { - constructor(message: string); + constructor(message: string); } class AuthenticationError extends DriverError { - constructor(message: string); + constructor(message: string); } class DriverInternalError extends DriverError { - constructor(message: string); + constructor(message: string); } class NoHostAvailableError extends DriverError { - constructor(innerErrors: any, message?: string); + constructor(innerErrors: any, message?: string); } class NotSupportedError extends DriverError { - constructor(message: string); + constructor(message: string); } class OperationTimedOutError extends DriverError {} class ResponseError extends DriverError { - constructor(code: number, message: string); + constructor(code: number, message: string); } } @@ -688,7 +688,7 @@ declare module "cassandra-driver" { interface IndexStatic { new (name: string, target: string, kind: IndexType, options: Object): Index; - + fromRows(indexRows: Array): Array; fromColumnRows(columnRows: Array, columnsByName: { [key:string]: ColumnInfo }): Array; } @@ -758,4 +758,4 @@ declare module "cassandra-driver" { replicateOnWrite: boolean; } } -} \ No newline at end of file +} diff --git a/chai-dom/chai-dom.d.ts b/chai-dom/chai-dom.d.ts index 397bc17cb4..64cf97f516 100644 --- a/chai-dom/chai-dom.d.ts +++ b/chai-dom/chai-dom.d.ts @@ -24,6 +24,14 @@ declare namespace Chai { value(text: string): Assertion; } + + interface Include { + + text(text: string|string[]): Assertion; + + html(text: string|string[]): Assertion; + + } } 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/diff/diff-tests.ts b/diff/diff-tests.ts index 46d367bf68..20d75b38ea 100644 --- a/diff/diff-tests.ts +++ b/diff/diff-tests.ts @@ -49,5 +49,44 @@ function printDiff(diff:jsdiff.IDiffResult[]) { console.log(addLineHeader(" ", part.value)); } }); +} -} \ No newline at end of file +function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { + var verifyPatch = jsdiff.parsePatch( + jsdiff.createTwoFilesPatch("oldFile.ts", "newFile.ts", oldStr, newStr, + "old", "new", { context: 1 })); + if (JSON.stringify(verifyPatch) !== JSON.stringify(uniDiff)) { + console.error("Patch did not match uniDiff"); + } +} + +function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { + var verifyApply = [ + jsdiff.applyPatch(oldStr, uniDiff), + jsdiff.applyPatch(oldStr, [uniDiff]) + ]; + jsdiff.applyPatches([uniDiff], { + loadFile: (index: number, callback: (err: Error, data: string) => void) => { + callback(undefined, one); + }, + patched: (index: number, content: string) => { + verifyApply.push(content); + }, + complete: (err?: Error) => { + if (err) { + console.error(err); + } + + verifyApply.forEach(result => { + if (result !== newStr) { + console.error("Result did not match newStr"); + } + }); + } + }); +} + +verifyPatchMethods(one, other, uniDiff); +var uniDiff = jsdiff.structuredPatch("oldFile.ts", "newFile.ts", one, other, + "old", "new", { context: 1 }); +verifyApplyMethods(one, other, uniDiff); diff --git a/diff/diff.d.ts b/diff/diff.d.ts index b1f947300b..fc4708c2a1 100644 --- a/diff/diff.d.ts +++ b/diff/diff.d.ts @@ -16,6 +16,22 @@ declare namespace JsDiff { componenets: IDiffResult[]; } + interface IHunk { + oldStart: number; + oldLines: number; + newStart: number; + newLines: number; + lines: string[]; + } + + interface IUniDiff { + oldFileName: string; + newFileName: string; + oldHeader: string; + newHeader: string; + hunks: IHunk[]; + } + class Diff { ignoreWhitespace:boolean; @@ -46,9 +62,21 @@ declare namespace JsDiff { function diffCss(oldStr:string, newStr:string):IDiffResult[]; - function createPatch(fileName:string, oldStr:string, newStr:string, oldHeader:string, newHeader:string):string; + function createPatch(fileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; - function applyPatch(oldStr:string, uniDiff:string):string; + function createTwoFilesPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; + + function structuredPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): IUniDiff; + + function applyPatch(oldStr: string, uniDiff: string | IUniDiff | IUniDiff[]): string; + + function applyPatches(uniDiff: IUniDiff[], options: { + loadFile: (index: number, callback: (err: Error, data: string) => void) => void, + patched: (index: number, content: string) => void, + complete: (err?: Error) => void + }): void; + + function parsePatch(diffStr: string, options?: {strict: boolean}): IUniDiff[]; function convertChangesToXML(changes:IDiffResult[]):string; 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/express-serve-static-core/express-serve-static-core.d.ts b/express-serve-static-core/express-serve-static-core.d.ts index e092d2ecef..de91c521cc 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -192,9 +192,10 @@ declare module "express-serve-static-core" { * req.accepts('html, json'); * // => "json" */ - accepts(type: string): string; - - accepts(type: string[]): string; + accepts(): string[]; + accepts(type: string): string | boolean; + accepts(type: string[]): string | boolean; + accepts(...type: string[]): string | boolean; /** * Returns the first accepted charset of the specified character sets, @@ -204,7 +205,10 @@ declare module "express-serve-static-core" { * For more information, or if you have issues or concerns, see accepts. * @param charset */ - acceptsCharsets(charset?: string | string[]): string[]; + acceptsCharsets(): string[]; + acceptsCharsets(charset: string): string | boolean; + acceptsCharsets(charset: string[]): string | boolean; + acceptsCharsets(...charset: string[]): string | boolean; /** * Returns the first accepted encoding of the specified encodings, @@ -214,7 +218,10 @@ declare module "express-serve-static-core" { * For more information, or if you have issues or concerns, see accepts. * @param encoding */ - acceptsEncodings(encoding?: string | string[]): string[]; + acceptsEncodings(): string[]; + acceptsEncodings(encoding: string): string | boolean; + acceptsEncodings(encoding: string[]): string | boolean; + acceptsEncodings(...encoding: string[]): string | boolean; /** * Returns the first accepted language of the specified languages, @@ -225,7 +232,10 @@ declare module "express-serve-static-core" { * * @param lang */ - acceptsLanguages(lang?: string | string[]): string[]; + acceptsLanguages(): string[]; + acceptsLanguages(lang: string): string | boolean; + acceptsLanguages(lang: string[]): string | boolean; + acceptsLanguages(...lang: string[]): string | boolean; /** * Parse Range header field, diff --git a/express/express-tests.ts b/express/express-tests.ts index 11f8fd44fd..ed9265b66a 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -50,6 +50,26 @@ router.delete(pathRE); router.use((req, res, next) => { next(); }) router.route('/users') .get((req, res, next) => { + let types: string[] = req.accepts(); + let type: string | boolean = req.accepts('json'); + type = req.accepts(['json', 'text']); + type = req.accepts('json', 'text'); + + let charsets: string[] = req.acceptsCharsets(); + let charset: string | boolean = req.acceptsCharsets('utf-8'); + charset = req.acceptsCharsets(['utf-8', 'utf-16']); + charset = req.acceptsCharsets('utf-8', 'utf-16'); + + let encodings: string[] = req.acceptsEncodings(); + let encoding: string | boolean = req.acceptsEncodings('gzip'); + encoding = req.acceptsEncodings(['gzip', 'deflate']); + encoding = req.acceptsEncodings('gzip', 'deflate'); + + let languages: string[] = req.acceptsLanguages(); + let language: string | boolean = req.acceptsLanguages('en'); + language = req.acceptsLanguages(['en', 'ja']); + language = req.acceptsLanguages('en', 'ja'); + res.send(req.query['token']); }); 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/get-port/get-port-tests.ts b/get-port/get-port-tests.ts new file mode 100644 index 0000000000..d414742230 --- /dev/null +++ b/get-port/get-port-tests.ts @@ -0,0 +1,7 @@ +/// + +import * as getPort from "get-port"; + +getPort().then(port => { + console.log(port); +}); diff --git a/get-port/get-port.d.ts b/get-port/get-port.d.ts new file mode 100644 index 0000000000..673c547f1c --- /dev/null +++ b/get-port/get-port.d.ts @@ -0,0 +1,9 @@ +// Type definitions for ajv +// Project: https://github.com/sindresorhus/get-port +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "get-port" { + var getPort: () => PromiseLike + export = getPort; +} diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index c8d0c8df7c..bebf0b99c8 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()); }); }); @@ -577,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) + }); + } + } } ] }, @@ -827,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 @@ -860,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()); @@ -946,3 +985,15 @@ app.on('ready', function () { console.log(webContents.getAllWebContents()); console.log(webContents.getFocusedWebContents()); + +var win = new BrowserWindow({ + webPreferences: { + offscreen: true + } +}); + +win.webContents.on('paint', (event, dirty, image) => { + console.log(dirty, image.getBitmap()); +}); + +win.loadURL('http://github.com'); diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index ce01bb23d5..7b246966ab 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.3.1 +// Type definitions for Electron v1.3.3 // 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 /** @@ -282,13 +299,13 @@ declare namespace Electron { * Note: This is only implemented on macOS and Windows. * On macOS, you can only register protocols that have been added to your app's info.plist. */ - setAsDefaultProtocolClient(protocol: string): void; + setAsDefaultProtocolClient(protocol: string): boolean; /** * Removes the current executable as the default handler for a protocol (aka URI scheme). * * Note: This is only implemented on macOS and Windows. */ - removeAsDefaultProtocolClient(protocol: string): void; + removeAsDefaultProtocolClient(protocol: string): boolean; /** * @returns Whether the current executable is the default handler for a protocol (aka URI scheme). * @@ -300,7 +317,7 @@ declare namespace Electron { * * Note: This API is only available on Windows. */ - setUserTasks(tasks: Task[]): void; + setUserTasks(tasks: Task[]): boolean; /** * This method makes your application a Single Instance Application instead of allowing * multiple instances of your app to run, this will ensure that only a single instance @@ -332,6 +349,8 @@ declare namespace Electron { getCurrentActivityType(): string; /** * Changes the Application User Model ID to id. + * + * Note: This is only implemented on Windows. */ setAppUserModelId(id: string): void; /** @@ -473,6 +492,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. * @@ -783,6 +809,10 @@ declare namespace Electron { * @returns Whether the window is focused. */ isFocused(): boolean; + /** + * @returns Whether the window is destroyed. + */ + isDestroyed(): boolean; /** * Shows and gives focus to the window. */ @@ -844,7 +874,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. */ @@ -853,6 +883,14 @@ declare namespace Electron { * @returns The window's width, height, x and y values. */ getBounds(): Rectangle; + /** + * Resizes and moves the window's client area (e.g. the web page) to width, height, x, y. + */ + setContentBounds(options: Rectangle, animate?: boolean): void; + /** + * @returns The window's client area (e.g. the web page) width, height, x and y values. + */ + getContentBounds(): Rectangle; /** * Resizes the window to width and height. */ @@ -1077,7 +1115,13 @@ declare namespace Electron { * @param progress Valid range is [0, 1.0]. If < 0, the progress bar is removed. * If greater than 0, it becomes indeterminate. */ - setProgressBar(progress: number): void; + setProgressBar(progress: number, options?: { + /** + * Mode for the progress bar. + * Note: This is only implemented on Windows. + */ + mode: 'none' | 'normal' | 'indeterminate' | 'error' | 'paused' + }): void; /** * Sets a 16px overlay onto the current Taskbar icon, usually used to convey * some sort of application status or to passively notify the user. @@ -1112,7 +1156,12 @@ declare namespace Electron { * * Note: This API is available only on Windows. */ - setThumbnailClip(region: Bounds): void; + setThumbnailClip(region: Rectangle): boolean; + /** + * Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. + * Note: This API is available only on Windows. + */ + setThumbnailToolTip(toolTip: string): boolean; /** * Same as webContents.showDefinitionForSelection(). * Note: This API is available only on macOS. @@ -1355,12 +1404,17 @@ declare namespace Electron { defaultEncoding?: string; /** * Whether to throttle animations and timers when the page becomes background. - * Default: true + * Default: true. */ backgroundThrottling?: boolean; + /** + * Whether to enable offscreen rendering for the browser window. + * Default: false. + */ + offscreen?: boolean; } - interface BrowserWindowOptions extends Rectangle { + interface BrowserWindowOptions { /** * Window’s width in pixels. * Default: 800. @@ -1570,13 +1624,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 +1900,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 +2086,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. */ @@ -2244,8 +2296,8 @@ declare namespace Electron { } type MenuItemType = 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio'; - type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close' | 'quit' | 'togglefullscreen'; - type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'front' | 'zoom' | 'window' | 'help' | 'services'; + type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close' | 'quit' | 'togglefullscreen' | 'resetzoom' | 'zoomin' | 'zoomout'; + type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'startspeaking' | 'stopspeaking' | 'front' | 'zoom' | 'window' | 'help' | 'services'; interface MenuItemOptions { /** @@ -2428,13 +2480,25 @@ 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 a copy of the image's raw bitmap pixel data. + */ + toBitmap(): Buffer; + /** + * @returns Buffer that contains the image's raw bitmap pixel data. + * + * The difference between getBitmap() and toBitmap() is, getBitmap() does not copy the bitmap data, + * so you have to use the returned Buffer immediately in current event loop tick, + * otherwise the data might be changed or destroyed. + */ + getBitmap(): Buffer; /** * @returns string The data URL of the image. */ @@ -2452,7 +2516,7 @@ declare namespace Electron { /** * @returns {} The size of the image. */ - getSize(): Dimension; + getSize(): Size; /** * Marks the image as template image. */ @@ -2675,10 +2739,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 +2754,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 +2793,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 @@ -3257,6 +3304,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 @@ -3271,6 +3374,26 @@ declare namespace Electron { * Note: This is only implemented on macOS. */ isDarkMode(): boolean; + /** + * @returns If the Swipe between pages setting is on. + * + * Note: This is only implemented on macOS. + */ + isSwipeTrackingFromScrollEventsEnabled(): boolean; + /** + * Posts event as native notifications of macOS. + * The userInfo contains the user information dictionary sent along with the notification. + * + * Note: This is only implemented on macOS. + */ + postNotification(event: string, userInfo: Object): void; + /** + * Posts event as native notifications of macOS. + * The userInfo contains the user information dictionary sent along with the notification. + * + * Note: This is only implemented on macOS. + */ + postLocalNotification(event: string, userInfo: Object): void; /** * Subscribes to native notifications of macOS, callback will be called when the corresponding event happens. * The id of the subscriber is returned, which can be used to unsubscribe the event. @@ -3318,17 +3441,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. @@ -3428,7 +3551,7 @@ declare namespace Electron { /** * @returns The bounds of this tray icon. */ - getBounds(): Bounds; + getBounds(): Rectangle; } interface Modifiers { @@ -3641,9 +3764,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. */ @@ -3657,9 +3780,9 @@ declare namespace Electron { */ on(event: 'select-bluetooth-device', listener: (event: Event, deviceList: BluetoothDevice[], callback: (deviceId: string) => void) => void): this; /** - * Emitted when a page's view is repainted. + * Emitted when a new frame is generated. Only the dirty area is passed in the buffer. */ - on(event: 'view-painted', listener: Function): this; + on(event: 'paint', listener: (event: Event, dirtyRect: Rectangle, image: NativeImage) => void): this; on(event: string, listener: Function): this; /** * Loads the url in the window. @@ -3769,6 +3892,29 @@ declare namespace Electron { * @returns Whether this page has been muted. */ isAudioMuted(): boolean; + /** + * 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. */ @@ -3935,6 +4081,31 @@ declare namespace Electron { * Note: This API is available only on macOS. */ showDefinitionForSelection(): void; + /** + * @returns Whether offscreen rendering is enabled. + */ + isOffscreen(): boolean; + /** + * If offscreen rendering is enabled and not painting, start painting. + */ + startPainting(): void; + /** + * If offscreen rendering is enabled and painting, stop painting. + */ + stopPainting(): void; + /** + * If offscreen rendering is enabled returns whether it is currently painting. + */ + isPainting(): boolean; + /** + * If offscreen rendering is enabled sets the frame rate to the specified number. + * Only values between 1 and 60 are accepted. + */ + setFrameRate(fps: number): void; + /** + * If offscreen rendering is enabled returns the current frame rate. + */ + getFrameRate(): number; /** * Sets the item as dragging item for current drag-drop operation. */ @@ -3985,7 +4156,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 } @@ -4189,7 +4360,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. @@ -4294,7 +4465,7 @@ declare namespace Electron { /** * Coordinates of first match region. */ - selectionArea?: Bounds; + selectionArea?: Rectangle; } interface DeviceEmulationParameters { @@ -4306,7 +4477,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} @@ -4320,7 +4491,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 @@ -4591,6 +4762,10 @@ declare namespace Electron { * @returns The title of guest page. */ getTitle(): string; + /** + * @returns Whether the web page is destroyed. + */ + isDestroyed(): boolean; /** * @returns Whether guest page is still loading resources. */ 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/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/graphene-pk11/graphene-pk11.d.ts b/graphene-pk11/graphene-pk11.d.ts index 5c0c5c5142..ce3d162f17 100644 --- a/graphene-pk11/graphene-pk11.d.ts +++ b/graphene-pk11/graphene-pk11.d.ts @@ -1,1230 +1,276 @@ -// Type definitions for graphene-pk11 v2.0.0 +// Type definitions for graphene-pk11 v2.0.2 // Project: https://github.com/PeculiarVentures/graphene // Definitions by: Stepan Miroshin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// /** * A simple layer for interacting with PKCS #11 / PKCS11 / CryptoKI for Node - * v2.0.0 + * v2.0.2 */ -declare module "graphene-pk11" { - type Callback = (err: Error, rv: number) => void; - type CK_PTR = Buffer; +declare module "types/graphene-pk11" { + import * as graphene from "graphene-pk11"; + import * as pkcs11 from "pkcs11js"; - class Pkcs11 { - lib: any; - /** - * load a library with PKCS11 interface - * @param {string} libFile path to PKCS11 library - */ - constructor(libFile: string); - protected callFunction(funcName: string, args: any[]): number; - /** - * C_Initialize initializes the Cryptoki library. - * @param pInitArgs if this is not NULL_PTR, it gets - * cast to CK_C_INITIALIZE_ARGS_PTR - * and dereferenced - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Initialize(pInitArgs?: CK_PTR): number; - C_Initialize(pInitArgs: CK_PTR, cllback: Callback): void; - /** - * C_Finalize indicates that an application is done with the Cryptoki library. - * @param pReserved reserved. Should be NULL_PTR - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Finalize(pReserved?: CK_PTR): number; - C_Finalize(pReserved: CK_PTR, callback: Callback): void; - /** - * C_GetInfo returns general information about Cryptoki. - * @param pInfo location that receives information - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetInfo(pInfo: CK_PTR): number; - C_GetInfo(pInfo: CK_PTR, callback: Callback): void; - /** - * C_GetSlotList obtains a list of slots in the system. - * @param {boolean} tokenPresent only slots with tokens? - * @param pSlotList receives array of slot IDs - * @param pulCount receives number of slots - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetSlotList(tokenPresent: boolean, pSlotList: CK_PTR, pulCount: CK_PTR): number; - C_GetSlotList(tokenPresent: boolean, pSlotList: CK_PTR, pulCount: CK_PTR, callback: Callback): void; - /** - * C_GetSlotInfo obtains information about a particular slot in - * the system. - * @param {number} slotID the ID of the slot - * @param {Buffer} pInfo receives the slot information - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetSlotInfo(slotID: number, pInfo: CK_PTR): number; - C_GetSlotInfo(slotID: number, pInfo: CK_PTR, callback: Callback): void; - /** - * C_GetTokenInfo obtains information about a particular token - * in the system. - * @param {number} slotID ID of the token's slot - * @param {Buffer} pInfo receives the token information - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetTokenInfo(slotID: number, pInfo: Buffer): number; - C_GetTokenInfo(slotID: number, pInfo: Buffer, callback: Callback): void; - /** - * C_GetMechanismList obtains a list of mechanism types - * supported by a token. - * @param {number} slotID ID of the token's slot - * @param {number} pMechanismList gets mech. array - * @param {number} pulCount gets # of mechs - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetMechanismList(slotID: number, pMechanismList: Buffer, pulCount: Buffer): number; - C_GetMechanismList(slotID: number, pMechanismList: Buffer, pulCount: Buffer, callback: Callback): void; - /** C_GetMechanismInfo obtains information about a particular - * mechanism possibly supported by a token. - * @param {number} slotID ID of the token's slot - * @param {number} type type of mechanism - * @param {Buffer} pInfo receives mechanism info - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetMechanismInfo(slotID: number, type: number, pInfo: Buffer): number; - C_GetMechanismInfo(slotID: number, type: number, pInfo: Buffer, callback: Callback): void; - /** - * C_InitToken initializes a token. - * @param {number} slotID ID of the token's slot - * @param {Buffer} pPin the SO's initial PIN - * @param {number} ulPinLen length in bytes of the PIN - * @param {number} pLabel 32-byte token label (blank padded) - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_InitToken(slotID: number, pPin: Buffer, ulPinLen: number, pLabel: Buffer): number; - C_InitToken(slotID: number, pPin: Buffer, ulPinLen: number, pLabel: Buffer, callback: Callback): void; - /** - * C_InitPIN initializes the normal user's PIN. - * @param {number} hSession the session's handle - * @param {Buffer} pPin the normal user's PIN - * @param {number} ulPinLen length in bytes of the PIN - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_InitPIN(hSession: number, pPin: Buffer, ulPinLen: number): number; - C_InitPIN(hSession: number, pPin: Buffer, ulPinLen: number, callback: Callback): void; - /** - * C_SetPIN modifies the PIN of the user who is logged in. - * @param {number} hSession the session's handle - * @param {Buffer} pOldPin the old PIN - * @param {number} ulOldLen length of the old PIN - * @param {Buffer} pNewPin the new PIN - * @param {number} ulNewLen length of the new PIN - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SetPIN(hSession: any, pOldPin: Buffer, ulOldLen: number, pNewPin: Buffer, ulNewLen: number): number; - C_SetPIN(hSession: any, pOldPin: Buffer, ulOldLen: number, pNewPin: Buffer, ulNewLen: number, callback: Callback): void; - /** - * C_OpenSession opens a session between an application and a - * token. - * @param {number} slotID ID of the token's slot - * @param {number} flags from CK_SESSION_INFO - * @param {Buffer} pApplication passed to callback - * @param {Buffer} Notify callback function - * @param {Buffer} phSession gets session handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_OpenSession(slotID: number, flags: number, pApplication?: Buffer, notify?: Buffer, phSession?: Buffer): number; - C_OpenSession(slotID: number, flags: number, pApplication: Buffer, notify: Buffer, phSession: Buffer, callback: Callback): void; - /** - * C_CloseSession closes a session between an application and a token. - * @param {number} hSession the session's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_CloseSession(hSession: number): number; - C_CloseSession(hSession: number, callback: Callback): void; - /** - * C_CloseAllSessions closes all sessions with a token. - * @param {number} slotID ID of the token's slot - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_CloseAllSessions(slotID: number): number; - C_CloseAllSessions(slotID: number, callback: Callback): void; - /** - * C_GetSessionInfo obtains information about the session. - * @param {number} hSession the session's handle - * @param {Buffer} pInfo receives session info - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetSessionInfo(hSession: number, pInfo: Buffer): number; - C_GetSessionInfo(hSession: number, pInfo: Buffer, callback: Callback): void; - /** - * C_GetOperationState obtains the state of the cryptographic operation in a session. - * @param {number} hSession the session's handle - * @param {Buffer} pOperationState gets state - * @param {Buffer} pulOperationStateLen gets state length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetOperationState(hSession: number, pOperationState: Buffer, pulOperationStateLen: Buffer): number; - C_GetOperationState(hSession: number, pOperationState: Buffer, pulOperationStateLen: Buffer, callback: Callback): void; - /** - * C_SetOperationState restores the state of the cryptographic operation in a session. - * @param {number} hSession the session's handle - * @param {Buffer} pOperationState holds state - * @param {number} ulOperationStateLen holds holds state length - * @param {number} hEncryptionKey en/decryption key - * @param {number} hAuthenticationKey sign/verify key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SetOperationState(hSession: number, pOperationState: Buffer, ulOperationStateLen: number, hEncryptionKey: number, hAuthenticationKey: number): number; - C_SetOperationState(hSession: number, pOperationState: Buffer, ulOperationStateLen: number, hEncryptionKey: number, hAuthenticationKey: number, callback: Callback): void; - /** - * C_Login logs a user into a token. - * @param {number} hSession the session's handle - * @param {number} userType the user type - * @param {Buffer} pPin the user's PIN - * @param {number} ulPinLen the length of the PIN - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Login(hSession: number, userType: number, pPin: Buffer, ulPinLen: number): number; - C_Login(hSession: number, userType: number, pPin: Buffer, ulPinLen: number, callback: Callback): void; - /** - * C_Logout logs a user out from a token. - * @param {number} hSession the session's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Logout(hSession: number): number; - C_Logout(hSession: number, callback: Callback): void; - /** - * C_CreateObject creates a new object. - * @param {number} hSession the session's handle - * @param {Buffer} pTemplate the object's template - * @param {number} ulCount attributes in template - * @param {Buffer} phObject gets new object's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_CreateObject(hSession: number, pTemplate: Buffer, ulCount: number, phObject: Buffer): number; - C_CreateObject(hSession: number, pTemplate: Buffer, ulCount: number, phObject: Buffer, callback: Callback): void; - /** - * C_CopyObject copies an object, creating a new object for the copy. - * @param {number} hSession the session's handle - * @param {number} hObject the object's handle - * @param {Buffer} pTemplate template for new object - * @param {number} ulCount attributes in template - * @param {Buffer} phNewObject receives handle of copy - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_CopyObject(hSession: number, hObject: number, pTemplate: Buffer, ulCount: number, phNewObject: Buffer): number; - C_CopyObject(hSession: number, hObject: number, pTemplate: Buffer, ulCount: number, phNewObject: Buffer, callback: Callback): void; - /** - * C_DestroyObject destroys an object. - * @param {number} hSession the session's handle - * @param {number} hObject the object's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DestroyObject(hSession: number, hObject: number): number; - C_DestroyObject(hSession: number, hObject: number, callback: Callback): void; - /** - * C_GetObjectSize gets the size of an object in bytes. - * @param {number} hSession the session's handle - * @param {number} hObject the object's handle - * @param {Buffer} pulSize receives size of object - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetObjectSize(hSession: number, hObject: number, pulSize: Buffer): number; - C_GetObjectSize(hSession: number, hObject: number, pulSize: Buffer, callback: Callback): void; - /** - * C_GetAttributeValue obtains the value of one or more object attributes. - * @param {number} hSession the session's handle - * @param {number} hObject the object's handle - * @param {Buffer} pTemplate specifies attrs; gets vals - * @param {number} ulCount attributes in template - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetAttributeValue(hSession: number, hObject: number, pTemplate: Buffer, ulCount: number): number; - C_GetAttributeValue(hSession: number, hObject: number, pTemplate: Buffer, ulCount: number, callback: Callback): void; - /** - * C_SetAttributeValue modifies the value of one or more object attributes - * @param {number} hSession the session's handle - * @param {number} hObject the object's handle - * @param {Buffer} pTemplate specifies attrs and values - * @param {number} ulCount attributes in template - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SetAttributeValue(hSession: number, hObject: number, pTemplate: Buffer, ulCount: number): number; - C_SetAttributeValue(hSession: number, hObject: number, pTemplate: Buffer, ulCount: number, callback: Callback): void; - /** - * C_FindObjectsInit initializes a search for token and session - * objects that match a template. - * @param {number} hSession the session's handle - * @param {Buffer} pTemplate attribute values to match - * @param {number} ulCount attrs in search template - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_FindObjectsInit(hSession: number, pTemplate: Buffer, ulCount: number): number; - C_FindObjectsInit(hSession: number, pTemplate: Buffer, ulCount: number, callback: Callback): void; - /** - * C_FindObjects continues a search for token and session - * objects that match a template, obtaining additional object - * handles. - * @param {number} hSession the session's handle - * @param {Buffer} phObject gets obj. handles - * @param {number} ulMaxObjectCount max handles to get - * @param {Buffer} pulObjectCount actual # returned - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_FindObjects(hSession: number, phObject: Buffer, ulMaxObjectCount: number, pulObjectCount: Buffer): number; - C_FindObjects(hSession: number, phObject: Buffer, ulMaxObjectCount: number, pulObjectCount: Buffer, callback: Callback): void; - /** - * C_FindObjectsFinal finishes a search for token and session objects. - * @param {number} hSession the session's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_FindObjectsFinal(hSession: number): number; - C_FindObjectsFinal(hSession: number, callback: Callback): void; - /** - * C_EncryptInit initializes an encryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the encryption mechanism - * @param {number} hKey handle of encryption key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_EncryptInit(hSession: number, pMechanism: Buffer, hKey: number): number; - C_EncryptInit(hSession: number, pMechanism: Buffer, hKey: number, callback: Callback): void; - /** - * C_Encrypt encrypts single-part data. - * @param {number} hSession the session's handle - * @param {Buffer} pData the plaintext data - * @param {number} ulDataLen bytes of plaintext - * @param {Buffer} pEncryptedData gets ciphertext - * @param {Buffer} pulEncryptedDataLen gets c-text size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Encrypt(hSession: number, pData: Buffer, ulDataLen: number, pEncryptedData: Buffer, pulEncryptedDataLen: Buffer): number; - C_Encrypt(hSession: number, pData: Buffer, ulDataLen: number, pEncryptedData: Buffer, pulEncryptedDataLen: Buffer, callback: Callback): void; - /** - * C_EncryptUpdate continues a multiple-part encryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pPart the plaintext data - * @param {number} ulPartLen plaintext data len - * @param {Buffer} pEncryptedPart gets ciphertext - * @param {Buffer} pulEncryptedPartLen gets c-text size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_EncryptUpdate(hSession: number, pPart: Buffer, ulPartLen: number, pEncryptedPart: Buffer, pulEncryptedPartLen: Buffer): number; - C_EncryptUpdate(hSession: number, pPart: Buffer, ulPartLen: number, pEncryptedPart: Buffer, pulEncryptedPartLen: Buffer, callback: Callback): void; - /** - * C_EncryptFinal finishes a multiple-part encryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pLastEncryptedPart last c-text - * @param {Buffer} pulLastEncryptedPartLen gets last size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_EncryptFinal(hSession: number, pLastEncryptedPart: Buffer, pulLastEncryptedPartLen: Buffer): number; - C_EncryptFinal(hSession: number, pLastEncryptedPart: Buffer, pulLastEncryptedPartLen: Buffer, callback: Callback): void; - /** - * C_DecryptInit initializes a decryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the decryption mechanism - * @param {number} hKey handle of decryption key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DecryptInit(hSession: number, pMechanism: Buffer, hKey: number): any; - C_DecryptInit(hSession: number, pMechanism: Buffer, hKey: number, callback: Callback): void; - /** - * C_Decrypt decrypts encrypted data in a single part. - * @param {number} hSession the session's handle - * @param {Buffer} pEncryptedData ciphertext - * @param {number} ulEncryptedDataLen ciphertext length - * @param {Buffer} pData gets plaintext - * @param {number} pulDataLen gets p-text size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Decrypt(hSession: number, pEncryptedData: Buffer, ulEncryptedDataLen: number, pData: Buffer, pulDataLen: Buffer): number; - C_Decrypt(hSession: number, pEncryptedData: Buffer, ulEncryptedDataLen: number, pData: Buffer, pulDataLen: Buffer, callback: Callback): void; - /** - * C_DecryptUpdate continues a multiple-part decryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pEncryptedPart encrypted data - * @param {number} ulEncryptedPartLen input length - * @param {Buffer} pPart gets plaintext - * @param {Buffer} pulPartLen p-text size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DecryptUpdate(hSession: number, pEncryptedPart: Buffer, ulEncryptedPartLen: number, pPart: Buffer, pulPartLen: Buffer): number; - C_DecryptUpdate(hSession: number, pEncryptedPart: Buffer, ulEncryptedPartLen: number, pPart: Buffer, pulPartLen: Buffer, callback: Callback): void; - /** - * C_DecryptFinal finishes a multiple-part decryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pLastPart gets plaintext - * @param {Buffer} pulLastPartLen p-text size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DecryptFinal(hSession: number, pLastPart: Buffer, pulLastPartLen: Buffer): number; - C_DecryptFinal(hSession: number, pLastPart: Buffer, pulLastPartLen: Buffer, callback: Callback): void; - /** - * C_DigestInit initializes a message-digesting operation. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the digesting mechanism - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DigestInit(hSession: number, pMechanism: Buffer): number; - C_DigestInit(hSession: number, pMechanism: Buffer, callback: Callback): void; - /** - * C_Digest digests data in a single part. - * @param {number} hSession the session's handle - * @param {Buffer} pData data to be digested - * @param {number} ulDataLen bytes of data to digest - * @param {Buffer} pDigest gets the message digest - * @param {Buffer} pulDigestLen gets digest length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Digest(hSession: number, pData: Buffer, ulDataLen: number, pDigest: Buffer, pulDigestLen: Buffer): number; - C_Digest(hSession: number, pData: Buffer, ulDataLen: number, pDigest: Buffer, pulDigestLen: Buffer, callback: Callback): void; - /** - * C_DigestUpdate continues a multiple-part message-digesting operation. - * @param {number} hSession the session's handle - * @param {Buffer} pPart data to be digested - * @param {number} ulPartLen bytes of data to be digested - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DigestUpdate(hSession: number, pPart: Buffer, ulPartLen: number): number; - C_DigestUpdate(hSession: number, pPart: Buffer, ulPartLen: number, callback: Callback): void; - /** - * C_DigestKey continues a multi-part message-digesting operation, - * by digesting the value of a secret key as part of - * the data already digested. - * @param {number} hSession the session's handle - * @param {number} hKey secret key to digest - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DigestKey(hSession: number, hKey: number): number; - C_DigestKey(hSession: number, hKey: number, callback: Callback): void; - /** - * C_DigestFinal finishes a multiple-part message-digesting - * operation. - * @param {number} hSession the session's handle - * @param {Buffer} pDigest gets the message digest - * @param {Buffer} pulDigestLen gets byte count of digest - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DigestFinal(hSession: number, pDigest: Buffer, pulDigestLen: Buffer): number; - C_DigestFinal(hSession: number, pDigest: Buffer, pulDigestLen: Buffer, callback: Callback): void; - /** - * C_SignInit 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 {number} hSession the session's handle - * @param {Buffer} pMechanism the signature mechanism - * @param {number} hKey handle of signature key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SignInit(hSession: number, pMechanism: Buffer, hKey: number): number; - C_SignInit(hSession: number, pMechanism: Buffer, hKey: number, callback: Callback): void; - /** - * C_Sign 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 {number} hSession the session's handle - * @param {Buffer} pData the data to sign - * @param {number} ulDataLen count of bytes to sign - * @param {Buffer} pSignature gets the signature - * @param {Buffer} pulSignatureLen gets signature length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Sign(hSession: number, pData: Buffer, ulDataLen: number, pSignature: Buffer, pulSignatureLen: Buffer): number; - C_Sign(hSession: number, pData: Buffer, ulDataLen: number, pSignature: Buffer, pulSignatureLen: Buffer, callback: Callback): void; - /** - * C_SignUpdate 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 {number} hSession the session's handle - * @param {Buffer} pPart the data to sign - * @param {number} ulPartLen count of bytes to sign - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SignUpdate(hSession: number, pPart: Buffer, ulPartLen: Buffer): number; - C_SignUpdate(hSession: number, pPart: Buffer, ulPartLen: Buffer, callback: Callback): void; - /** - * C_SignFinal finishes a multiple-part signature operation, - * returning the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pSignature gets the signature - * @param {Buffer} pulSignatureLen gets signature length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SignFinal(hSession: number, pSignature: Buffer, pulSignatureLen: Buffer): number; - C_SignFinal(hSession: number, pSignature: Buffer, pulSignatureLen: Buffer, callback: Callback): void; - /** - * C_SignRecoverInit initializes a signature operation, where - * the data can be recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the signature mechanism - * @param {number} hKey handle of the signature key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SignRecoverInit(hSession: number, pMechanism: Buffer, hKey: number): number; - C_SignRecoverInit(hSession: number, pMechanism: Buffer, hKey: number, callback: Callback): void; - /** - * C_SignRecover signs data in a single operation, where the - * data can be recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pData the data to sign - * @param {number} ulDataLen count of bytes to sign - * @param {Buffer} pSignature gets the signature - * @param {Buffer} pulSignatureLen gets signature length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SignRecover(hSession: number, pData: Buffer, ulDataLen: number, pSignature: Buffer, pulSignatureLen: Buffer): number; - C_SignRecover(hSession: number, pData: Buffer, ulDataLen: number, pSignature: Buffer, pulSignatureLen: Buffer, callback: Callback): void; - /** - * C_VerifyInit 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 {number} hSession the session's handle - * @param {Buffer} pMechanism the verification mechanism - * @param {number} hKey verification key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_VerifyInit(hSession: number, pMechanism: Buffer, hKey: number): number; - C_VerifyInit(hSession: number, pMechanism: Buffer, hKey: number, callback: Callback): void; - /** - * C_Verify 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 {number} hSession the session's handle - * @param {Buffer} pData signed data - * @param {number} ulDataLen length of signed data - * @param {Buffer} pSignature signature - * @param {number} ulSignatureLen signature length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Verify(hSession: number, pData: Buffer, ulDataLen: number, pSignature: Buffer, ulSignatureLen: Buffer): number; - C_Verify(hSession: number, pData: Buffer, ulDataLen: number, pSignature: Buffer, ulSignatureLen: Buffer, callback: Callback): void; - /** - * C_VerifyUpdate continues a multiple-part verification - * operation, where the signature is an appendix to the data, - * and plaintext cannot be recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pPart signed data - * @param {number} ulPartLen length of signed data - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_VerifyUpdate(hSession: number, pPart: Buffer, ulPartLen: number): number; - C_VerifyUpdate(hSession: number, pPart: Buffer, ulPartLen: number, callback: Callback): void; - /** - * C_VerifyFinal finishes a multiple-part verification - * operation, checking the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pSignature signature to verify - * @param {number} ulSignatureLen signature length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_VerifyFinal(hSession: number, pSignature: Buffer, ulSignatureLen: number): number; - C_VerifyFinal(hSession: number, pSignature: Buffer, ulSignatureLen: number, callback: Callback): void; - /** - * C_VerifyRecoverInit initializes a signature verification - * operation, where the data is recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the verification mechanism - * @param {number} hKey verification key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_VerifyRecoverInit(hSession: number, pMechanism: Buffer, hKey: number): number; - C_VerifyRecoverInit(hSession: number, pMechanism: Buffer, hKey: number, callback: Callback): void; - /** - * C_VerifyRecover verifies a signature in a single-part - * operation, where the data is recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pSignature signature to verify - * @param {number} ulSignatureLen signature length - * @param {Buffer} pData gets signed data - * @param {Buffer} pulDataLen gets signed data len - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_VerifyRecover(hSession: number, pSignature: Buffer, ulSignatureLen: number, pData: Buffer, pulDataLen: Buffer): number; - C_VerifyRecover(hSession: number, pSignature: Buffer, ulSignatureLen: number, pData: Buffer, pulDataLen: Buffer, callback: Callback): void; - /** - * C_DigestEncryptUpdate continues a multiple-part digesting - * and encryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pPart the plaintext data - * @param {number} ulPartLen plaintext length - * @param {Buffer} pEncryptedPart gets ciphertext - * @param {Buffer} pulEncryptedPartLen gets c-text length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DigestEncryptUpdate(hSession: number, pPart: Buffer, ulPartLen: number, pEncryptedPart: Buffer, pulEncryptedPartLen: Buffer): number; - C_DigestEncryptUpdate(hSession: number, pPart: Buffer, ulPartLen: number, pEncryptedPart: Buffer, pulEncryptedPartLen: Buffer, callback: Callback): void; - /** - * C_DecryptDigestUpdate continues a multiple-part decryption and - * digesting operation. - * @param {number} hSession the session's handle - * @param {Buffer} pEncryptedPart ciphertext - * @param {number} ulEncryptedPartLen ciphertext length - * @param {Buffer} pPart gets plaintext - * @param {Buffer} pulPartLen gets plaintext len - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DecryptDigestUpdate(hSession: number, pEncryptedPart: Buffer, ulEncryptedPartLen: number, pPart: Buffer, pulPartLen: Buffer): number; - C_DecryptDigestUpdate(hSession: number, pEncryptedPart: Buffer, ulEncryptedPartLen: number, pPart: Buffer, pulPartLen: Buffer, callback: Callback): void; - /** - * C_SignEncryptUpdate continues a multiple-part signing and - * encryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pPart the plaintext data - * @param {number} ulPartLen plaintext length - * @param {Buffer} pEncryptedPart gets ciphertext - * @param {Buffer} pulEncryptedPartLen gets c-text length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SignEncryptUpdate(hSession: number, pPart: Buffer, ulPartLen: number, pEncryptedPart: Buffer, pulEncryptedPartLen: Buffer): number; - C_SignEncryptUpdate(hSession: number, pPart: Buffer, ulPartLen: number, pEncryptedPart: Buffer, pulEncryptedPartLen: Buffer, callback: Callback): void; - /** - * C_DecryptVerifyUpdate continues a multiple-part decryption and - * verify operation. - * @param {number} hSession the session's handle - * @param {Buffer} pEncryptedPart ciphertext - * @param {number} ulEncryptedPartLen ciphertext length - * @param {Buffer} pPart gets plaintext - * @param {Buffer} pulPartLen gets p-text length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DecryptVerifyUpdate(hSession: number, pEncryptedPart: Buffer, ulEncryptedPartLen: number, pPart: Buffer, pulPartLen: Buffer): number; - C_DecryptVerifyUpdate(hSession: number, pEncryptedPart: Buffer, ulEncryptedPartLen: number, pPart: Buffer, pulPartLen: Buffer, callback: Callback): void; - /** - * C_GenerateKey generates a secret key, creating a new key object. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism key generation mech. - * @param {Buffer} pTemplate template for new key - * @param {number} ulCount # of attrs in template - * @param {Buffer} phKey gets handle of new key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GenerateKey(hSession: number, pMechanism: Buffer, pTemplate: Buffer, ulCount: number, phKey: Buffer): number; - C_GenerateKey(hSession: number, pMechanism: Buffer, pTemplate: Buffer, ulCount: number, phKey: Buffer, callback: Callback): any; - /** - * C_GenerateKeyPair generates a public-key/private-key pair, - * creating new key objects. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism key-gen mech. - * @param {Buffer} pPublicKeyTemplate template for public key - * @param {number} ulPublicKeyAttributeCount public attrs - * @param {Buffer} pPrivateKeyTemplate template for private key - * @param {number} ulPrivateKeyAttributeCount private attrs - * @param {Buffer} phPublicKey gets public key handle - * @param {Buffer} phPrivateKey gets private key handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GenerateKeyPair(hSession: number, pMechanism: Buffer, pPublicKeyTemplate: Buffer, ulPublicKeyAttributeCount: number, pPrivateKeyTemplate: Buffer, ulPrivateKeyAttributeCount: number, phPublicKey: Buffer, phPrivateKey: Buffer): number; - C_GenerateKeyPair(hSession: number, pMechanism: Buffer, pPublicKeyTemplate: Buffer, ulPublicKeyAttributeCount: number, pPrivateKeyTemplate: Buffer, ulPrivateKeyAttributeCount: number, phPublicKey: Buffer, phPrivateKey: Buffer, callback: Callback): void; - /** - * C_WrapKey wraps (i.e., encrypts) a key. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the wrapping mechanism - * @param {number} hWrappingKey wrapping key - * @param {number} hKey key to be wrapped - * @param {Buffer} pWrappedKey gets wrapped key - * @param {Buffer} pulWrappedKeyLen gets wrapped key size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_WrapKey(hSession: number, pMechanism: Buffer, hWrappingKey: number, hKey: number, pWrappedKey: Buffer, pulWrappedKeyLen: Buffer): number; - C_WrapKey(hSession: number, pMechanism: Buffer, hWrappingKey: number, hKey: number, pWrappedKey: Buffer, pulWrappedKeyLen: Buffer, callback: Callback): void; - /** - * C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new - * key object. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism unwrapping mech. - * @param {Buffer} pWrappedKey the wrapped key - * @param {number} ulWrappedKeyLen wrapped key len - * @param {Buffer} pTemplate new key template - * @param {number} ulAttributeCount template length - * @param {Buffer} pTemplate new key template - * @param {number} ulAttributeCount template length - * @param {Buffer} phKey gets new handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_UnwrapKey(hSession: number, pMechanism: Buffer, hUnwrappingKey: number, pWrappedKey: Buffer, ulWrappedKeyLen: number, pTemplate: Buffer, ulAttributeCount: number, phKey: Buffer): number; - C_UnwrapKey(hSession: number, pMechanism: Buffer, hUnwrappingKey: number, pWrappedKey: Buffer, ulWrappedKeyLen: number, pTemplate: Buffer, ulAttributeCount: number, phKey: Buffer, callback: Callback): void; - /** - * C_DeriveKey derives a key from a base key, creating a new key object. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism key deriv. mech. - * @param {number} hBaseKey base key - * @param {Buffer} pTemplate new key template - * @param {number} ulAttributeCount template length - * @param {Buffer} phKey gets new handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DeriveKey(hSession: number, pMechanism: Buffer, hBaseKey: number, pTemplate: Buffer, ulAttributeCount: number, phKey: Buffer): number; - C_DeriveKey(hSession: number, pMechanism: Buffer, hBaseKey: number, pTemplate: Buffer, ulAttributeCount: number, phKey: Buffer, callback: Callback): void; - /** - * C_SeedRandom mixes additional seed material into the token's - * random number generator. - * @param {number} hSession the session's handle - * @param {Buffer} pSeed the seed material - * @param {number} ulSeedLen length of seed material - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SeedRandom(hSession: number, pSeed: Buffer, ulSeedLen: number): number; - C_SeedRandom(hSession: number, pSeed: Buffer, ulSeedLen: number, callback: Callback): void; - /** - * C_GenerateRandom generates random data. - * @param {number} hSession the session's handle - * @param {Buffer} pRandomData receives the random data - * @param {number} ulRandomLen # of bytes to generate - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GenerateRandom(hSession: number, pRandomData: Buffer, ulRandomLen: number): number; - C_GenerateRandom(hSession: number, pRandomData: Buffer, ulRandomLen: number, callback: Callback): void; - /** - * C_GetFunctionStatus is a legacy function; it obtains an - * updated status of a function running in parallel with an - * application. - * @param {number} hSession the session's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetFunctionStatus(hSession: number): number; - C_GetFunctionStatus(hSession: number, callback: Callback): void; - /** - * C_CancelFunction is a legacy function; it cancels a function - * running in parallel. - * @param {number} hSession the session's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_CancelFunction(hSession: number): number; - C_CancelFunction(hSession: number, callback: Callback): void; - /** - * C_WaitForSlotEvent waits for a slot event (token insertion, - * removal, etc.) to occur. - * @param {number} flags blocking/nonblocking flag - * @param {Buffer} pSlot location that receives the slot ID - * @param {Buffer} pRserved reserved. Should be NULL_PTR - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_WaitForSlotEvent(flags: number, pSlot: Buffer, pRserved: Buffer): number; - C_WaitForSlotEvent(flags: number, pSlot: Buffer, pRserved: Buffer, callback: Callback): number; + // ========== Core ========== + + /** + * Handle + */ + type Handle = Buffer; + /** + * BaseObject + * + * @interface BaseObject + */ + interface BaseObject { + } + /** + * HandleObject + * + * @interface HandleObject + * @extends {BaseObject} + */ + interface HandleObject extends BaseObject { + /** + * handle to pkcs11 object + */ + handle: Handle; } - enum KeyType { - RSA, - DSA, - DH, - ECDSA, - EC, - X9_42_DH, - KEA, - GENERIC_SECRET, - RC2, - RC4, - DES, - DES2, - DES3, - CAST, - CAST3, - CAST5, - CAST128, - RC5, - IDEA, - SKIPJACK, - BATON, - JUNIPER, - CDMF, - AES, - GOSTR3410, - GOSTR3411, - GOST28147, - BLOWFISH, - TWOFISH, - SECURID, - HOTP, - ACTI, - CAMELLIA, - ARIA, - } - enum KeyGenMechanism { - AES, - RSA, - RSA_X9_31, - DSA, - DH_PKCS, - DH_X9_42, - GOSTR3410, - GOST28147, - RC2, - RC4, - DES, - DES2, - SECURID, - ACTI, - CAST, - CAST3, - CAST5, - CAST128, - RC5, - IDEA, - GENERIC_SECRET, - SSL3_PRE_MASTER, - CAMELLIA, - ARIA, - SKIPJACK, - KEA, - BATON, - ECDSA, - EC, - JUNIPER, - TWOFISH, - } + /** + * Collection + * + * @interface Collection + * @extends {BaseObject} + * @template T + */ + interface Collection extends BaseObject { - enum MechanismEnum { - RSA_PKCS_KEY_PAIR_GEN, - RSA_PKCS, - RSA_9796, - RSA_X_509, - MD2_RSA_PKCS, - MD5_RSA_PKCS, - SHA1_RSA_PKCS, - RIPEMD128_RSA_PKCS, - RIPEMD160_RSA_PKCS, - RSA_PKCS_OAEP, - RSA_X9_31_KEY_PAIR_GEN, - RSA_X9_31, - SHA1_RSA_X9_31, - RSA_PKCS_PSS, - SHA1_RSA_PKCS_PSS, - DSA_KEY_PAIR_GEN, - DSA, - DSA_SHA1, - DH_PKCS_KEY_PAIR_GEN, - DH_PKCS_DERIVE, - X9_42_DH_KEY_PAIR_GEN, - X9_42_DH_DERIVE, - X9_42_DH_HYBRID_DERIVE, - X9_42_MQV_DERIVE, - SHA256_RSA_PKCS, - SHA384_RSA_PKCS, - SHA512_RSA_PKCS, - SHA256_RSA_PKCS_PSS, - SHA384_RSA_PKCS_PSS, - SHA512_RSA_PKCS_PSS, - SHA224_RSA_PKCS, - SHA224_RSA_PKCS_PSS, - RC2_KEY_GEN, - RC2_ECB, - RC2_CBC, - RC2_MAC, - RC2_MAC_GENERAL, - RC2_CBC_PAD, - RC4_KEY_GEN, - RC4, - DES_KEY_GEN, - DES_ECB, - DES_CBC, - DES_MAC, - DES_MAC_GENERAL, - DES_CBC_PAD, - DES2_KEY_GEN, - DES3_KEY_GEN, - DES3_ECB, - DES3_CBC, - DES3_MAC, - DES3_MAC_GENERAL, - DES3_CBC_PAD, - CDMF_KEY_GEN, - CDMF_ECB, - CDMF_CBC, - CDMF_MAC, - CDMF_MAC_GENERAL, - CDMF_CBC_PAD, - DES_OFB64, - DES_OFB8, - DES_CFB64, - DES_CFB8, - MD2, - MD2_HMAC, - MD2_HMAC_GENERAL, - MD5, - MD5_HMAC, - MD5_HMAC_GENERAL, - SHA1, - SHA, - SHA_1, - SHA_1_HMAC, - SHA_1_HMAC_GENERAL, - RIPEMD128, - RIPEMD128_HMAC, - RIPEMD128_HMAC_GENERAL, - RIPEMD160, - RIPEMD160_HMAC, - RIPEMD160_HMAC_GENERAL, - SHA256, - SHA256_HMAC, - SHA256_HMAC_GENERAL, - SHA224, - SHA224_HMAC, - SHA224_HMAC_GENERAL, - SHA384, - SHA384_HMAC, - SHA384_HMAC_GENERAL, - SHA512, - SHA512_HMAC, - SHA512_HMAC_GENERAL, - SECURID_KEY_GEN, - SECURID, - HOTP_KEY_GEN, - HOTP, - ACTI, - ACTI_KEY_GEN, - CAST_KEY_GEN, - CAST_ECB, - CAST_CBC, - CAST_MAC, - CAST_MAC_GENERAL, - CAST_CBC_PAD, - CAST3_KEY_GEN, - CAST3_ECB, - CAST3_CBC, - CAST3_MAC, - CAST3_MAC_GENERAL, - CAST3_CBC_PAD, - CAST5_KEY_GEN, - CAST128_KEY_GEN, - CAST5_ECB, - CAST128_ECB, - CAST5_CBC, - CAST128_CBC, - CAST5_MAC, - CAST128_MAC, - CAST5_MAC_GENERAL, - CAST128_MAC_GENERAL, - CAST5_CBC_PAD, - CAST128_CBC_PAD, - RC5_KEY_GEN, - RC5_ECB, - RC5_CBC, - RC5_MAC, - RC5_MAC_GENERAL, - RC5_CBC_PAD, - IDEA_KEY_GEN, - IDEA_ECB, - IDEA_CBC, - IDEA_MAC, - IDEA_MAC_GENERAL, - IDEA_CBC_PAD, - GENERIC_SECRET_KEY_GEN, - CONCATENATE_BASE_AND_KEY, - CONCATENATE_BASE_AND_DATA, - CONCATENATE_DATA_AND_BASE, - XOR_BASE_AND_DATA, - EXTRACT_KEY_FROM_KEY, - SSL3_PRE_MASTER_KEY_GEN, - SSL3_MASTER_KEY_DERIVE, - SSL3_KEY_AND_MAC_DERIVE, - SSL3_MASTER_KEY_DERIVE_DH, - TLS_PRE_MASTER_KEY_GEN, - TLS_MASTER_KEY_DERIVE, - TLS_KEY_AND_MAC_DERIVE, - TLS_MASTER_KEY_DERIVE_DH, - TLS_PRF, - SSL3_MD5_MAC, - SSL3_SHA1_MAC, - MD5_KEY_DERIVATION, - MD2_KEY_DERIVATION, - SHA1_KEY_DERIVATION, - SHA256_KEY_DERIVATION, - SHA384_KEY_DERIVATION, - SHA512_KEY_DERIVATION, - SHA224_KEY_DERIVATION, - PBE_MD2_DES_CBC, - PBE_MD5_DES_CBC, - PBE_MD5_CAST_CBC, - PBE_MD5_CAST3_CBC, - PBE_MD5_CAST5_CBC, - PBE_MD5_CAST128_CBC, - PBE_SHA1_CAST5_CBC, - PBE_SHA1_CAST128_CBC, - PBE_SHA1_RC4_128, - PBE_SHA1_RC4_40, - PBE_SHA1_DES3_EDE_CBC, - PBE_SHA1_DES2_EDE_CBC, - PBE_SHA1_RC2_128_CBC, - PBE_SHA1_RC2_40_CBC, - PKCS5_PBKD2, - PBA_SHA1_WITH_SHA1_HMAC, - WTLS_PRE_MASTER_KEY_GEN, - WTLS_MASTER_KEY_DERIVE, - WTLS_MASTER_KEY_DERIVE_DH_ECC, - WTLS_PRF, - WTLS_SERVER_KEY_AND_MAC_DERIVE, - WTLS_CLIENT_KEY_AND_MAC_DERIVE, - KEY_WRAP_LYNKS, - KEY_WRAP_SET_OAEP, - CMS_SIG, - KIP_DERIVE, - KIP_WRAP, - KIP_MAC, - CAMELLIA_KEY_GEN, - CAMELLIA_ECB, - CAMELLIA_CBC, - CAMELLIA_MAC, - CAMELLIA_MAC_GENERAL, - CAMELLIA_CBC_PAD, - CAMELLIA_ECB_ENCRYPT_DATA, - CAMELLIA_CBC_ENCRYPT_DATA, - CAMELLIA_CTR, - ARIA_KEY_GEN, - ARIA_ECB, - ARIA_CBC, - ARIA_MAC, - ARIA_MAC_GENERAL, - ARIA_CBC_PAD, - ARIA_ECB_ENCRYPT_DATA, - ARIA_CBC_ENCRYPT_DATA, - SKIPJACK_KEY_GEN, - SKIPJACK_ECB64, - SKIPJACK_CBC64, - SKIPJACK_OFB64, - SKIPJACK_CFB64, - SKIPJACK_CFB32, - SKIPJACK_CFB16, - SKIPJACK_CFB8, - SKIPJACK_WRAP, - SKIPJACK_PRIVATE_WRAP, - SKIPJACK_RELAYX, - KEA_KEY_PAIR_GEN, - KEA_KEY_DERIVE, - FORTEZZA_TIMESTAMP, - BATON_KEY_GEN, - BATON_ECB128, - BATON_ECB96, - BATON_CBC128, - BATON_COUNTER, - BATON_SHUFFLE, - BATON_WRAP, - ECDSA_KEY_PAIR_GEN, - EC_KEY_PAIR_GEN, - ECDSA, - ECDSA_SHA1, - ECDSA_SHA224, - ECDSA_SHA256, - ECDSA_SHA384, - ECDSA_SHA512, - ECDH1_DERIVE, - ECDH1_COFACTOR_DERIVE, - ECMQV_DERIVE, - JUNIPER_KEY_GEN, - JUNIPER_ECB128, - JUNIPER_CBC128, - JUNIPER_COUNTER, - JUNIPER_SHUFFLE, - JUNIPER_WRAP, - FASTHASH, - AES_KEY_GEN, - AES_ECB, - AES_CBC, - AES_MAC, - AES_MAC_GENERAL, - AES_CBC_PAD, - AES_CTR, - AES_CMAC, - AES_CMAC_GENERAL, - BLOWFISH_KEY_GEN, - BLOWFISH_CBC, - TWOFISH_KEY_GEN, - TWOFISH_CBC, - AES_GCM, - AES_CCM, - AES_KEY_WRAP, - AES_KEY_WRAP_PAD, - DES_ECB_ENCRYPT_DATA, - DES_CBC_ENCRYPT_DATA, - DES3_ECB_ENCRYPT_DATA, - DES3_CBC_ENCRYPT_DATA, - AES_ECB_ENCRYPT_DATA, - AES_CBC_ENCRYPT_DATA, - GOSTR3410_KEY_PAIR_GEN, - GOSTR3410, - GOSTR3410_WITH_GOSTR3411, - GOSTR3410_KEY_WRAP, - GOSTR3410_DERIVE, - GOSTR3411, - GOSTR3411_HMAC, - GOST28147_KEY_GEN, - GOST28147_ECB, - GOST28147, - GOST28147_MAC, - GOST28147_KEY_WRAP, - DSA_PARAMETER_GEN, - DH_PKCS_PARAMETER_GEN, - X9_42_DH_PARAMETER_GEN, - VENDOR_DEFINED, - } + /** + * returns length of collection + */ + length: number; - interface IParams { - toCKI(): Buffer; - } - - interface IAlgorithm { - name: string; - params: Buffer | IParams; - } - - type MechanismType = MechanismEnum | KeyGenMechanism | IAlgorithm | string; - - enum MechanismFlag { - /** - * `True` if the mechanism is performed by the device; `false` if the mechanism is performed in software - */ - HW, - /** - * `True` if the mechanism can be used with encrypt function - */ - ENCRYPT, - /** - * `True` if the mechanism can be used with decrypt function - */ - DECRYPT, - /** - * `True` if the mechanism can be used with digest function - */ - DIGEST, - /** - * `True` if the mechanism can be used with sign function - */ - SIGN, - /** - * `True` if the mechanism can be used with sign recover function - */ - SIGN_RECOVER, - /** - * `True` if the mechanism can be used with verify function - */ - VERIFY, - /** - * `True` if the mechanism can be used with verify recover function - */ - VERIFY_RECOVER, - /** - * `True` if the mechanism can be used with geberate function - */ - GENERATE, - /** - * `True` if the mechanism can be used with generate key pair function - */ - GENERATE_KEY_PAIR, - /** - * `True` if the mechanism can be used with wrap function - */ - WRAP, - /** - * `True` if the mechanism can be used with unwrap function - */ - UNWRAP, - /** - * `True` if the mechanism can be used with derive function - */ - DERIVE, - } - class Mechanism extends HandleObject { - protected slotHandle: number; - /** - * the minimum size of the key for the mechanism - * _whether this is measured in bits or in bytes is mechanism-dependent_ - */ - minKeySize: number; - /** - * the maximum size of the key for the mechanism - * _whether this is measured in bits or in bytes is mechanism-dependent_ - */ - maxKeySize: number; - /** - * bit flag specifying mechanism capabilities - */ - flags: number; - /** - * returns string name from MechanismEnum - */ - name: string; - constructor(handle: number, slotHandle: number, lib: Pkcs11); - protected getInfo(): void; - static create(alg: MechanismType): Buffer; - static vendor(jsonFile: string): any; - static vendor(name: string, value: number): any; - } - - class MechanismCollection extends Collection { - protected slotHandle: number; - constructor(items: Array, slotHandle: number, lib: Pkcs11, classType?: typeof Mechanism); /** * returns item from collection by index * @param {number} index of element in collection `[0..n]` */ - items(index: number): Mechanism; + items(index: number): T; + + } + type SessionObjectCollection = Collection + type MechanismCollection = Collection; + type SlotCollection = Collection; + + // ========== PKCS11 Objects ========== + + /** + * Certificate objects (object class CKO_CERTIFICATE) hold public-key or attribute certificates + */ + interface Certificate extends Storage { + /** + * Type of certificate + */ + type: graphene.CertificateType; + /** + * The certificate can be trusted for the application that it was created. + */ + trusted: boolean; + /** + * Categorization of the certificate + */ + category: graphene.CertificateCategory; + /** + * Checksum + */ + checkValue: Buffer; + /** + * Start date for the certificate (default empty) + */ + startDate: Date; + /** + * End date for the certificate (default empty) + */ + endDate: Date; + } + + /** + * X.509 certificate objects (certificate type `CKC_X_509`) hold X.509 public key certificates + */ + interface X509Certificate extends Certificate { + /** + * DER-encoding of the certificate subject name + * - Must be specified when the object is created. + * - Must be non-empty if `CKA_URL` is empty. + */ + subject: Buffer; + /** + * Key identifier for public/private key pair (default empty) + */ + id: Buffer; + /** + * DER-encoding of the certificate issuer name (default empty) + */ + issuer: Buffer; + /** + * HEX-encoding of the certificate serial number (default empty) + */ + serialNumber: string; + /** + * BER-encoding of the certificate + * - Must be specified when the object is created. + * - Must be non-empty if `CKA_URL` is empty. + */ + value: Buffer; + /** + * If not empty this attribute gives the URL where the complete certificate + * can be obtained (default empty) + * - Must be non-empty if `CKA_VALUE` is empty + */ + url: string; + /** + * SHA-1 hash of the subject public key (default empty) + * - Can only be empty if `CKA_URL` is empty. + */ + subjetcKeyIdentifier: Buffer; + /** + * SHA-1 hash of the issuer public key (default empty) + * - Can only be empty if `CKA_URL` is empty. + */ + authorityKeyIdentifier: Buffer; + /** + * Java MIDP security domain + */ + java: graphene.JavaMIDP; + } + + /** + * WTLS certificate objects (certificate type `CKC_WTLS`) hold WTLS public key certificates + */ + interface WtlsCertificate extends Certificate { + /** + * WTLS-encoding (Identifier type) of the certificate subject + * - Must be specified when the object is created. + * - Can only be empty if `CKA_VALUE` is empty. + */ + subject: Buffer; + /** + * WTLS-encoding (Identifier type) of the certificate issuer (default empty) + */ + issuer: Buffer; + /** + * Key identifier for public/private key pair (default empty) + */ + id: Buffer; + /** + * WTLS-encoding of the certificate + * - Must be specified when the object is created. + * - Must be non-empty if `CKA_URL` is empty. + */ + value: Buffer; + /** + * If not empty this attribute gives the URL where the complete certificate + * can be obtained (default empty) + * - Must be non-empty if `CKA_VALUE` is empty + */ + url: string; + /** + * DER-encoding of the certificate serial number (default empty) + */ + serialNumber: Buffer; + /** + * SHA-1 hash of the subject public key (default empty) + * - Can only be empty if `CKA_URL` is empty. + */ + subjetcKeyIdentifier: Buffer; + /** + * SHA-1 hash of the issuer public key (default empty) + * - Can only be empty if `CKA_URL` is empty. + */ + authorityKeyIdentifier: Buffer; + } + + /** + * X.509 attribute certificate objects (certificate type `CKC_X_509_ATTR_CERT`) hold X.509 attribute certificates + */ + interface AttributeCertificate extends Certificate { + /** + * DER-encoding of the attribute certificate's subject field. + * This is distinct from the `CKA_SUBJECT` attribute contained in `CKC_X_509` certificates + * because the `ASN.1` syntax and encoding are different. + * - Must be specified when the object is created + */ + owner: Buffer; + /** + * DER-encoding of the attribute certificate's issuer field. + * This is distinct from the `CKA_ISSUER` attribute contained in `CKC_X_509` certificates + * because the ASN.1 syntax and encoding are different. (default empty) + */ + issuer: Buffer; + /** + * DER-encoding of the certificate serial number (default empty) + */ + serialNumber: Buffer; + /** + * BER-encoding of a sequence of object identifier values corresponding + * to the attribute types contained in the certificate. + * When present, this field offers an opportunity for applications + * to search for a particular attribute certificate without fetching + * and parsing the certificate itself. (default empty) + */ + types: Buffer; + /** + * BER-encoding of the certificate + * - Must be specified when the object is created. + */ + value: Buffer; + } + + interface DomainParameters extends Storage { + /** + * Type of key the domain parameters can be used to generate. + */ + keyType: graphene.KeyType; + /** + * `CK_TRUE` only if domain parameters were either * generated locally (i.e., on the token) + * with a `C_GenerateKey` * created with a `C_CopyObject` call as a copy of domain parameters + * which had its `CKA_LOCAL` attribute set to `CK_TRUE` + */ + local: boolean; + } + + /** + * Data objects (object class `CKO_DATA`) hold information defined by an application. + * Other than providing access to it, Cryptoki does not attach any special meaning to a data object + * + * @ + * @class Data + * @extends {Storage} + */ + interface Data extends Storage { + /** + * Description of the application that manages the object (default empty) + * + * @type {string} + */ + application: string; + /** + * DER-encoding of the object identifier indicating the data object type (default empty) + * + * @type {Buffer} + */ + objectId: Buffer; + /** + * Value of the object (default empty) + * + * @type {Buffer} + */ + value: Buffer; } /** @@ -1232,13 +278,13 @@ declare module "graphene-pk11" { * - defines the object class `CKO_PUBLIC_KEY`, `CKO_PRIVATE_KEY` and `CKO_SECRET_KEY` for type `CK_OBJECT_CLASS` * as used in the `CKA_CLASS` attribute of objects */ - class Key extends Storage { + interface Key extends Storage { /** * Type of key * - Must be specified when object is created with `C_CreateObject` * - Must be specified when object is unwrapped with `C_UnwrapKey` */ - type: KeyType; + type: graphene.KeyType; /** * Key identifier for key (default empty) * - May be modified after object is created with a `C_SetAttributeValue` call, @@ -1288,41 +334,736 @@ declare module "graphene-pk11" { * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. * - Must not be specified when object is unwrapped with `C_UnwrapKey`. */ - mechanism: KeyGenMechanism; + mechanism: graphene.KeyGenMechanism; allowedMechanisms: void; } - - class DomainParameters extends Storage { + /** + * Private key objects (object class `CKO_PRIVATE_KEY`) hold private keys + */ + interface PrivateKey extends Key { /** - * Type of key the domain parameters can be used to generate. + * DER-encoding of the key subject name (default empty) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. */ - keyType: KeyType; + subject: Buffer; /** - * `CK_TRUE` only if domain parameters were either * generated locally (i.e., on the token) - * with a `C_GenerateKey` * created with a `C_CopyObject` call as a copy of domain parameters - * which had its `CKA_LOCAL` attribute set to `CK_TRUE` + * `CK_TRUE` if key is sensitive + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Attribute cannot be changed once set to CK_TRUE. It becomes a read only attribute. + * - Default value is token-specific, and may depend on the values of other attributes. */ - local: boolean; + sensitive: boolean; + /** + * `CK_TRUE` if key supports decryption + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + decrypt: boolean; + /** + * `CK_TRUE` if key supports signatures where the signature is an appendix to the data + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + sign: boolean; + /** + * `CK_TRUE` if key supports signatures where the data can be recovered from the signature + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + signRecover: boolean; + /** + * `CK_TRUE` if key supports unwrapping (i.e., can be used to unwrap other keys) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + unwrap: boolean; + /** + * `CK_TRUE` if key is extractable and can be wrapped + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Attribute cannot be changed once set to `CK_FALSE`. It becomes a read only attribute. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + extractable: boolean; + /** + * `CK_TRUE` if key has always had the `CKA_SENSITIVE` attribute set to `CK_TRUE` + * - Must not be specified when object is created with `C_CreateObject`. + * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. + * - Must not be specified when object is unwrapped with `C_UnwrapKey`. + */ + alwaysSensitive: boolean; + /** + * `CK_TRUE` if key has never had the `CKA_EXTRACTABLE` attribute set to `CK_TRUE` + * - Must not be specified when object is created with `C_CreateObject`. + * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. + * - Must not be specified when object is unwrapped with `C_UnwrapKey`. + */ + neverExtractable: boolean; + /** + * `CK_TRUE` if the key can only be wrapped with a wrapping key + * that has `CKA_TRUSTED` set to `CK_TRUE`. Default is `CK_FALSE`. + * - Attribute cannot be changed once set to `CK_TRUE`. It becomes a read only attribute. + */ + wrapTrusted: boolean; + /** + * For wrapping keys. The attribute template to apply to any keys unwrapped + * using this wrapping key. Any user supplied template is applied after this template + * as if the object has already been created. + */ + template: void; + alwaysAuthenticate: boolean; } /** - * Data objects (object class `CKO_DATA`) hold information defined by an application. - * Other than providing access to it, Cryptoki does not attach any special meaning to a data object + * Public key objects (object class CKO_PUBLIC_KEY) hold public keys */ - class Data extends Storage { + interface PublicKey extends Key { /** - * Description of the application that manages the object (default empty) + * DER-encoding of the key subject name (default empty) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. */ - application: string; + subject: Buffer; /** - * DER-encoding of the object identifier indicating the data object type (default empty) + * `CK_TRUE` if key supports encryption + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. */ - objectId: Buffer; + encrypt: boolean; /** - * Value of the object (default empty) + * `CK_TRUE` if key supports verification where the signature is an appendix to the data + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. */ + verify: boolean; + /** + * `CK_TRUE` if key supports verification where the data is recovered from the signature + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + verifyRecover: boolean; + /** + * `CK_TRUE` if key supports wrapping (i.e., can be used to wrap other keys) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + wrap: boolean; + /** + * The key can be trusted for the application that it was created. + * - The wrapping key can be used to wrap keys with `CKA_WRAP_WITH_TRUSTED` set to `CK_TRUE`. + * - Can only be set to CK_TRUE by the SO user. + */ + trusted: boolean; + /** + * For wrapping keys. The attribute template to match against any keys wrapped using this wrapping key. + * Keys that do not match cannot be wrapped. + */ + template: void; + } + + /** + * Secret key objects (object class `CKO_SECRET_KEY`) hold secret keys. + */ + interface SecretKey extends Key { + /** + * `CK_TRUE` if key is sensitive + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Attribute cannot be changed once set to `CK_TRUE`. It becomes a read only attribute. + */ + sensitive: boolean; + /** + * `CK_TRUE` if key supports encryption + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + encrypt: boolean; + /** + * `CK_TRUE` if key supports decryption + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + decrypt: boolean; + /** + * `CK_TRUE` if key supports verification (i.e., of authentication codes) where the signature is an appendix to the data + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + verify: boolean; + /** + * `CK_TRUE` if key supports signatures (i.e., authentication codes) where the signature is an appendix to the data + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + sign: boolean; + /** + * `CK_TRUE` if key supports wrapping (i.e., can be used to wrap other keys) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + wrap: boolean; + /** + * `CK_TRUE` if key supports unwrapping (i.e., can be used to unwrap other keys) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + unwrap: boolean; + /** + * `CK_TRUE` if key is extractable and can be wrapped + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Attribute cannot be changed once set to `CK_FALSE`. It becomes a read only attribute. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + extractable: boolean; + /** + * `CK_TRUE` if key has always had the `CKA_SENSITIVE` attribute set to `CK_TRUE` + * - Must not be specified when object is created with `C_CreateObject`. + * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. + * - Must not be specified when object is unwrapped with `C_UnwrapKey`. + */ + alwaysSensitive: boolean; + /** + * `CK_TRUE` if key has never had the `CKA_EXTRACTABLE` attribute set to `CK_TRUE` + * - Must not be specified when object is created with `C_CreateObject`. + * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. + * - Must not be specified when object is unwrapped with `C_UnwrapKey`. + */ + neverExtractable: boolean; + /** + * Key checksum + */ + checkValue: Buffer; + /** + * `CK_TRUE` if the key can only be wrapped with a wrapping key + * that has `CKA_TRUSTED` set to `CK_TRUE`. Default is `CK_FALSE`. + * - Attribute cannot be changed once set to `CK_TRUE`. It becomes a read only attribute. + */ + wrapTrusted: boolean; + /** + * The wrapping key can be used to wrap keys with `CKA_WRAP_WITH_TRUSTED` set to `CK_TRUE`. + * - Can only be set to CK_TRUE by the SO user. + */ + trusted: boolean; + /** + * For wrapping keys. + * The attribute template to match against any keys wrapped using this wrapping key. + * Keys that do not match cannot be wrapped. + */ + wrapTemplate: void; + /** + * For wrapping keys. + * The attribute template to apply to any keys unwrapped using this wrapping key. + * Any user supplied template is applied after this template as if the object has already been created. + */ + unwrapTemplate: void; + } + + interface Storage extends SessionObject { + /** + * `true` if object is a token object; + * `false` if object is a session object. Default is `false`. + */ + token: boolean; + /** + * `true` if object is a private object; + * `false` if object is a public object. + * Default value is token-specific, and may depend on the values of other attributes of the object. + */ + private: boolean; + /** + * `true` if object can be modified. Default is `false` + */ + modifiable: boolean; + /** + * Description of the object (default empty) + */ + label: string; + } + + interface SessionObject extends HandleObject { + /** + * Session + */ + session: Session; + /** + * gets the size of an object in bytes + * + * @readonly + * @type {number} + */ + size: number; + /** + * copies an object, creating a new object for the copy + * + * @param {ITemplate} template template for the new object + * @returns {SessionObject} + */ + copy(template: ITemplate): SessionObject; + /** + * destroys an object + */ + destroy(): void; + getAttribute(attr: string): ITemplate; + getAttribute(attrs: ITemplate): ITemplate; + setAttribute(attrs: string, value: any): void; + setAttribute(attrs: ITemplate): void; + class: graphene.ObjectClass; + toType(): T; + } + + // ========== Crypto ========== + + /** + * Type CryptoData + */ + type CryptoData = string | Buffer; + + interface INamedCurve { + name: string; + oid: string; value: Buffer; + size: number; + } + + /** + * Cipher + * + * @interface Cipher + * @extends {BaseObject} + */ + interface Cipher extends BaseObject { + update(data: CryptoData): Buffer; + final(): Buffer; + once(data: CryptoData, enc: Buffer): Buffer; + once(data: CryptoData, enc: Buffer, cb: (error: Error, data: Buffer) => void): void; + } + + /** + * Decipher + * + * @interface Decipher + * @extends {BaseObject} + */ + interface Decipher extends BaseObject { + update(data: Buffer): Buffer; + final(): Buffer; + once(data: Buffer, dec: Buffer): Buffer; + once(data: Buffer, dec: Buffer, cb: (error: Error, data: Buffer) => void): void; + } + + /** + * Digest + * + * @interface Digest + * @extends {BaseObject} + */ + interface Digest extends BaseObject { + update(data: CryptoData): void; + final(): Buffer; + once(data: CryptoData): Buffer; + once(data: CryptoData, cb: (error: Error, data: Buffer) => void): void; + } + + /** + * Sign + * + * @interface Sign + * @extends {BaseObject} + */ + interface Sign extends BaseObject { + update(data: CryptoData): void; + final(): Buffer; + once(data: CryptoData): Buffer; + once(data: CryptoData, cb: (error: Error, data: Buffer) => void): void; + } + + /** + * Verify + * + * @interface Verify + * @extends {BaseObject} + */ + interface Verify extends BaseObject { + update(data: CryptoData): void; + final(signature: Buffer): boolean; + once(data: CryptoData, signature: Buffer): boolean; + once(data: CryptoData, signature: Buffer, cb: (error: Error, valid: boolean) => void): void; + } + + interface IAlgorithm { + name: string; + params: Buffer | IParams; + } + + type MechanismType = graphene.MechanismEnum | graphene.KeyGenMechanism | IAlgorithm | string; + + interface Mechanism extends BaseObject { + /** + * the minimum size of the key for the mechanism + * _whether this is measured in bits or in bytes is mechanism-dependent_ + */ + minKeySize: number; + /** + * the maximum size of the key for the mechanism + * _whether this is measured in bits or in bytes is mechanism-dependent_ + */ + maxKeySize: number; + /** + * bit flag specifying mechanism capabilities + */ + flags: number; + /** + * returns string name from MechanismEnum + */ + name: string; + } + + interface IParams { + toCKI(): any; + } + + interface IKeyPair { + privateKey: PrivateKey; + publicKey: PublicKey; + } + + /** + * provides information about a session + * + * @ + * @class Session + * @extends {HandleObject} + */ + interface Session extends HandleObject { + /** + * Slot + * + * @type {Slot} + */ + slot: Slot; + /** + * the state of the session + * + * @type {number} + */ + state: number; + /** + * bit flags that define the type of session + * + * @type {number} + */ + flags: number; + /** + * an error code defined by the cryptographic device. Used for errors not covered by Cryptoki + * + * @type {number} + */ + deviceError: number; + /** + * closes a session between an application and a token + */ + close(): void; + /** + * initializes the normal user's PIN + * @param {string} pin the normal user's PIN + */ + initPin(pin: string): void; + /** + * modifies the PIN of the user who is logged in + * @param {string} oldPin + * @param {string} newPin + */ + setPin(oldPin: string, newPin: string): void; + /** + * obtains a copy of the cryptographic operations state of a session, encoded as a string of bytes + */ + getOperationState(): Buffer; + /** + * restores the cryptographic operations state of a session + * from a string of bytes obtained with getOperationState + * @param {Buffer} state the saved state + * @param {number} encryptionKey holds key which will be used for an ongoing encryption + * or decryption operation in the restored session + * (or 0 if no encryption or decryption key is needed, + * either because no such operation is ongoing in the stored session + * or because all the necessary key information is present in the saved state) + * @param {number} authenticationKey holds a handle to the key which will be used for an ongoing signature, + * MACing, or verification operation in the restored session + * (or 0 if no such key is needed, either because no such operation is ongoing in the stored session + * or because all the necessary key information is present in the saved state) + */ + setOperationState(state: Buffer, encryptionKey?: number, authenticationKey?: number): void; + /** + * logs a user into a token + * @param {string} pin the user's PIN. + * - This standard allows PIN values to contain any valid `UTF8` character, + * but the token may impose subset restrictions + * @param {} userType the user type. Default is `USER` + */ + login(pin: string, userType?: graphene.UserType): void; + /** + * logs a user out from a token + */ + logout(): void; + /** + * creates a new object + * - Only session objects can be created during a read-only session. + * - Only public objects can be created unless the normal user is logged in. + * @param {ITemplate} template the object's template + * @returns {SessionObject} + */ + create(template: ITemplate): SessionObject; + /** + * Copies an object, creating a new object for the copy + * @param {SessionObject} object the copied object + * @param {ITemplate} template template for new object + * @returns {SessionObject} + */ + copy(object: SessionObject, template: ITemplate): SessionObject; + /** + * removes all session objects matched to template + * - if template is null, removes all session objects + * - returns a number of destroied session objects + * @param {ITemplate} template template + */ + destroy(template: ITemplate): number; + /** + * @param {SessionObject} object + */ + destroy(object: SessionObject): number; + destroy(): number; + /** + * removes all session objects + * - returns a number of destroied session objects + */ + clear(): number; + /** + * returns a collection of session objects mached to template + * @param template template + * @param callback optional callback function wich is called for each founded object + * - if callback function returns false, it breaks find function. + */ + find(callback?: (obj: SessionObject) => any): SessionObjectCollection; + find(template: ITemplate, callback?: (obj: SessionObject, index: number) => any): SessionObjectCollection; + /** + * Returns object from session by handle + * @param {number} handle handle of object + * @returns T + */ + getObject(handle: Handle): T; + /** + * generates a secret key or set of domain parameters, creating a new object. + * @param mechanism generation mechanism + * @param template template for the new key or set of domain parameters + */ + generateKey(mechanism: MechanismType, template?: ITemplate): SecretKey; + generateKey(mechanism: MechanismType, template: ITemplate, callback: (err: Error, key: SecretKey) => void): void; + generateKeyPair(mechanism: MechanismType, publicTemplate: ITemplate, privateTemplate: ITemplate): IKeyPair; + generateKeyPair(mechanism: MechanismType, publicTemplate: ITemplate, privateTemplate: ITemplate, callback: (err: Error, keys: IKeyPair) => void): void; + createSign(alg: MechanismType, key: Key): Sign; + createVerify(alg: MechanismType, key: Key): Verify; + createCipher(alg: MechanismType, key: Key): Cipher; + createDecipher(alg: MechanismType, key: Key, blockSize?: number): Decipher; + createDigest(alg: MechanismType): Digest; + wrapKey(alg: MechanismType, wrappingKey: Key, key: Key): Buffer; + wrapKey(alg: MechanismType, wrappingKey: Key, key: Key, callback: (err: Error, wkey: Buffer) => void): void; + unwrapKey(alg: MechanismType, unwrappingKey: Key, wrappedKey: Buffer, template: ITemplate): Key; + unwrapKey(alg: MechanismType, unwrappingKey: Key, wrappedKey: Buffer, template: ITemplate, callback: (err: Error, key: Key) => void): void; + /** + * derives a key from a base key, creating a new key object + * @param {MechanismType} alg key deriv. mech + * @param {Key} baseKey base key + * @param {ITemplate} template new key template + */ + deriveKey(alg: MechanismType, baseKey: Key, template: ITemplate): SecretKey; + deriveKey(alg: MechanismType, baseKey: Key, template: ITemplate, callback: (err: Error, key: Key) => void): void; + /** + * generates random data + * @param {number} size \# of bytes to generate + */ + generateRandom(size: number): Buffer; + } + + interface Slot extends HandleObject { + slotDescription: string; + manufacturerID: string; + flags: number; + hardwareVersion: pkcs11.Version; + firmwareVersion: pkcs11.Version; + module: graphene.Module; + /** + * Returns information about token + * + * @returns {Token} + */ + getToken(): Token; + /** + * returns list of `MechanismInfo` + * + * @returns {MechanismCollection} + */ + getMechanisms(): MechanismCollection; + /** + * initializes a token + * + * @param {string} pin the SO's initial PIN + * @returns {string} + */ + initToken(pin: string): string; + /** + * opens a session between an application and a token in a particular slot + * + * @param {SessionFlag} [flags=session.SessionFlag.SERIAL_SESSION] indicates the type of session + * @returns {Session} + */ + open(flags?: graphene.SessionFlag): Session; + /** + * closes all sessions an application has with a token + */ + closeAll(): void; + } + + interface Token extends HandleObject { + /** + * application-defined label, assigned during token initialization. + * - Must be padded with the blank character (' '). + * - Should __not__ be null-terminated. + */ + label: string; + /** + * ID of the device manufacturer. + * - Must be padded with the blank character (' '). + * - Should __not__ be null-terminated. + */ + manufacturerID: string; + /** + * model of the device. + * - Must be padded with the blank character (' '). + * - Should __not__ be null-terminated. + */ + model: string; + /** + * character-string serial number of the device. + * - Must be padded with the blank character (' '). + * - Should __not__ be null-terminated. + */ + serialNumber: string; + /** + * bit flags indicating capabilities and status of the device + */ + flags: number; + /** + * maximum number of sessions that can be opened with the token at one time by a single application + */ + maxSessionCount: number; + /** + * number of sessions that this application currently has open with the token + */ + sessionCount: number; + /** + * maximum number of read/write sessions that can be opened + * with the token at one time by a single application + */ + maxRwSessionCount: number; + /** + * number of read/write sessions that this application currently has open with the token + */ + rwSessionCount: number; + /** + * maximum length in bytes of the PIN + */ + maxPinLen: number; + /** + * minimum length in bytes of the PIN + */ + minPinLen: number; + /** + * the total amount of memory on the token in bytes in which public objects may be stored + */ + totalPublicMemory: number; + /** + * the amount of free (unused) memory on the token in bytes for public objects + */ + freePublicMemory: number; + /** + * the total amount of memory on the token in bytes in which private objects may be stored + */ + totalPrivateMemory: number; + /** + * the amount of free (unused) memory on the token in bytes for private objects + */ + freePrivateMemory: number; + /** + * version number of hardware + */ + hardwareVersion: pkcs11.Version; + /** + * version number of firmware + */ + firmwareVersion: pkcs11.Version; + /** + * current time as a character-string of length 16, + * represented in the format YYYYMMDDhhmmssxx + */ + utcTime: Date; } interface ITemplate { @@ -1638,7 +1379,7 @@ declare module "graphene-pk11" { /** * CKA_OTP_USER_IDENTIFIER */ - OtpUserId?: any; + otpUserId?: any; /** * CKA_OTP_SERVICE_IDENTIFIER */ @@ -1724,41 +1465,211 @@ declare module "graphene-pk11" { */ allowedMechanisms?: any; } - class Attribute { - protected $value: Buffer; - type: number; - name: string; - convertType: string; - length: number; - value: any; - constructor(type: number, value?: any); - constructor(type: string, value?: any); - get(): any; - set(template: any): void; - } - class Template { - protected attrs: Attribute[]; - length: number; - constructor(template: string); - constructor(template: ITemplate); - set(v: any): Template; - ref(): Buffer; - serialize(): any; + +} + +declare module "graphene-pk11" { + import * as graphene from "types/graphene-pk11"; + import * as pkcs11 from "pkcs11js"; + + // ========== Parameters ========== + + // ========== AES ========== + + /** + * Parameter AES CBC + * + * @class AesCbcParams + * @implements {graphene.IParams} + * @implements {pkcs11.AesCBC} + */ + class AesCbcParams implements graphene.IParams, pkcs11.AesCBC { + /** + * initialization vector + * - must have a fixed size of 16 bytes + */ + iv: Buffer; + /** + * the data + */ + data: Buffer; + type: MechParams; + constructor(iv: Buffer, data?: Buffer); + toCKI(): Buffer; } - class BaseObject { - protected lib: Pkcs11; - constructor(lib?: Pkcs11); - } - class HandleObject extends BaseObject { + /** + * Parameter AES CCM + * + * @class AesCcmParams + * @implements {graphene.IParams} + */ + class AesCcmParams implements graphene.IParams { /** - * handle to pkcs11 object + * length of the data where 0 <= dataLength < 2^8L */ - handle: number; - constructor(handle: number, lib: Pkcs11); - protected getInfo(): void; + dataLength: number; + /** + * the nonce + */ + nonce: Buffer; + /** + * the additional authentication data + * - This data is authenticated but not encrypted + */ + aad: Buffer; + /** + * length of authentication tag (output following cipher text) in bits. + * - Can be any value between 0 and 128 + */ + macLength: number; + type: MechParams; + constructor(dataLength: number, nonce: Buffer, aad?: Buffer, macLength?: number); + toCKI(): pkcs11.AesCCM; } + /** + * Parameter AES GCM + * + * @class AesGcmParams + * @implements {graphene.IParams} + */ + class AesGcmParams implements graphene.IParams { + /** + * initialization vector + * - The length of the initialization vector can be any number between 1 and 256. + * 96-bit (12 byte) IV values can be processed more efficiently, + * so that length is recommended for situations in which efficiency is critical. + */ + iv: Buffer; + /** + * pointer to additional authentication data. + * This data is authenticated but not encrypted. + */ + aad: Buffer; + /** + * length of authentication tag (output following cipher text) in bits. + * Can be any value between 0 and 128. Default 128 + */ + tagBits: number; + type: MechParams; + constructor(iv: Buffer, aad?: Buffer, tagBits?: number); + toCKI(): pkcs11.AesGCM; + } + + // ========== EC ========== + + /** + * Parameter EC DH + * + * @class EcdhParams + * @implements {graphene.IParams} + * @implements {pkcs11.ECDH1} + */ + class EcdhParams implements graphene.IParams, pkcs11.ECDH1 { + /** + * key derivation function used on the shared secret value + */ + kdf: EcKdf; + /** + * some data shared between the two parties + */ + sharedData: Buffer; + /** + * other party's EC public key value + */ + publicData: Buffer; + type: MechParams; + /** + * Creates an instance of EcdhParams. + * + * @param {EcKdf} kdf key derivation function used on the shared secret value + * @param {Buffer} [sharedData=null] some data shared between the two parties + * @param {Buffer} [publicData=null] other party's EC public key value + */ + constructor(kdf: EcKdf, sharedData?: Buffer, publicData?: Buffer); + toCKI(): pkcs11.ECDH1; + } + + class NamedCurve { + static getByName(name: string): graphene.INamedCurve; + static getByOid(oid: string): graphene.INamedCurve; + } + + /** + * EcKdf is used to indicate the Key Derivation Function (KDF) + * applied to derive keying data from a shared secret. + * The key derivation function will be used by the EC key agreement schemes. + */ + enum EcKdf { + NULL, + SHA1, + SHA224, + SHA256, + SHA384, + SHA512, + } + + // ========== RSA ========== + + /** + * Parameter RSA OAEP + * + * @class RsaOaepParams + * @implements {graphene.IParams} + */ + class RsaOaepParams implements graphene.IParams { + hashAlgorithm: MechanismEnum; + mgf: RsaMgf; + source: number; + sourceData: Buffer; + type: MechParams; + constructor(hashAlg?: MechanismEnum, mgf?: RsaMgf, sourceData?: Buffer); + toCKI(): pkcs11.RsaOAEP; + } + + /** + * Parameter RSA PSS + * + * @class RsaPssParams + * @implements {graphene.IParams} + */ + class RsaPssParams implements graphene.IParams { + /** + * hash algorithm used in the PSS encoding; + * - if the signature mechanism does not include message hashing, + * then this value must be the mechanism used by the application to generate + * the message hash; + * - if the signature mechanism includes hashing, + * then this value must match the hash algorithm indicated + * by the signature mechanism + */ + hashAlgorithm: MechanismEnum; + /** + * mask generation function to use on the encoded block + */ + mgf: RsaMgf; + /** + * length, in bytes, of the salt value used in the PSS encoding; + * - typical values are the length of the message hash and zero + */ + saltLength: number; + type: MechParams; + constructor(hashAlg?: MechanismEnum, mgf?: RsaMgf, saltLen?: number); + toCKI(): pkcs11.RsaPSS; + } + + enum RsaMgf { + MGF1_SHA1, + MGF1_SHA224, + MGF1_SHA256, + MGF1_SHA384, + MGF1_SHA512, + } + + + // ========== Enums ========== + enum ObjectClass { DATA, CERTIFICATE, @@ -1771,327 +1682,467 @@ declare module "graphene-pk11" { OTP_KEY, } - class SessionObject extends HandleObject { - /** - * Session - */ - session: Session; - /** - * gets the size of an object in bytes - */ - size: number; - constructor(object: SessionObject); - constructor(handle: number, session: Session, lib: Pkcs11); - /** - * copies an object, creating a new object for the copy - * @param {ITemplate} template template for the new object - */ - copy(template: ITemplate): SessionObject; - /** - * destroys an object - */ - destroy(): void; - getAttribute(attr: string): ITemplate; - getAttribute(attrs: ITemplate): ITemplate; - setAttribute(attrs: string, value: any): any; - setAttribute(attrs: ITemplate): any; - protected get(name: string): any; - protected set(name: string, value: any): void; - class: ObjectClass; - toType(): T; + class Mechanism { + static vendor(jsonFile: string): void; + static vendor(name: string, value: number): void; } - class SessionObjectCollection extends Collection { - session: Session; - items(index: number): SessionObject; - constructor(items: Array, session: Session, lib: Pkcs11, classType?: any); + enum CertificateType { + X_509, + X_509_ATTR_CERT, + WTLS, } - /** - * Private key objects (object class `CKO_PRIVATE_KEY`) hold private keys - */ - class PrivateKey extends Key { - /** - * DER-encoding of the key subject name (default empty) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - */ - subject: Buffer; - /** - * `CK_TRUE` if key is sensitive - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Attribute cannot be changed once set to CK_TRUE. It becomes a read only attribute. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - sensitive: boolean; - /** - * `CK_TRUE` if key supports decryption - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - decrypt: boolean; - /** - * `CK_TRUE` if key supports signatures where the signature is an appendix to the data - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - sign: boolean; - /** - * `CK_TRUE` if key supports signatures where the data can be recovered from the signature - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - signRecover: boolean; - /** - * `CK_TRUE` if key supports unwrapping (i.e., can be used to unwrap other keys) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - unwrap: boolean; - /** - * `CK_TRUE` if key is extractable and can be wrapped - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Attribute cannot be changed once set to `CK_FALSE`. It becomes a read only attribute. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - extractable: boolean; - /** - * `CK_TRUE` if key has always had the `CKA_SENSITIVE` attribute set to `CK_TRUE` - * - Must not be specified when object is created with `C_CreateObject`. - * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. - * - Must not be specified when object is unwrapped with `C_UnwrapKey`. - */ - alwaysSensitive: boolean; - /** - * `CK_TRUE` if key has never had the `CKA_EXTRACTABLE` attribute set to `CK_TRUE` - * - Must not be specified when object is created with `C_CreateObject`. - * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. - * - Must not be specified when object is unwrapped with `C_UnwrapKey`. - */ - neverExtractable: boolean; - /** - * `CK_TRUE` if the key can only be wrapped with a wrapping key - * that has `CKA_TRUSTED` set to `CK_TRUE`. Default is `CK_FALSE`. - * - Attribute cannot be changed once set to `CK_TRUE`. It becomes a read only attribute. - */ - wrapTrusted: boolean; - /** - * For wrapping keys. The attribute template to apply to any keys unwrapped - * using this wrapping key. Any user supplied template is applied after this template - * as if the object has already been created. - */ - template: void; - alwaysAuthenticate: boolean; + enum CertificateCategory { + Unspecified = 0, + TokenUser = 1, + Authority = 2, + OtherEntity = 3, } - /** - * Public key objects (object class CKO_PUBLIC_KEY) hold public keys - */ - class PublicKey extends Key { - /** - * DER-encoding of the key subject name (default empty) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - */ - subject: Buffer; - /** - * `CK_TRUE` if key supports encryption - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - encrypt: boolean; - /** - * `CK_TRUE` if key supports verification where the signature is an appendix to the data - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - verify: boolean; - /** - * `CK_TRUE` if key supports verification where the data is recovered from the signature - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - verifyRecover: boolean; - /** - * `CK_TRUE` if key supports wrapping (i.e., can be used to wrap other keys) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - wrap: boolean; - /** - * The key can be trusted for the application that it was created. - * - The wrapping key can be used to wrap keys with `CKA_WRAP_WITH_TRUSTED` set to `CK_TRUE`. - * - Can only be set to CK_TRUE by the SO user. - */ - trusted: boolean; - /** - * For wrapping keys. The attribute template to match against any keys wrapped using this wrapping key. - * Keys that do not match cannot be wrapped. - */ - template: void; + enum KeyType { + RSA, + DSA, + DH, + ECDSA, + EC, + X9_42_DH, + KEA, + GENERIC_SECRET, + RC2, + RC4, + DES, + DES2, + DES3, + CAST, + CAST3, + CAST5, + CAST128, + RC5, + IDEA, + SKIPJACK, + BATON, + JUNIPER, + CDMF, + AES, + GOSTR3410, + GOSTR3411, + GOST28147, + BLOWFISH, + TWOFISH, + SECURID, + HOTP, + ACTI, + CAMELLIA, + ARIA, } - /** - * Secret key objects (object class `CKO_SECRET_KEY`) hold secret keys. - */ - class SecretKey extends Key { - /** - * `CK_TRUE` if key is sensitive - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Attribute cannot be changed once set to `CK_TRUE`. It becomes a read only attribute. - */ - sensitive: boolean; - /** - * `CK_TRUE` if key supports encryption - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - encrypt: boolean; - /** - * `CK_TRUE` if key supports decryption - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - decrypt: boolean; - /** - * `CK_TRUE` if key supports verification (i.e., of authentication codes) where the signature is an appendix to the data - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - verify: boolean; - /** - * `CK_TRUE` if key supports signatures (i.e., authentication codes) where the signature is an appendix to the data - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - sign: boolean; - /** - * `CK_TRUE` if key supports wrapping (i.e., can be used to wrap other keys) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - wrap: boolean; - /** - * `CK_TRUE` if key supports unwrapping (i.e., can be used to unwrap other keys) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - unwrap: boolean; - /** - * `CK_TRUE` if key is extractable and can be wrapped - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Attribute cannot be changed once set to `CK_FALSE`. It becomes a read only attribute. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - extractable: boolean; - /** - * `CK_TRUE` if key has always had the `CKA_SENSITIVE` attribute set to `CK_TRUE` - * - Must not be specified when object is created with `C_CreateObject`. - * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. - * - Must not be specified when object is unwrapped with `C_UnwrapKey`. - */ - alwaysSensitive: boolean; - /** - * `CK_TRUE` if key has never had the `CKA_EXTRACTABLE` attribute set to `CK_TRUE` - * - Must not be specified when object is created with `C_CreateObject`. - * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. - * - Must not be specified when object is unwrapped with `C_UnwrapKey`. - */ - neverExtractable: boolean; - /** - * Key checksum - */ - checkValue: Buffer; - /** - * `CK_TRUE` if the key can only be wrapped with a wrapping key - * that has `CKA_TRUSTED` set to `CK_TRUE`. Default is `CK_FALSE`. - * - Attribute cannot be changed once set to `CK_TRUE`. It becomes a read only attribute. - */ - wrapTrusted: boolean; - /** - * The wrapping key can be used to wrap keys with `CKA_WRAP_WITH_TRUSTED` set to `CK_TRUE`. - * - Can only be set to CK_TRUE by the SO user. - */ - trusted: boolean; - /** - * For wrapping keys. - * The attribute template to match against any keys wrapped using this wrapping key. - * Keys that do not match cannot be wrapped. - */ - wrapTemplate: void; - /** - * For wrapping keys. - * The attribute template to apply to any keys unwrapped using this wrapping key. - * Any user supplied template is applied after this template as if the object has already been created. - */ - unwrapTemplate: void; + enum KeyGenMechanism { + AES, + RSA, + RSA_X9_31, + DSA, + DH_PKCS, + DH_X9_42, + GOSTR3410, + GOST28147, + RC2, + RC4, + DES, + DES2, + SECURID, + ACTI, + CAST, + CAST3, + CAST5, + CAST128, + RC5, + IDEA, + GENERIC_SECRET, + SSL3_PRE_MASTER, + CAMELLIA, + ARIA, + SKIPJACK, + KEA, + BATON, + ECDSA, + EC, + JUNIPER, + TWOFISH, } + enum MechanismFlag { + /** + * `True` if the mechanism is performed by the device; `false` if the mechanism is performed in software + */ + HW, + /** + * `True` if the mechanism can be used with encrypt function + */ + ENCRYPT, + /** + * `True` if the mechanism can be used with decrypt function + */ + DECRYPT, + /** + * `True` if the mechanism can be used with digest function + */ + DIGEST, + /** + * `True` if the mechanism can be used with sign function + */ + SIGN, + /** + * `True` if the mechanism can be used with sign recover function + */ + SIGN_RECOVER, + /** + * `True` if the mechanism can be used with verify function + */ + VERIFY, + /** + * `True` if the mechanism can be used with verify recover function + */ + VERIFY_RECOVER, + /** + * `True` if the mechanism can be used with geberate function + */ + GENERATE, + /** + * `True` if the mechanism can be used with generate key pair function + */ + GENERATE_KEY_PAIR, + /** + * `True` if the mechanism can be used with wrap function + */ + WRAP, + /** + * `True` if the mechanism can be used with unwrap function + */ + UNWRAP, + /** + * `True` if the mechanism can be used with derive function + */ + DERIVE, + } - interface ISlotInfo { - slotDescription: string; - manufacturerID: string; - flags: number; - hardwareVersion: IVersion; - firmwareVersion: IVersion; + enum MechanismEnum { + RSA_PKCS_KEY_PAIR_GEN, + RSA_PKCS, + RSA_9796, + RSA_X_509, + MD2_RSA_PKCS, + MD5_RSA_PKCS, + SHA1_RSA_PKCS, + RIPEMD128_RSA_PKCS, + RIPEMD160_RSA_PKCS, + RSA_PKCS_OAEP, + RSA_X9_31_KEY_PAIR_GEN, + RSA_X9_31, + SHA1_RSA_X9_31, + RSA_PKCS_PSS, + SHA1_RSA_PKCS_PSS, + DSA_KEY_PAIR_GEN, + DSA, + DSA_SHA1, + DSA_SHA224, + DSA_SHA256, + DSA_SHA384, + DSA_SHA512, + DH_PKCS_KEY_PAIR_GEN, + DH_PKCS_DERIVE, + X9_42_DH_KEY_PAIR_GEN, + X9_42_DH_DERIVE, + X9_42_DH_HYBRID_DERIVE, + X9_42_MQV_DERIVE, + SHA256_RSA_PKCS, + SHA384_RSA_PKCS, + SHA512_RSA_PKCS, + SHA256_RSA_PKCS_PSS, + SHA384_RSA_PKCS_PSS, + SHA512_RSA_PKCS_PSS, + SHA224_RSA_PKCS, + SHA224_RSA_PKCS_PSS, + RC2_KEY_GEN, + RC2_ECB, + RC2_CBC, + RC2_MAC, + RC2_MAC_GENERAL, + RC2_CBC_PAD, + RC4_KEY_GEN, + RC4, + DES_KEY_GEN, + DES_ECB, + DES_CBC, + DES_MAC, + DES_MAC_GENERAL, + DES_CBC_PAD, + DES2_KEY_GEN, + DES3_KEY_GEN, + DES3_ECB, + DES3_CBC, + DES3_MAC, + DES3_MAC_GENERAL, + DES3_CBC_PAD, + CDMF_KEY_GEN, + CDMF_ECB, + CDMF_CBC, + CDMF_MAC, + CDMF_MAC_GENERAL, + CDMF_CBC_PAD, + DES_OFB64, + DES_OFB8, + DES_CFB64, + DES_CFB8, + MD2, + MD2_HMAC, + MD2_HMAC_GENERAL, + MD5, + MD5_HMAC, + MD5_HMAC_GENERAL, + SHA1, + SHA, + SHA_1, + SHA_1_HMAC, + SHA_1_HMAC_GENERAL, + RIPEMD128, + RIPEMD128_HMAC, + RIPEMD128_HMAC_GENERAL, + RIPEMD160, + RIPEMD160_HMAC, + RIPEMD160_HMAC_GENERAL, + SHA256, + SHA256_HMAC, + SHA256_HMAC_GENERAL, + SHA224, + SHA224_HMAC, + SHA224_HMAC_GENERAL, + SHA384, + SHA384_HMAC, + SHA384_HMAC_GENERAL, + SHA512, + SHA512_HMAC, + SHA512_HMAC_GENERAL, + SECURID_KEY_GEN, + SECURID, + HOTP_KEY_GEN, + HOTP, + ACTI, + ACTI_KEY_GEN, + CAST_KEY_GEN, + CAST_ECB, + CAST_CBC, + CAST_MAC, + CAST_MAC_GENERAL, + CAST_CBC_PAD, + CAST3_KEY_GEN, + CAST3_ECB, + CAST3_CBC, + CAST3_MAC, + CAST3_MAC_GENERAL, + CAST3_CBC_PAD, + CAST5_KEY_GEN, + CAST128_KEY_GEN, + CAST5_ECB, + CAST128_ECB, + CAST5_CBC, + CAST128_CBC, + CAST5_MAC, + CAST128_MAC, + CAST5_MAC_GENERAL, + CAST128_MAC_GENERAL, + CAST5_CBC_PAD, + CAST128_CBC_PAD, + RC5_KEY_GEN, + RC5_ECB, + RC5_CBC, + RC5_MAC, + RC5_MAC_GENERAL, + RC5_CBC_PAD, + IDEA_KEY_GEN, + IDEA_ECB, + IDEA_CBC, + IDEA_MAC, + IDEA_MAC_GENERAL, + IDEA_CBC_PAD, + GENERIC_SECRET_KEY_GEN, + CONCATENATE_BASE_AND_KEY, + CONCATENATE_BASE_AND_DATA, + CONCATENATE_DATA_AND_BASE, + XOR_BASE_AND_DATA, + EXTRACT_KEY_FROM_KEY, + SSL3_PRE_MASTER_KEY_GEN, + SSL3_MASTER_KEY_DERIVE, + SSL3_KEY_AND_MAC_DERIVE, + SSL3_MASTER_KEY_DERIVE_DH, + TLS_PRE_MASTER_KEY_GEN, + TLS_MASTER_KEY_DERIVE, + TLS_KEY_AND_MAC_DERIVE, + TLS_MASTER_KEY_DERIVE_DH, + TLS_PRF, + SSL3_MD5_MAC, + SSL3_SHA1_MAC, + MD5_KEY_DERIVATION, + MD2_KEY_DERIVATION, + SHA1_KEY_DERIVATION, + SHA256_KEY_DERIVATION, + SHA384_KEY_DERIVATION, + SHA512_KEY_DERIVATION, + SHA224_KEY_DERIVATION, + PBE_MD2_DES_CBC, + PBE_MD5_DES_CBC, + PBE_MD5_CAST_CBC, + PBE_MD5_CAST3_CBC, + PBE_MD5_CAST5_CBC, + PBE_MD5_CAST128_CBC, + PBE_SHA1_CAST5_CBC, + PBE_SHA1_CAST128_CBC, + PBE_SHA1_RC4_128, + PBE_SHA1_RC4_40, + PBE_SHA1_DES3_EDE_CBC, + PBE_SHA1_DES2_EDE_CBC, + PBE_SHA1_RC2_128_CBC, + PBE_SHA1_RC2_40_CBC, + PKCS5_PBKD2, + PBA_SHA1_WITH_SHA1_HMAC, + WTLS_PRE_MASTER_KEY_GEN, + WTLS_MASTER_KEY_DERIVE, + WTLS_MASTER_KEY_DERIVE_DH_ECC, + WTLS_PRF, + WTLS_SERVER_KEY_AND_MAC_DERIVE, + WTLS_CLIENT_KEY_AND_MAC_DERIVE, + KEY_WRAP_LYNKS, + KEY_WRAP_SET_OAEP, + CAMELLIA_KEY_GEN, + CAMELLIA_ECB, + CAMELLIA_CBC, + CAMELLIA_MAC, + CAMELLIA_MAC_GENERAL, + CAMELLIA_CBC_PAD, + CAMELLIA_ECB_ENCRYPT_DATA, + CAMELLIA_CBC_ENCRYPT_DATA, + CAMELLIA_CTR, + ARIA_KEY_GEN, + ARIA_ECB, + ARIA_CBC, + ARIA_MAC, + ARIA_MAC_GENERAL, + ARIA_CBC_PAD, + ARIA_ECB_ENCRYPT_DATA, + ARIA_CBC_ENCRYPT_DATA, + SKIPJACK_KEY_GEN, + SKIPJACK_ECB64, + SKIPJACK_CBC64, + SKIPJACK_OFB64, + SKIPJACK_CFB64, + SKIPJACK_CFB32, + SKIPJACK_CFB16, + SKIPJACK_CFB8, + SKIPJACK_WRAP, + SKIPJACK_PRIVATE_WRAP, + SKIPJACK_RELAYX, + KEA_KEY_PAIR_GEN, + KEA_KEY_DERIVE, + FORTEZZA_TIMESTAMP, + BATON_KEY_GEN, + BATON_ECB128, + BATON_ECB96, + BATON_CBC128, + BATON_COUNTER, + BATON_SHUFFLE, + BATON_WRAP, + ECDSA_KEY_PAIR_GEN, + EC_KEY_PAIR_GEN, + ECDSA, + ECDSA_SHA1, + ECDSA_SHA224, + ECDSA_SHA256, + ECDSA_SHA384, + ECDSA_SHA512, + ECDH1_DERIVE, + ECDH1_COFACTOR_DERIVE, + ECMQV_DERIVE, + JUNIPER_KEY_GEN, + JUNIPER_ECB128, + JUNIPER_CBC128, + JUNIPER_COUNTER, + JUNIPER_SHUFFLE, + JUNIPER_WRAP, + FASTHASH, + AES_KEY_GEN, + AES_ECB, + AES_CBC, + AES_MAC, + AES_MAC_GENERAL, + AES_CBC_PAD, + AES_CTR, + AES_CMAC, + AES_CMAC_GENERAL, + BLOWFISH_KEY_GEN, + BLOWFISH_CBC, + TWOFISH_KEY_GEN, + TWOFISH_CBC, + AES_GCM, + AES_CCM, + AES_KEY_WRAP, + AES_KEY_WRAP_PAD, + DES_ECB_ENCRYPT_DATA, + DES_CBC_ENCRYPT_DATA, + DES3_ECB_ENCRYPT_DATA, + DES3_CBC_ENCRYPT_DATA, + AES_ECB_ENCRYPT_DATA, + AES_CBC_ENCRYPT_DATA, + GOSTR3410_KEY_PAIR_GEN, + GOSTR3410, + GOSTR3410_WITH_GOSTR3411, + GOSTR3410_KEY_WRAP, + GOSTR3410_DERIVE, + GOSTR3411, + GOSTR3411_HMAC, + GOST28147_KEY_GEN, + GOST28147_ECB, + GOST28147, + GOST28147_MAC, + GOST28147_KEY_WRAP, + DSA_PARAMETER_GEN, + DH_PKCS_PARAMETER_GEN, + X9_42_DH_PARAMETER_GEN, + VENDOR_DEFINED, + } + + enum MechParams { + AesCBC = 1, + AesCCM = 2, + AesGCM = 3, + RsaOAEP = 4, + RsaPSS = 5, + EcDH = 6, + } + + enum SessionFlag { + /** + * `True` if the session is read/write; `false` if the session is read-only + */ + RW_SESSION, + /** + * This flag is provided for backward compatibility, and should always be set to `true` + */ + SERIAL_SESSION + } + + enum UserType { + /** + * Security Officer + */ + SO, + /** + * User + */ + USER, + /** + * Context specific + */ + CONTEXT_SPECIFIC } enum SlotFlag { @@ -2106,205 +2157,7 @@ declare module "graphene-pk11" { /** * True if the slot is a hardware slot, as opposed to a software slot implementing a "soft token" */ - HW_SLOT, - } - - interface IVersion { - major: number; - minor: number; - } - interface IModuleInfo { - cryptokiVersion: IVersion; - manufacturerID: string; - flags: number; - libraryDescription: string; - libraryVersion: IVersion; - } - - class Collection { - protected items_: Array; - protected classType: any; - protected lib: Pkcs11; - constructor(items: Array, lib: Pkcs11, classType: any); - /** - * returns length of collection - */ - length: number; - /** - * returns item from collection by index - * @param {number} index of element in collection `[0..n]` - */ - items(index: number): T; - } - - enum SessionOpenFlag { - /** - * session is r/w - */ - RW_SESSION, - /** - * no parallel - */ - SERIAL_SESSION, - } - enum SessionFlag { - /** - * `True` if the session is read/write; `false` if the session is read-only - */ - RW_SESSION, - /** - * This flag is provided for backward compatibility, and should always be set to `true` - */ - SERIAL_SESSION, - } - enum UserType { - /** - * Security Officer - */ - SO, - /** - * User - */ - USER, - /** - * Context specific - */ - CONTEXT_SPECIFIC, - } - interface IKeyPair { - privateKey: PrivateKey; - publicKey: PublicKey; - } - /** - * provides information about a session - */ - class Session extends HandleObject { - constructor(handle: number, slot: Slot, lib: Pkcs11); - slot: Slot; - /** - * the state of the session - */ - state: number; - /** - * bit flags that define the type of session - */ - flags: number; - /** - * an error code defined by the cryptographic device. Used for errors not covered by Cryptoki - */ - deviceError: number; - protected getInfo(): void; - /** - * closes a session between an application and a token - */ - close(): void; - /** - * initializes the normal user's PIN - * @param {string} pin the normal user's PIN - */ - initPin(pin: string): void; - /** - * modifies the PIN of the user who is logged in - * @param {string} oldPin - * @param {string} newPin - */ - setPin(oldPin: string, newPin: string): void; - /** - * obtains a copy of the cryptographic operations state of a session, encoded as a string of bytes - */ - getOperationState(): Buffer; - /** - * restores the cryptographic operations state of a session - * from a string of bytes obtained with getOperationState - * @param {Buffer} state the saved state - * @param {number} encryptionKey holds key which will be used for an ongoing encryption - * or decryption operation in the restored session - * (or 0 if no encryption or decryption key is needed, - * either because no such operation is ongoing in the stored session - * or because all the necessary key information is present in the saved state) - * @param {number} authenticationKey holds a handle to the key which will be used for an ongoing signature, - * MACing, or verification operation in the restored session - * (or 0 if no such key is needed, either because no such operation is ongoing in the stored session - * or because all the necessary key information is present in the saved state) - */ - setOperationState(state: Buffer, encryptionKey?: number, authenticationKey?: number): void; - /** - * logs a user into a token - * @param {string} pin the user's PIN. - * - This standard allows PIN values to contain any valid `UTF8` character, - * but the token may impose subset restrictions - * @param {} userType the user type. Default is `USER` - */ - login(pin: string, userType?: UserType): void; - /** - * logs a user out from a token - */ - logout(): void; - /** - * creates a new object - * - Only session objects can be created during a read-only session. - * - Only public objects can be created unless the normal user is logged in. - * @param {ITemplate} template the object's template - */ - create(template: ITemplate): SessionObject; - /** - * removes all session objects matched to template - * - if template is null, removes all session objects - * - returns a number of destroied session objects - * @param {ITemplate} template template - */ - destroy(template: ITemplate): number; - /** - * @param {SessionObject} object - */ - destroy(object: SessionObject): number; - destroy(): number; - /** - * removes all session objects - * - returns a number of destroied session objects - */ - clear(): number; - /** - * returns a collection of session objects mached to template - * @param template template - * @param callback optional callback function wich is called for each founded object - * - if callback function returns false, it breaks find function. - */ - find(callback?: (obj: SessionObject) => void): SessionObjectCollection; - find(template: ITemplate, callback?: (obj: SessionObject) => void): SessionObjectCollection; - /** - * Returns object from session by handle - * @param {number} handle handle of object - * @returns T - */ - getObject(handle: number): T; - /** - * generates a secret key or set of domain parameters, creating a new object. - * @param mechanism generation mechanism - * @param template template for the new key or set of domain parameters - */ - generateKey(mechanism: MechanismType, template?: ITemplate): SecretKey; - generateKey(mechanism: MechanismType, template: ITemplate, callback: (err: Error, key: SecretKey) => void): void; - generateKeyPair(mechanism: MechanismType, publicTemplate: ITemplate, privateTemplate: ITemplate): IKeyPair; - createSign(alg: MechanismType, key: Key): Sign; - createVerify(alg: MechanismType, key: Key): Verify; - createCipher(alg: MechanismType, key: Key): Cipher; - createDecipher(alg: MechanismType, key: Key): Decipher; - createDigest(alg: MechanismType): Digest; - wrapKey(alg: MechanismType, wrappingKey: Key, key: Key): Buffer; - unwrapKey(alg: MechanismType, unwrappingKey: Key, wrappedKey: Buffer, template: ITemplate): Key; - /** - * derives a key from a base key, creating a new key object - * @param {MechanismType} alg key deriv. mech - * @param {Key} baseKey base key - * @param {ITemplate} template new key template - */ - deriveKey(alg: MechanismType, baseKey: Key, template: ITemplate): SecretKey; - /** - * generates random data - * @param {number} size \# of bytes to generate - */ - generateRandom(size: number): Buffer; + HW_SLOT } enum TokenFlag { @@ -2325,139 +2178,25 @@ declare module "graphene-pk11" { SO_PIN_COUNT_LOW, SO_PIN_FINAL_TRY, SO_PIN_LOCKED, - SO_PIN_TO_BE_CHANGED, - } - class Token extends HandleObject { - /** - * application-defined label, assigned during token initialization. - * - Must be padded with the blank character (' '). - * - Should __not__ be null-terminated. - */ - label: string; - /** - * ID of the device manufacturer. - * - Must be padded with the blank character (' '). - * - Should __not__ be null-terminated. - */ - manufacturerID: string; - /** - * model of the device. - * - Must be padded with the blank character (' '). - * - Should __not__ be null-terminated. - */ - model: string; - /** - * character-string serial number of the device. - * - Must be padded with the blank character (' '). - * - Should __not__ be null-terminated. - */ - serialNumber: string; - /** - * bit flags indicating capabilities and status of the device - */ - flags: number; - /** - * maximum number of sessions that can be opened with the token at one time by a single application - */ - maxSessionCount: number; - /** - * number of sessions that this application currently has open with the token - */ - sessionCount: number; - /** - * maximum number of read/write sessions that can be opened - * with the token at one time by a single application - */ - maxRwSessionCount: number; - /** - * number of read/write sessions that this application currently has open with the token - */ - rwSessionCount: number; - /** - * maximum length in bytes of the PIN - */ - maxPinLen: number; - /** - * minimum length in bytes of the PIN - */ - minPinLen: number; - /** - * the total amount of memory on the token in bytes in which public objects may be stored - */ - totalPublicMemory: number; - /** - * the amount of free (unused) memory on the token in bytes for public objects - */ - freePublicMemory: number; - /** - * the total amount of memory on the token in bytes in which private objects may be stored - */ - totalPrivateMemory: number; - /** - * the amount of free (unused) memory on the token in bytes for private objects - */ - freePrivateMemory: number; - /** - * version number of hardware - */ - hardwareVersion: IVersion; - /** - * version number of firmware - */ - firmwareVersion: IVersion; - /** - * current time as a character-string of length 16, - * represented in the format YYYYMMDDhhmmssxx - */ - utcTime: Date; - constructor(handle: number, lib: Pkcs11); - protected getInfo(): void; + SO_PIN_TO_BE_CHANGED } - class Slot extends HandleObject implements ISlotInfo { - slotDescription: string; - manufacturerID: string; - flags: number; - hardwareVersion: IVersion; - firmwareVersion: IVersion; - module: Module; - constructor(handle: number, module: Module, lib: Pkcs11); - protected getInfo(): void; - getToken(): Token; - /** - * returns list of `MechanismInfo` - */ - getMechanisms(): MechanismCollection; - /** - * initializes a token - * @param {string} pin the SO's initial PIN - * @param {string} label label of the token - */ - initToken(pin: string, label: string): void; - /** - * opens a session between an application and a token in a particular slot - * @parsm flags indicates the type of session - */ - open(flags?: number): Session; - /** - * closes all sessions an application has with a token - */ - closeAll(): void; + enum JavaMIDP { + Unspecified, + Manufacturer, + Operator, + ThirdParty } - class SlotCollection extends Collection { - module: Module; - items(index: number): Slot; - constructor(items: Array, module: Module, lib: Pkcs11, classType?: any); - } + // ========== Module ========== - class Module extends BaseObject implements IModuleInfo { + class Module implements graphene.BaseObject { libFile: string; libName: string; /** * Cryptoki interface version */ - cryptokiVersion: IVersion; + cryptokiVersion: pkcs11.Version; /** * blank padded manufacturer ID */ @@ -2473,9 +2212,10 @@ declare module "graphene-pk11" { /** * version of library */ - libraryVersion: IVersion; - constructor(lib: Pkcs11); - protected getInfo(): void; + libraryVersion: pkcs11.Version; + + constructor(lib: pkcs11.PKCS11); + /** * initializes the Cryptoki library */ @@ -2489,231 +2229,17 @@ declare module "graphene-pk11" { * @param {number} index index of an element in collection * @param {number} tokenPresent only slots with tokens. Default `True` */ - getSlots(index: number, tokenPresent?: boolean): Slot; + getSlots(index: number, tokenPresent?: boolean): graphene.Slot; /** * @param {number} tokenPresent only slots with tokens. Default `True` */ - getSlots(tokenPresent?: boolean): SlotCollection; + getSlots(tokenPresent?: boolean): graphene.SlotCollection; /** * loads pkcs11 lib + * @param libFile path to PKCS11 library + * @param libName name of PKCS11 library */ static load(libFile: string, libName?: string): Module; } - class Cipher { - session: Session; - lib: Pkcs11; - constructor(session: Session, alg: MechanismType, key: Key, lib: Pkcs11); - protected init(alg: MechanismType, key: Key): void; - update(text: string): Buffer; - update(data: Buffer): Buffer; - final(): Buffer; - } - - class Decipher { - session: Session; - lib: Pkcs11; - constructor(session: Session, alg: MechanismType, key: Key, lib: Pkcs11); - protected init(alg: MechanismType, key: Key): void; - update(text: string): Buffer; - update(data: Buffer): Buffer; - final(): Buffer; - } - - class Digest { - session: Session; - lib: Pkcs11; - constructor(session: Session, alg: MechanismType, lib: Pkcs11); - protected init(alg: MechanismType): void; - update(text: string): void; - update(data: Buffer): void; - final(): Buffer; - } - - class Sign { - session: Session; - lib: Pkcs11; - constructor(session: Session, alg: MechanismType, key: Key, lib: Pkcs11); - protected init(alg: MechanismType, key: Key): void; - update(text: string): void; - update(data: Buffer): void; - final(): Buffer; - } - - class Verify { - session: Session; - lib: Pkcs11; - constructor(session: Session, alg: MechanismType, key: Key, lib: Pkcs11); - protected init(alg: MechanismType, key: Key): void; - update(text: string): void; - update(data: Buffer): void; - final(signature: Buffer): boolean; - } - - /** - * - * EC - * - */ - - /** - * EcKdf is used to indicate the Key Derivation Function (KDF) - * applied to derive keying data from a shared secret. - * The key derivation function will be used by the EC key agreement schemes. - */ - enum EcKdf { - NULL, - SHA1, - SHA224, - SHA256, - SHA384, - SHA512, - } - - class EcdhParams implements IParams { - /** - * key derivation function used on the shared secret value - */ - kdf: EcKdf; - /** - * some data shared between the two parties - */ - sharedData: Buffer; - /** - * other party's EC public key value - */ - publicData: Buffer; - /** - * @param {EcKdf} kdf key derivation function used on the shared secret value - * @param {Buffer=null} sharedData some data shared between the two parties - * @param {Buffer=null} publicData other party's EC public key value - */ - constructor(kdf: EcKdf, sharedData?: Buffer, publicData?: Buffer); - toCKI(): Buffer; - } - - export interface INamedCurve { - name: string; - oid: string; - value: Buffer; - size: number; - } - - class NamedCurve { - static getByName(name: string): INamedCurve; - static getByOid(oid: string): INamedCurve; - } - - /** - * - * AES - * - */ - - class AesCbcParams implements IParams { - /** - * initialization vector - * - must have a fixed size of 16 bytes - */ - iv: Buffer; - /** - * the data - */ - data: Buffer; - constructor(iv: Buffer, data: Buffer); - toCKI(): Buffer; - } - - class AesCcmParams implements IParams { - /** - * length of the data where 0 <= dataLength < 2^8L - */ - dataLength: number; - /** - * the nonce - */ - nonce: Buffer; - /** - * the additional authentication data - * - This data is authenticated but not encrypted - */ - aad: Buffer; - /** - * length of authentication tag (output following cipher text) in bits. - * - Can be any value between 0 and 128 - */ - macLength: number; - constructor(dataLength: number, nonce: Buffer, aad?: Buffer, macLength?: number); - toCKI(): Buffer; - } - - class AesGcmParams implements IParams { - /** - * initialization vector - * - The length of the initialization vector can be any number between 1 and 256. - * 96-bit (12 byte) IV values can be processed more efficiently, - * so that length is recommended for situations in which efficiency is critical. - */ - iv: Buffer; - /** - * pointer to additional authentication data. - * This data is authenticated but not encrypted. - */ - aad: Buffer; - /** - * length of authentication tag (output following cipher text) in bits. - * Can be any value between 0 and 128. Default 128 - */ - tagBits: number; - constructor(iv: Buffer, aad?: Buffer, tagBits?: number); - toCKI(): Buffer; - } - - /** - * - * RSA - * - */ - - enum RsaMgf { - MGF1_SHA1, - MGF1_SHA224, - MGF1_SHA256, - MGF1_SHA384, - MGF1_SHA512, - } - - class RsaOaepParams implements IParams { - hashAlgorithm: MechanismEnum; - mgf: RsaMgf; - source: number; - sourceData: Buffer; - constructor(hashAlg?: MechanismEnum, mgf?: RsaMgf, sourceData?: Buffer); - toCKI(): Buffer; - } - - class RsaPssParams implements IParams { - /** - * hash algorithm used in the PSS encoding; - * - if the signature mechanism does not include message hashing, - * then this value must be the mechanism used by the application to generate - * the message hash; - * - if the signature mechanism includes hashing, - * then this value must match the hash algorithm indicated - * by the signature mechanism - */ - hashAlgorithm: MechanismEnum; - /** - * mask generation function to use on the encoded block - */ - mgf: RsaMgf; - /** - * length, in bytes, of the salt value used in the PSS encoding; - * - typical values are the length of the message hash and zero - */ - saltLength: number; - constructor(hashAlg?: MechanismEnum, mgf?: RsaMgf, saltLen?: number); - toCKI(): Buffer; - } - } \ No newline at end of file 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/handlebars/handlebars.d.ts b/handlebars/handlebars.d.ts index 0af3d6f6e7..96b0491040 100644 --- a/handlebars/handlebars.d.ts +++ b/handlebars/handlebars.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Handlebars v3.0.3 +// Type definitions for Handlebars v4.0.5 // Project: http://handlebarsjs.com/ // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -15,14 +15,25 @@ declare namespace Handlebars { export function Exception(message: string): void; export function log(level: number, obj: any): void; export function parse(input: string): hbs.AST.Program; - export function compile(input: any, options?: any): HandlebarsTemplateDelegate; + export function compile(input: any, options?: CompileOptions): HandlebarsTemplateDelegate; + export function precompile(input: any, options?: PrecompileOptions): TemplateSpecification; + export function template(precompilation: TemplateSpecification): HandlebarsTemplateDelegate; + + export function create(): typeof Handlebars; export var SafeString: typeof hbs.SafeString; + export var escapeExpression: typeof hbs.Utils.escapeExpression; export var Utils: typeof hbs.Utils; export var logger: Logger; export var templates: HandlebarsTemplates; export var helpers: any; + export function registerDecorator(name: string, fn: Function): void; + export function registerDecorator(obj: {[name: string] : Function}): void; + export function unregisterDecorator(name: string): void; + + export function noConflict(): typeof Handlebars; + export module AST { export var helpers: hbs.AST.helpers; } @@ -32,6 +43,9 @@ declare namespace Handlebars { Program(program: hbs.AST.Program): void; BlockStatement(block: hbs.AST.BlockStatement): void; PartialStatement(partial: hbs.AST.PartialStatement): void; + PartialBlockStatement(partial: hbs.AST.PartialBlockStatement): void; + DecoratorBlock(decorator: hbs.AST.DecoratorBlock): void; + Decorator(decorator: hbs.AST.Decorator): void; MustacheStatement(mustache: hbs.AST.MustacheStatement): void; ContentStatement(content: hbs.AST.ContentStatement): void; CommentStatement(comment?: hbs.AST.CommentStatement): void; @@ -52,6 +66,9 @@ declare namespace Handlebars { Program(program: hbs.AST.Program): void; BlockStatement(block: hbs.AST.BlockStatement): void; PartialStatement(partial: hbs.AST.PartialStatement): void; + PartialBlockStatement(partial: hbs.AST.PartialBlockStatement): void; + DecoratorBlock(decorator: hbs.AST.DecoratorBlock): void; + Decorator(decorator: hbs.AST.Decorator): void; MustacheStatement(mustache: hbs.AST.MustacheStatement): void; ContentStatement(content: hbs.AST.ContentStatement): void; CommentStatement(comment?: hbs.AST.CommentStatement): void; @@ -81,6 +98,37 @@ interface HandlebarsTemplates { [index: string]: HandlebarsTemplateDelegate; } +interface TemplateSpecification { + +} + +interface CompileOptions { + data?: boolean; + compat?: boolean; + knownHelpers?: { + helperMissing?: boolean; + blockHelperMissing?: boolean; + each?: boolean; + if?: boolean; + unless?: boolean; + with?: boolean; + log?: boolean; + lookup?: boolean; + } + knownHelpersOnly?: boolean; + noEscape?: boolean; + strict?: boolean; + assumeObjects?: boolean; + preventIndent?: boolean; + ignoreStandalone?: boolean; + explicitPartialContext?: boolean; +} + +interface PrecompileOptions extends CompileOptions { + srcName?: string; + destName?: string; +} + declare namespace hbs { class SafeString { constructor(str: string); @@ -89,6 +137,12 @@ declare namespace hbs { namespace Utils { function escapeExpression(str: string): string; + function createFrame(obj: Object): Object; + function isEmpty(obj: any) : boolean; + function extend(obj: any, ...source: any[]): any; + function toString(obj: any): string; + function isArray(obj: any): boolean; + function isFunction(obj: any): boolean; } } @@ -137,6 +191,8 @@ declare namespace hbs { strip: StripFlags; } + interface Decorator extends MustacheStatement { } + interface BlockStatement extends Statement { path: PathExpression; params: Expression[]; @@ -148,6 +204,8 @@ declare namespace hbs { closeStrip: StripFlags; } + interface DecoratorBlock extends BlockStatement { } + interface PartialStatement extends Statement { name: PathExpression | SubExpression; params: Expression[]; @@ -156,6 +214,15 @@ declare namespace hbs { strip: StripFlags; } + interface PartialBlockStatement extends Statement { + name: PathExpression | SubExpression; + params: Expression[], + hash: Hash, + program: Program, + openStrip: StripFlags, + closeStrip: StripFlags + } + interface ContentStatement extends Statement { value: string; original: StripFlags; 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/hellosign-embedded/hellosign-embedded-tests.ts b/hellosign-embedded/hellosign-embedded-tests.ts new file mode 100644 index 0000000000..455171942e --- /dev/null +++ b/hellosign-embedded/hellosign-embedded-tests.ts @@ -0,0 +1,39 @@ +/// + +HelloSign.init('abc123'); + +// some options +HelloSign.open({ + url: 'http://example.org', + messageListener: (e: HelloSign.MessageEvent) => { + if (e.event === HelloSign.EVENT_SIGNED) { + console.log('signed'); + } + }, + uxVersion: 2 +}); + +// all options +HelloSign.open({ + url: 'http://example.org', + redirectUrl: 'https://github.com/DefinitelyTyped/DefinitelyTyped', + allowCancel: true, + messageListener: (e: HelloSign.MessageEvent) => { + if (e.event === HelloSign.EVENT_SIGNED) { + console.log('signed'); + } + }, + userCulture: HelloSign.CULTURES.EN_US, + debug: true, + skipDomainVerification: true, + container: document.getElementById('#hellosign-container'), + height: 1326, + hideHeader: true, + uxVersion: 2, + requester: 'hellosign@example.org', + whiteLabelingOptions: { + "page_background_color": "#f7f8f9" + } +}); + +HelloSign.close(); diff --git a/hellosign-embedded/hellosign-embedded.d.ts b/hellosign-embedded/hellosign-embedded.d.ts new file mode 100644 index 0000000000..f215dac6bc --- /dev/null +++ b/hellosign-embedded/hellosign-embedded.d.ts @@ -0,0 +1,193 @@ +// Type definitions for hellosign-embedded v1.0.3 +// Project: https://github.com/HelloFax/hellosign-embedded +// Definitions by: Brian Surowiec +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module HelloSign { + interface MessageEvent { + event: string; + } + + interface ClientCultures { + /** + * English (United States) + * + * @default en_US + */ + EN_US: string; + + /** + * French (France) + * + * @default fr_FR + */ + FR_FR: string; + + /** + * German (Germany) + * + * @default de_DE + */ + DE_DE: string; + + /** + * Swedish (Sweden) + * + * @default sv_SE + */ + SV_SE: string; + + /** + * Chinese (China) + * + * @default zh_CN + */ + ZH_CN: string; + + /** + * Danish (Denmark) + * + * @default da_DK + */ + DA_DK: string; + + /** + * Dutch (The Netherlands) + * @default nl_NL + */ + NL_NL: string; + + /** + * The available client UI cultures + */ + supportedCultures: string[]; + } + + interface OpenParameters { + /** + * The url to open in the child frame + */ + url?: string; + + /** + * Where to go after the signature is completed + */ + redirectUrl?: string; + + /** + * Whether a cancel button should be displayed + * + * @default true + */ + allowCancel?: boolean; + + /** + * A listener for X-window messages coming from the child frame + */ + messageListener?: (eventData: MessageEvent) => void; + + /** + * One of the HelloSign.CULTURES.supportedCultures + * + * @default HelloSign.CULTURES.EN_US + */ + userCulture?: string; + + /** + * When true, debugging statements will be written to the console + * + * @default false + */ + debug?: boolean; + + /** + * When true, domain verification step will be skipped if and only if the Signature Request was created with test_mode=1 + * + * @default false + */ + skipDomainVerification?: boolean; + + /** + * DOM element that will contain the iframe on the page (defaults to document.body) + */ + container?: Element; + + /** + * Height of the iFrame (only applicable when a container is specified) + */ + height?: number; + + /** + * When true, the header will be hidden. + * This is only functional for customers with embedded branding enabled. + * + * @default false + */ + hideHeader?: boolean; + + /** + * The version of the embedded user experience to display to signers (1 = legacy, 2 = responsive). + * This option is only honored if your account has accessed the API prior to Nov 14, 2015. + */ + uxVersion?: number; + + /** + * The email of the person issuing a signature request. + * Required for allowing 'Me + Others' requests + */ + requester?: string; + + /** + * An associative array to be used to customize the app's signer page + */ + whiteLabelingOptions?: Object; + } + + interface HelloSignStatic { + /** + * The available client UI cultures + */ + CULTURES: ClientCultures; + + /** + * The signature request was signed + * + * @default signature_request_signed + */ + EVENT_SIGNED: string; + + /** + * The user closed the iFrame before completing + * + * @default signature_request_canceled + */ + EVENT_CANCELED: string; + + /** + * An error occurred in the iFrame + * + * @default error + */ + EVENT_ERROR: string; + + /** + * Initialize using your HelloSign API client ID. + * + * @param appClientId The API client ID the request is for. + */ + init(appClientId: string): void; + + /** + * Open the signing window. + * + * @param params The options to use when opening the signing window. + */ + open(params: OpenParameters): void; + + /** + * Close the signing window. + */ + close(): void; + } +} + +declare var HelloSign: HelloSign.HelloSignStatic; diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index a338f19757..7185587190 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -3183,6 +3183,14 @@ interface HighchartsPointEvents { * @since 1.2.0 */ update?: (event: Event) => boolean|void; + /** + * Fires when the legend item belonging to the pie point (slice) is clicked. + * The this keyword refers to the point itself. One parameter, event, is passed to the function. + * This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. + * The default action is to toggle the visibility of the point. This can be prevented by calling event.preventDefault(). + */ + legendItemClick?: (event: Event) => boolean | void; + } interface HighchartsHalo { @@ -6053,7 +6061,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 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/inversify-inject-decorators/inversify-inject-decorators-tests.ts b/inversify-inject-decorators/inversify-inject-decorators-tests.ts new file mode 100644 index 0000000000..468bbaf763 --- /dev/null +++ b/inversify-inject-decorators/inversify-inject-decorators-tests.ts @@ -0,0 +1,214 @@ +/// +/// + +import getDecorators from "inversify-inject-decorators"; +import { Kernel, injectable, tagged, named } from "inversify"; + +module lazyInject { + + let kernel = new Kernel(); + let { lazyInject } = getDecorators(kernel); + let TYPES = { Weapon: "Weapon" }; + + interface Weapon { + name: string; + durability: number; + use(): void; + } + + @injectable() + class Sword implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Sword"; + } + public use() { + this.durability = this.durability - 10; + } + } + + class Warrior { + @lazyInject(TYPES.Weapon) + public weapon: Weapon; + } + + kernel.bind(TYPES.Weapon).to(Sword); + + let warrior = new Warrior(); + console.log(warrior.weapon instanceof Sword); // true + +} + +module lazyInjectNamed { + + let kernel = new Kernel(); + let { lazyInjectNamed } = getDecorators(kernel); + let TYPES = { Weapon: "Weapon" }; + + interface Weapon { + name: string; + durability: number; + use(): void; + } + + @injectable() + class Sword implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Sword"; + } + public use() { + this.durability = this.durability - 10; + } + } + + @injectable() + class Shuriken implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Shuriken"; + } + public use() { + this.durability = this.durability - 10; + } + } + + class Warrior { + + @lazyInjectNamed(TYPES.Weapon, "not-throwwable") + @named("not-throwwable") + public primaryWeapon: Weapon; + + @lazyInjectNamed(TYPES.Weapon, "throwwable") + @named("throwwable") + public secondaryWeapon: Weapon; + + } + + kernel.bind(TYPES.Weapon).to(Sword).whenTargetNamed("not-throwwable"); + kernel.bind(TYPES.Weapon).to(Shuriken).whenTargetNamed("throwwable"); + + let warrior = new Warrior(); + console.log(warrior.primaryWeapon instanceof Sword); // true + console.log(warrior.primaryWeapon instanceof Shuriken); // true + +} + +module lazyInjectTagged { + + let kernel = new Kernel(); + let { lazyInjectTagged } = getDecorators(kernel); + let TYPES = { Weapon: "Weapon" }; + + interface Weapon { + name: string; + durability: number; + use(): void; + } + + @injectable() + class Sword implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Sword"; + } + public use() { + this.durability = this.durability - 10; + } + } + + @injectable() + class Shuriken implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Shuriken"; + } + public use() { + this.durability = this.durability - 10; + } + } + + class Warrior { + + @lazyInjectTagged(TYPES.Weapon, "throwwable", false) + @tagged("throwwable", false) + public primaryWeapon: Weapon; + + @lazyInjectTagged(TYPES.Weapon, "throwwable", true) + @tagged("throwwable", true) + public secondaryWeapon: Weapon; + + } + + kernel.bind(TYPES.Weapon).to(Sword).whenTargetTagged("throwwable", false); + kernel.bind(TYPES.Weapon).to(Shuriken).whenTargetTagged("throwwable", true); + + let warrior = new Warrior(); + console.log(warrior.primaryWeapon instanceof Sword); // true + console.log(warrior.primaryWeapon instanceof Shuriken); // true + +} + +module lazyMultiInject { + + let kernel = new Kernel(); + let { lazyMultiInject } = getDecorators(kernel); + let TYPES = { Weapon: "Weapon" }; + + interface Weapon { + name: string; + durability: number; + use(): void; + } + + @injectable() + class Sword implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Sword"; + } + public use() { + this.durability = this.durability - 10; + } + } + + @injectable() + class Shuriken implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Shuriken"; + } + public use() { + this.durability = this.durability - 10; + } + } + + class Warrior { + + @lazyMultiInject(TYPES.Weapon) + public weapons: Weapon[]; + + } + + kernel.bind(TYPES.Weapon).to(Sword); + kernel.bind(TYPES.Weapon).to(Shuriken); + + let warrior = new Warrior(); + console.log(warrior.weapons[0] instanceof Sword); // true + console.log(warrior.weapons[1] instanceof Shuriken); // true + +} diff --git a/inversify-inject-decorators/inversify-inject-decorators.d.ts b/inversify-inject-decorators/inversify-inject-decorators.d.ts new file mode 100644 index 0000000000..032ed40cdd --- /dev/null +++ b/inversify-inject-decorators/inversify-inject-decorators.d.ts @@ -0,0 +1,32 @@ +// Type definitions for inversify-inject-decorators 1.0.0-beta.1 +// Project: https://github.com/inversify/inversify-inject-decorators +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare namespace inversifyInjectDecorators { + + interface InjectDecorators { + + lazyInject: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => + (proto: any, key: string) => void; + + lazyInjectNamed: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable), named: string) => + (proto: any, key: string) => void; + + lazyInjectTagged: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable), key: string, value: any) => + (proto: any, propertyName: string) => void; + + lazyMultiInject: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => + (proto: any, key: string) => void; + + } + + export function getDecorators(kernel: inversify.interfaces.Kernel): InjectDecorators; + +} + +declare module "inversify-inject-decorators" { + export default inversifyInjectDecorators.getDecorators; +} 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/json-editor/json-editor-tests.ts b/json-editor/json-editor-tests.ts new file mode 100644 index 0000000000..0492324555 --- /dev/null +++ b/json-editor/json-editor-tests.ts @@ -0,0 +1,146 @@ +/// + +var element = document.getElementById('editor_holder'); +var editor = new JSONEditor(element, {}); + +// Set an option globally +JSONEditor.defaults.options.theme = 'bootstrap2'; +// Set an option during instantiation +editor = new JSONEditor(element, { + theme: 'bootstrap2' +}); +editor.on('ready', function () { + // Now the api methods will be available + editor.validate(); +}); + +var editor2 = new JSONEditor<{ name: string; }>(element, {}); +editor2.setValue({ name: "John Smith" }); +var value = editor2.getValue(); +console.log(value.name) // Will log "John Smith" + +// Get a reference to a node within the editor +var name2 = editor.getEditor('root.name'); + +// `getEditor` will return null if the path is invalid +if (name2) { + name2.setValue("John Smith"); + + console.log(name2.getValue()); +} + +var errors = editor.validate(); + +if (errors.length) { + // errors is an array of objects, each with a `path`, `property`, and `message` parameter + // `property` is the schema keyword that triggered the validation error (e.g. "minLength") + // `path` is a dot separated path into the JSON object (e.g. "root.path.to.field") + console.log(errors); +} +else { + // It's valid! +} + +// Validate an arbitrary value against the editor's schema +var errors = editor.validate({ + value: { + to: "test" + } +}); + +editor.on('change', function () { + // Do something +}); + +editor.off('change', function () { + // Do something +}); + +editor.watch('path.to.field', function () { + // Do something +}); + +editor.unwatch('path.to.field', function () { + // Do something +}); + +// Disable entire form +editor.disable(); + +// Disable part of the form +editor.getEditor('root.location').disable(); + +// Enable entire form +editor.enable(); + +// Enable part of the form +editor.getEditor('root.location').enable(); + +// Check if form is currently enabled +if (editor.isEnabled()) alert("It's editable!"); + +editor.destroy(); + +JSONEditor.defaults.options.theme = 'foundation5'; + +JSONEditor.plugins.sceditor.emoticonsEnabled = false; + +JSONEditor.plugins.epiceditor.basePath = 'epiceditor'; + +JSONEditor.plugins.ace.theme = 'twilight'; + +JSONEditor.defaults.editors.object.options.collapsed = true; + +JSONEditor.defaults.options.template = 'handlebars'; + +var myengine = { + compile: function (template: any) { + // Compile should return a render function + return function (vars: any) { + // A real template engine would render the template here + var result = template; + return result; + } + } +}; + +// Set globally +JSONEditor.defaults.options.template = myengine; + +// Override a specific translation +JSONEditor.defaults.languages.en.error_minLength = + "This better be at least {{0}} characters long or else!"; + + +// Create your own language mapping +// Any keys not defined here will fall back to the "en" language +JSONEditor.defaults.languages.es = { + error_notset: "propiedad debe existir" +}; + +JSONEditor.defaults.language = "es"; + +JSONEditor.defaults.resolvers.unshift(function (schema) { + if (schema.type === "object" && schema.format === "location") { + return "location"; + } + + // If no valid editor is returned, the next resolver function will be used +}); + +JSONEditor.plugins.selectize.enable = true; + +JSONEditor.defaults.custom_validators.push(function (schema, value, path) { + var errors: JSONEditorError[] = []; + if (schema.format === "date") { + if (!/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(value)) { + // Errors must be an object with `path`, `property`, and `message` + errors.push({ + path: path, + property: 'format', + message: 'Dates must be in the format "YYYY-MM-DD"' + }); + } + } + return errors; +}); diff --git a/json-editor/json-editor.d.ts b/json-editor/json-editor.d.ts new file mode 100644 index 0000000000..cbb0c9c29c --- /dev/null +++ b/json-editor/json-editor.d.ts @@ -0,0 +1,184 @@ +// Type definitions for json-editor +// Project: https://github.com/jdorn/json-editor +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type JSONEditorOptions = { + /** + * If true, JSON Editor will load external URLs in $ref via ajax. + */ + ajax?: boolean; + /** + * If true, remove all "add row" buttons from arrays. + */ + disable_array_add?: boolean; + /** + * If true, remove all "delete row" buttons from arrays. + */ + disable_array_delete?: boolean; + /** + * If true, remove all "move up" and "move down" buttons from arrays. + */ + disable_array_reorder?: boolean; + /** + * If true, remove all collapse buttons from objects and arrays. + */ + disable_collapse?: boolean; + /** + * If true, remove all Edit JSON buttons from objects. + */ + disable_edit_json?: boolean; + /** + * If true, remove all Edit Properties buttons from objects. + */ + disable_properties?: boolean; + /** + * The first part of the `name` attribute of form inputs in the editor. An full example name is `root[person][name]` where "root" is the form_name_root. + */ + form_name_root?: string; + /** + * The icon library to use for the editor. + */ + iconlib?: boolean; + /** + * If true, objects can only contain properties defined with the properties keyword. + */ + no_additional_properties?: boolean; + /** + * An object containing schema definitions for URLs. Allows you to pre-define external schemas. + */ + refs?: any; + /** + * If true, all schemas that don't explicitly set the required property will be required. + */ + required_by_default?: boolean; + /** + * If true, makes oneOf copy properties over when switching. + */ + keep_oneof_values?: boolean; + /** + * A valid JSON Schema to use for the editor. Version 3 and Version 4 of the draft specification are supported. + */ + schema?: any; + /** + * When to show validation errors in the UI. Valid values are interaction, change, always, and never. + */ + show_errors?: "interaction" | "change" | "always" | "never"; + /** + * Seed the editor with an initial value. This should be valid against the editor's schema. + */ + startval?: TValue; + /** + * The JS template engine to use. + */ + template?: string | { compile: (template: string) => (vars: any) => string }; + /** + * The CSS theme to use. + */ + theme?: string; + /** + * If true, only required properties will be included by default. + */ + display_required_only?: boolean; +} +type JSONEditorError = { + path: string; + property: string; + message: string; +} +type JSONEditorObjectOptions = { + /** + * If set to true, the editor will start collapsed + */ + collapsed?: boolean; + /** + * If set to true, the collapse button will be hidden + */ + disable_collapse?: boolean; + /** + * If set to true, the Edit JSON button will be hidden + */ + disable_edit_json?: boolean; + /** + * If set to true, the Edit Properties button will be hidden + */ + disable_properties?: boolean; +} +type JSONEditorArrayOptions = { + /** + * If set to true, the editor will start collapsed + */ + collapsed?: boolean; + /** + * If set to true, the "add row" button will be hidden + */ + disable_array_add?: boolean; + /** + * If set to true, all of the "delete" buttons will be hidden + */ + disable_array_delete?: boolean; + /** + * If set to true, just the "delete all rows" button will be hidden + */ + disable_array_delete_all_rows?: boolean; + /** + * If set to true, just the "delete last row" buttons will be hidden + */ + disable_array_delete_last_row?: boolean; + /** + * If set to true, the "move up/down" buttons will be hidden + */ + disable_array_reorder?: boolean; + /** + * If set to true, the collapse button will be hidden + */ + disable_collapse?: boolean; +} +declare class JSONEditor { + public static defaults: { + options: JSONEditorOptions; + editors: { + object: { + options: JSONEditorObjectOptions; + }; + array: { + options: JSONEditorArrayOptions; + } + }; + languages: any; + language: string; + resolvers: ((schema: any) => string)[]; + custom_validators: (((schema: any, value: string, path: string) => JSONEditorError[]))[]; + }; + public static plugins: { + sceditor: { + emoticonsEnabled: boolean; + }; + epiceditor: { + basePath: string; + }; + ace: { + theme: string; + }; + selectize: { + enable: boolean; + }; + }; + constructor(element: HTMLElement, options: JSONEditorOptions); + public on(event: string, fn: Function): JSONEditor; + public off(event: string, fn: Function): JSONEditor; + public watch(event: string, fn: Function): JSONEditor; + public unwatch(event: string, fn: Function): JSONEditor; + public validate(value?: TValue): JSONEditorError[]; + public setValue(value: TValue): void; + public getValue(): TValue; + public getEditor(name: string): JSONEditor; + public disable(): void; + public enable(): void; + public isEnabled(): boolean; + public destroy(): void; +} + +declare module "json-editor" { + export = JSONEditor; +} 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/jsonschema/jsonschema-tests.ts b/jsonschema/jsonschema-tests.ts new file mode 100644 index 0000000000..e8acc29886 --- /dev/null +++ b/jsonschema/jsonschema-tests.ts @@ -0,0 +1,6 @@ +/// +import { Validator, IJSONSchemaValidationError } from "jsonschema"; + +const v: Validator = new Validator(); + +const validationResults: { errors: Array } = v.validate("Smith", {"type": "string"}); diff --git a/jsonschema/jsonschema.d.ts b/jsonschema/jsonschema.d.ts new file mode 100644 index 0000000000..1c2f0f915e --- /dev/null +++ b/jsonschema/jsonschema.d.ts @@ -0,0 +1,103 @@ +// Type definitions for jsonschema +// Project: https://github.com/tdegrunt/jsonschema +// Definitions by: Vlado Tešanovic +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module "jsonschema" { + + export interface IJSONSchemaResult { + errors: Array; + instance: any; + arguments: Array<{}>; + propertyPath: string; + name: string; + schema: {}; + throwError: any; + disableFormat: boolean; + } + + export interface IJSONSchemaValidationError { + message: string; + property: string; + stack: string; + schema: {}; + name: string; + instance: any; + argument: {}; + } + + export interface IJSONSchemaOptions { + propertyName?: string; + base?: string; + } + + /** + * How to; + * + * const v: Validator = new Validator(); + * + * const schema: {} = { + * "type": "object", + * "properties": { + * "key": { + * "type": "string", + * "required": true + * }, + * "value": { + * "type": "string", + * "required": true + * } + * } + * }; + * + * const validationResults: { errors: Array } = + * v.validate({ key: "Name", value: "A10" }, {"type": "string"}); + * + */ + export class Validator { + + /** + * Creates a new Validator object + * @name Validator + * @constructor + */ + new(): this; + + /** + * Validates instance against the provided schema + * @param instance + * @param schema + * @param [options] + * @param [ctx] + * @return {Array} + */ + validate(instance: any, schema: {}, options?: IJSONSchemaOptions, ctx?: {}): IJSONSchemaResult; + + /** + * Adds a schema with a certain urn to the Validator instance. + * @param schema + * @param urn + * @return {Object} + */ + addSchema(schema: {}, urn: string): {}; + + /** + * Add Sub schema to existing one + * @param baseuri + * @param schema + */ + addSubSchema(baseuri: string, schema: {}): {} + + /** + * Sets all the schemas of the Validator instance. + * @param schemas + */ + setSchemas (schemas: Array<{}>): void; + + /** + * Returns the schema of a certain urn + * @param urn + */ + getSchema(urn: string): {}; + } +} + diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index a7a0417cc4..3a00c32551 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({}); @@ -65,6 +78,18 @@ var knex = Knex({ client: 'pg' }); +// searchPath +var knex = Knex({ + client: 'pg', + searchPath: 'public', +}); + +// useNullAsDefault +var knex = Knex({ + client: 'sqlite', + useNullAsDefault: true, +}); + knex('books').insert({title: 'Test'}).returning('*').toString(); // Migrations diff --git a/knex/knex.d.ts b/knex/knex.d.ts index bb6395807e..64d530ed49 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -453,6 +453,9 @@ declare module "knex" { Sqlite3ConnectionConfig|SocketConnectionConfig; pool?: PoolConfig; migrations?: MigratorConfig; + acquireConnectionTimeout?: number; + useNullAsDefault?: boolean; + searchPath?: string; } interface ConnectionConfig { diff --git a/koa-hbs/koa-hbs-tests.ts b/koa-hbs/koa-hbs-tests.ts new file mode 100644 index 0000000000..373c3ab8b9 --- /dev/null +++ b/koa-hbs/koa-hbs-tests.ts @@ -0,0 +1,21 @@ +/// +/// + +import * as Hbs from 'koa-hbs'; +import * as Koa from 'koa'; +import * as Path from 'path'; + +const app = new Koa(); +const hbs = new Hbs(); + +app.use(hbs.middleware({ + viewPath: Path.join(__dirname, './views') +})); + +app.use(function *(next: any) { + yield this.render('index', { + title: 'Hello World!' + }); +}); + +app.listen(3000); diff --git a/koa-hbs/koa-hbs.d.ts b/koa-hbs/koa-hbs.d.ts new file mode 100644 index 0000000000..cd8fc9c5b4 --- /dev/null +++ b/koa-hbs/koa-hbs.d.ts @@ -0,0 +1,55 @@ +// Type definitions for koa-favicon v2.x +// Project: https://github.com/gilt/koa-hbs +// Definitions by: Jacob Malone +// Definitions: https://github.com/jcbmln/DefinitelyTyped + +/* =================== USAGE =================== + + import * as Hbs from "koa-hbs"; + import * as Koa from "koa"; + + var hbs = new Hbs(); + var app = new Koa(); + + app.use(hbs.middleware({ + viewPath: __dirname + '/views' + })); + + app.use(function *() { + yield this.render('main', { + title: 'koa-hbs' + }); + }); + + =============================================== */ + +/// + +declare module "koa-hbs" { + + import * as Koa from "koa"; + + namespace Hbs { + export interface Middleware { + viewPath: Array | string, + handlebars?: Function, + templateOptions?: {}, + extname?: string, + partialsPath?: Array | string, + defaultLayout?: string, + layoutsPath?: string, + contentHelperName?: string, + blockHelperName?: string, + disableCache?: boolean + } + } + + class Hbs { + constructor(); + + middleware(opts: Hbs.Middleware): any; + } + + namespace Hbs {} + export = Hbs; +} 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/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts new file mode 100644 index 0000000000..c6519ab371 --- /dev/null +++ b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts @@ -0,0 +1,10 @@ +/// +/// + +var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', + osmAttrib = '© OpenStreetMap contributors', + osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib}), + map = new L.Map('map', {layers: [osm], center: new L.LatLng(-37.7772, 175.2756), zoom: 15 }); + +// Add geocoding plugin +L.control.geocoder('search-MKZrG6M').addTo(map); diff --git a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts new file mode 100644 index 0000000000..8809472e43 --- /dev/null +++ b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts @@ -0,0 +1,177 @@ +// Type definitions for leaflet-geocoder-mapzen v1.6.3 +// Project: https://github.com/mapzen/leaflet-geocoder +// Definitions by: Leonard Lausen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +declare namespace L { + namespace Control { + export interface GeocoderStatic extends ClassStatic { + /** + * Creates a geocoder control. + */ + new (options?: GeocoderOptions): Geocoder; + } + + export interface Geocoder extends L.Control { + } + + export interface GeocoderOptions { + /** + * Host endpoint for a Pelias-compatible search API. + * + * Default value: 'https://search.mapzen.com/v1'. + */ + url?: string; + + /** + * If true, search is bounded by the current map view. + * You may also provide a custom bounding box in form of a LatLngBounds object. + * Note: bounds is not supported by autocomplete. + * + * Default value: false. + */ + bounds?: LatLngBounds | boolean; + + /** + * If true, search and autocomplete prioritizes results near the center + * of the current view. + * You may also provide a custom LatLng value + * (in any of the accepted Leaflet formats) to act as the center bias. + * + * Default value: 'true'. + */ + focus?: LatLng | boolean; + + /** + * Filters results by layers (documentation). + * If left blank, results will come from all available layers. + * + * Default value: null. + */ + layers?: string | any[] ; + + /** + * An object of key-value pairs which will be serialized + * into query parameters that will be passed to the API. + * This allows custom queries that are not already supported + * by the convenience options listed above. + * For a full list of supported parameters, + * please read the Mapzen Search documentation. + * + * IMPORTANT: some parameters only work with the /search endpoint, + * and do not apply to /autocomplete requests! + * All supplied parameters are passed through; + * this library doesn't know which are valid parameters and which are not. + * In the event that other options conflict with parameters passed through params, + * the params option takes precedence. + * + * Default value: null. + */ + params?: Object; + + /** + * The position of the control (one of the map corners). + * Can be 'topleft', 'topright', 'bottomleft', or 'bottomright'. + * + * Default value: 'topleft'. + */ + position?: PositionString; + + /** + * Attribution text to include. + * Set to blank or null to disable. + * + * Default value: 'Geocoding by Mapzen' + */ + attribution?: string; + + /** + * Placeholder text to display in the search input box. + * Set to blank or null to disable. + * + * Default value: 'Search' + */ + placeholder?: string; + + /** + * Tooltip text to display on the search icon. Set to blank or null to disable. + * + * Default value: 'Search' + */ + title?: string; + + /** + * If true, highlighting a search result pans the map to that location. + * + * Default value: true + */ + panToPoint?: boolean; + + /** + * If true, an icon is used to indicate a polygonal result, + * matching any non-"venue" or non-"address" layer type. + * If false, no icon is displayed. + * For custom icons, pass a string containing a path to the image. + * + * Default value: true + */ + polygonIcon?: boolean | string; + + /** + * If true, search results drops Leaflet's default blue markers onto the map. + * You may customize this marker's appearance and + * behavior using Leaflet marker options. + * + * Default value: true + */ + markers?: MarkerOptions | boolean; + + /** + * If true, the input box will expand to take up the full width of the map container. + * If an integer breakpoint is provided, + * the full width applies only if the map container width is below this breakpoint. + * + * Default value: 650 + */ + fullWidth?: number | boolean; + + /** + * If true, the search input is always expanded. + * It does not collapse into a button-only state. + * + * Default value: false + */ + expanded?: boolean; + + /** + * If true, suggested results are fetched on each keystroke. + * If false, this is disabled and users must obtain results + * by pressing the Enter key after typing in their query. + * + * Default value: true + */ + autocomplete?: boolean; + + /** + * If true, selected results will make a request to the service /place endpoint. + * If false, this is disabled. + * The geocoder does not handle responses to /place, + * you will need to do handle it yourself in the results event listener (see below). + * + * Default value: false + */ + place?: boolean; + } + } + + export namespace control { + + /** + * Creates a geocoder control. + */ + export function geocoder(api_key: string, options?: Control.GeocoderOptions): L.Control.Geocoder; + } +} 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/marker-animate-unobtrusive/marker-animate-unobtrusive-amd-tests.ts b/marker-animate-unobtrusive/marker-animate-unobtrusive-amd-tests.ts new file mode 100644 index 0000000000..544c95af5a --- /dev/null +++ b/marker-animate-unobtrusive/marker-animate-unobtrusive-amd-tests.ts @@ -0,0 +1,8 @@ +/// +/// + +import SlidingMarker = require('SlidingMarker'); +import MarkerWithGhost = require('MarkerWithGhost'); + +SlidingMarker.initializeGlobally(); +MarkerWithGhost.initializeGlobally(); diff --git a/marker-animate-unobtrusive/marker-animate-unobtrusive-tests.ts b/marker-animate-unobtrusive/marker-animate-unobtrusive-tests.ts new file mode 100644 index 0000000000..73ad4da4b5 --- /dev/null +++ b/marker-animate-unobtrusive/marker-animate-unobtrusive-tests.ts @@ -0,0 +1,50 @@ +/// +/// + +function test_init() { + SlidingMarker.initializeGlobally(); + MarkerWithGhost.initializeGlobally(); +} + +function test_options() { + var options: SlidingMarkerOptions = { + position: new google.maps.LatLng(0, 0), + easing: "easeInOutSine", + duration: 1000, + animateFunctionAdapter: (marker, destPoint, easing, duration) => {} + }; + var m = new SlidingMarker(options); + var g = new MarkerWithGhost(options); +} + +function test_sliding_marker() { + let googleMarker: google.maps.Marker; + let p: google.maps.LatLng; + let d: number; + let e:jQuery.easing.IEasingType; + + var m = new SlidingMarker(); + googleMarker = m; + + p = m.getPosition(); + m.setDuration(d); + d = m.getDuration(); + m.setEasing(e); + e = m.getEasing(); + p = m.getAnimationPosition(); + m.setPositionNotAnimated(p); +} + +function test_marker_with_ghost() { + let p: google.maps.LatLng; + let d: number; + let e:jQuery.easing.IEasingType; + let slidingMarker: SlidingMarker; + + var g = new MarkerWithGhost(); + slidingMarker = g; + + g.setGhostPosition(p); + p = g.getGhostPosition(); + p = g.getGhostAnimationPosition(); +} diff --git a/marker-animate-unobtrusive/marker-animate-unobtrusive.d.ts b/marker-animate-unobtrusive/marker-animate-unobtrusive.d.ts new file mode 100644 index 0000000000..61a4a680df --- /dev/null +++ b/marker-animate-unobtrusive/marker-animate-unobtrusive.d.ts @@ -0,0 +1,72 @@ +// Type definitions for marker-animate-unobtrusive 0.2.8 +// Project: https://github.com/terikon/marker-animate-unobtrusive +// Definitions by: Roman Viskin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace jQuery.easing { + type IEasingType = + 'swing' | + 'easeInQuad' | + 'easeOutQuad' | + 'easeInOutQuad' | + 'easeInCubic' | + 'easeOutCubic' | + 'easeInOutCubic' | + 'easeInQuart' | + 'easeOutQuart' | + 'easeInOutQuart' | + 'easeInQuint' | + 'easeOutQuint' | + 'easeInOutQuint' | + 'easeInSine' | + 'easeOutSine' | + 'easeInOutSine' | + 'easeInExpo' | + 'easeOutExpo' | + 'easeInOutExpo' | + 'easeInCirc' | + 'easeOutCirc' | + 'easeInOutCirc' | + 'easeInElastic' | + 'easeOutElastic' | + 'easeInOutElastic' | + 'easeInBack' | + 'easeOutBack' | + 'easeInOutBack' | + 'easeInBounce' | + 'easeOutBounce' | + 'easeInOutBounce'; +} + +interface SlidingMarkerOptions extends google.maps.MarkerOptions { + easing?: jQuery.easing.IEasingType, + duration?: number, + animateFunctionAdapter?: (marker: google.maps.Marker, destPoint: google.maps.LatLng, easing: 'linear' | jQuery.easing.IEasingType, duration: number) => void +} + +declare class SlidingMarker extends google.maps.Marker { + static initializeGlobally(): void; + constructor(opts?: SlidingMarkerOptions); + setDuration(duration: number): void; + getDuration(): number; + setEasing(easing: jQuery.easing.IEasingType): void; + getEasing(): jQuery.easing.IEasingType; + getAnimationPosition(): google.maps.LatLng; + setPositionNotAnimated(position: google.maps.LatLng | google.maps.LatLngLiteral): void; +} + +declare class MarkerWithGhost extends SlidingMarker { + setGhostPosition(ghostPosition: google.maps.LatLng | google.maps.LatLngLiteral): void; + getGhostPosition(): google.maps.LatLng; + getGhostAnimationPosition(): google.maps.LatLng; +} + +declare module "SlidingMarker" { + export = SlidingMarker; +} + +declare module "MarkerWithGhost" { + export = MarkerWithGhost; +} 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 359f1679c5..6770d84632 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -324,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; @@ -607,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; @@ -901,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 { @@ -918,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; } @@ -1985,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/nodemailer-direct-transport/nodemailer-direct-transport.d.ts b/nodemailer-direct-transport/nodemailer-direct-transport.d.ts index ce5caed172..4fa8e9ad34 100644 --- a/nodemailer-direct-transport/nodemailer-direct-transport.d.ts +++ b/nodemailer-direct-transport/nodemailer-direct-transport.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "nodemailer-direct-transport" { diff --git a/nodemailer-pickup-transport/nodemailer-pickup-transport.d.ts b/nodemailer-pickup-transport/nodemailer-pickup-transport.d.ts index 52aef3801d..35dfad9bc1 100644 --- a/nodemailer-pickup-transport/nodemailer-pickup-transport.d.ts +++ b/nodemailer-pickup-transport/nodemailer-pickup-transport.d.ts @@ -3,7 +3,7 @@ // Definitions by: Peter Snider // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "nodemailer-pickup-transport" { diff --git a/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts b/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts new file mode 100644 index 0000000000..1cbd06929b --- /dev/null +++ b/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts @@ -0,0 +1,26 @@ +/// +/// + +import * as AWS from 'aws-sdk'; +import * as sesTransport from 'nodemailer-ses-transport'; + +var opts: sesTransport.SesOptions = { + ses: new AWS.SES(), + rateLimit: 5, + maxConnections: 3, +}; + +var transport: nodemailer.Transport = sesTransport(opts); + +// setup e-mail data with unicode symbols +var mailOptions: nodemailer.SendMailOptions = { + from: 'Fred Foo ✔ ', // sender address + to: 'bar@blurdybloop.com, baz@blurdybloop.com', // list of receivers + subject: 'Hello ✔', // Subject line + text: 'Hello world ✔', // plaintext body + html: 'Hello world ✔' // html body +}; + +transport.send(mailOptions, (error: Error, info: nodemailer.SentMessageInfo): void => { + // nothing +}); diff --git a/nodemailer-ses-transport/nodemailer-ses-transport.d.ts b/nodemailer-ses-transport/nodemailer-ses-transport.d.ts new file mode 100644 index 0000000000..8ce3d88d69 --- /dev/null +++ b/nodemailer-ses-transport/nodemailer-ses-transport.d.ts @@ -0,0 +1,29 @@ +// Type definitions for nodemailer-ses-transport 1.4.0 +// Project: https://github.com/andris9/nodemailer-ses-transport +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module "nodemailer-ses-transport" { + + import * as AWS from 'aws-sdk'; + + namespace sesTransport { + export interface SesOptions { + ses?: AWS.SES; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: string; + region?: string; + httpOptions?: AWS.HttpOptions; + rateLimit?: number; + maxConnections?: number; + } + } + + function sesTransport(options: sesTransport.SesOptions): nodemailer.Transport; + + export = sesTransport; +} diff --git a/nodemailer-smtp-pool/nodemailer-smtp-pool.d.ts b/nodemailer-smtp-pool/nodemailer-smtp-pool.d.ts index d815bab293..b636ef7df7 100644 --- a/nodemailer-smtp-pool/nodemailer-smtp-pool.d.ts +++ b/nodemailer-smtp-pool/nodemailer-smtp-pool.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// +/// declare module "nodemailer-smtp-pool" { import tls = require("tls"); diff --git a/nodemailer-smtp-transport/nodemailer-smtp-transport.d.ts b/nodemailer-smtp-transport/nodemailer-smtp-transport.d.ts index 0beff75ee5..412dd269b0 100644 --- a/nodemailer-smtp-transport/nodemailer-smtp-transport.d.ts +++ b/nodemailer-smtp-transport/nodemailer-smtp-transport.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// +/// declare module "nodemailer-smtp-transport" { diff --git a/nodemailer/nodemailer-tests.ts b/nodemailer/nodemailer-tests.ts index 46aae5448d..85c89ddea6 100644 --- a/nodemailer/nodemailer-tests.ts +++ b/nodemailer/nodemailer-tests.ts @@ -42,4 +42,22 @@ transporter.sendMail(mailOptions, (error: Error, info: nodemailer.SentMessageInf // promise send mail without callback transporter .sendMail(mailOptions) - .then(info => info.messageId) \ No newline at end of file + .then(info => info.messageId) + +// create template based sender function +var sendPwdReset = transporter.templateSender({ + subject: 'Password reset for {{username}}!', + text: 'Hello, {{username}}, Please go here to reset your password: {{ reset }}', + html: 'Hello, {{username}}, Please go here to reset your password: {{ reset }}

' +}, { + from: 'sender@example.com', +}); + +// use template based sender to send a message +sendPwdReset({ + to: 'receiver@example.com' +}, { + username: 'Node Mailer', + reset: 'https://www.example.com/reset?token=' +}) +.then(info => info.messageId); diff --git a/nodemailer/nodemailer-types.d.ts b/nodemailer/nodemailer-types.d.ts deleted file mode 100644 index 6fde6ebad9..0000000000 --- a/nodemailer/nodemailer-types.d.ts +++ /dev/null @@ -1,149 +0,0 @@ -// Type definitions for Nodemailer 1.3.2 -// Project: https://github.com/andris9/Nodemailer -// Definitions by: Rogier Schouten -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace nodemailer { - - export interface AttachmentObject { - /** - * filename to be reported as the name of the attached file, use of unicode is allowed - */ - filename?: string; - /** - * optional content id for using inline images in HTML message source - */ - cid?: string; - /** - * Pathname or URL to use streaming - */ - path?: string; - /** - * String, Buffer or a Stream contents for the attachment - */ - content: string|Buffer|NodeJS.ReadableStream; - /** - * If set and content is string, then encodes the content to a Buffer using the specified encoding. Example values: base64, hex, 'binary' etc. Useful if you want to use binary attachments in a JSON formatted e-mail object. - */ - encoding?: string; - /** - * optional content type for the attachment, if not set will be derived from the filename property - */ - contentType?: string; - /** - * optional content disposition type for the attachment, defaults to 'attachment' - */ - contentDisposition?: string; - } - - export interface SendMailOptions { - /** - * The e-mail address of the sender. All e-mail addresses can be plain 'sender@server.com' or formatted 'Sender Name ', see here for details - */ - from?: string; - /** - * An e-mail address that will appear on the Sender: field - */ - sender?: string; - /** - * Comma separated list or an array of recipients e-mail addresses that will appear on the To: field - */ - to?: string|string[]; - /** - * Comma separated list or an array of recipients e-mail addresses that will appear on the Cc: field - */ - cc?: string|string[]; - /** - * Comma separated list or an array of recipients e-mail addresses that will appear on the Bcc: field - */ - bcc?: string|string[]; - /** - * An e-mail address that will appear on the Reply-To: field - */ - replyTo?: string; - /** - * The message-id this message is replying - */ - inReplyTo?: string; - /** - * Message-id list (an array or space separated string) - */ - references?: string|string[]; - /** - * The subject of the e-mail - */ - subject?: string; - /** - * The plaintext version of the message as an Unicode string, Buffer, Stream or an object {path: '...'} - */ - text?: string|Buffer|NodeJS.ReadableStream|AttachmentObject; - /** - * The HTML version of the message as an Unicode string, Buffer, Stream or an object {path: '...'} - */ - html?: string|Buffer|NodeJS.ReadableStream|AttachmentObject; - /** - * An object or array of additional header fields (e.g. {"X-Key-Name": "key value"} or [{key: "X-Key-Name", value: "val1"}, {key: "X-Key-Name", value: "val2"}]) - */ - headers?: any; - /** - * An array of attachment objects (see below for details) - */ - attachments?: AttachmentObject[]; - /** - * An array of alternative text contents (in addition to text and html parts) (see below for details) - */ - alternatives?: AttachmentObject[]; - /** - * optional Message-Id value, random value will be generated if not set - */ - messageId?: string; - /** - * optional Date value, current UTC string will be used if not set - */ - date?: Date; - /** - * optional transfer encoding for the textual parts (defaults to 'quoted-printable') - */ - encoding?: string; - } - - export interface SentMessageInfo { - /** - * most transports should return the final Message-Id value used with this property - */ - messageId: string; - /** - * includes the envelope object for the message - */ - envelope: any; - /** - * is an array returned by SMTP transports (includes recipient addresses that were accepted by the server) - */ - accepted: string[]; - /** - * is an array returned by SMTP transports (includes recipient addresses that were rejected by the server) - */ - rejected: string[]; - /** - * is an array returned by Direct SMTP transport. Includes recipient addresses that were temporarily rejected together with the server response - */ - pending?: string[]; - /** - * is a string returned by SMTP transports and includes the last SMTP response from the server - */ - response: string; - } - - /** - * This is what you implement to create a new transporter yourself - */ - export interface Transport { - name: string; - version: string; - send(mail: SendMailOptions, callback?: (error: Error, info: SentMessageInfo) => void): void; - close(): void; - } - -} diff --git a/nodemailer/nodemailer.d.ts b/nodemailer/nodemailer.d.ts index 647566437f..cd30f2acdc 100644 --- a/nodemailer/nodemailer.d.ts +++ b/nodemailer/nodemailer.d.ts @@ -3,8 +3,8 @@ // Definitions by: Rogier Schouten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// /// -/// /// /// @@ -13,6 +13,8 @@ declare module "nodemailer" { import directTransport = require("nodemailer-direct-transport"); import smtpTransport = require("nodemailer-smtp-transport"); + import * as Promise from 'bluebird'; + export type Transport = nodemailer.Transport; export type SendMailOptions = nodemailer.SendMailOptions; export type SentMessageInfo = nodemailer.SentMessageInfo; @@ -39,6 +41,17 @@ declare module "nodemailer" { */ sendMail(mail: SendMailOptions): Promise; + /** + * Send mail using a template. + */ + templateSender(template?: any, defaults?: any): (mailData: any, context: any) => Promise; + + /** + * Send mail using a template with a callback. + */ + templateSender(template?: any, defaults?: any, callback?: (error: Error, info: SentMessageInfo) => void): void; + + /** * Attach a plugin. 'compile' and 'stream' plugins can be attached with use(plugin) method * @@ -48,14 +61,14 @@ declare module "nodemailer" { use(step: string, plugin: Plugin): void; /** - * Verifies connection with server - */ - verify(callback: (error: Error, success?: boolean) => void): void; - - /** - * Verifies connection with server - */ - verify(): Promise; + * Verifies connection with server + */ + verify(callback: (error: Error, success?: boolean) => void): void; + + /** + * Verifies connection with server + */ + verify(): Promise; /** * Close all connections @@ -76,3 +89,146 @@ declare module "nodemailer" { */ export function createTransport(transport: Transport, defaults?: Object): Transporter; } + +declare namespace nodemailer { + + export interface AttachmentObject { + /** + * filename to be reported as the name of the attached file, use of unicode is allowed + */ + filename?: string; + /** + * optional content id for using inline images in HTML message source + */ + cid?: string; + /** + * Pathname or URL to use streaming + */ + path?: string; + /** + * String, Buffer or a Stream contents for the attachment + */ + content: string|Buffer|NodeJS.ReadableStream; + /** + * If set and content is string, then encodes the content to a Buffer using the specified encoding. Example values: base64, hex, 'binary' etc. Useful if you want to use binary attachments in a JSON formatted e-mail object. + */ + encoding?: string; + /** + * optional content type for the attachment, if not set will be derived from the filename property + */ + contentType?: string; + /** + * optional content disposition type for the attachment, defaults to 'attachment' + */ + contentDisposition?: string; + } + + export interface SendMailOptions { + /** + * The e-mail address of the sender. All e-mail addresses can be plain 'sender@server.com' or formatted 'Sender Name ', see here for details + */ + from?: string; + /** + * An e-mail address that will appear on the Sender: field + */ + sender?: string; + /** + * Comma separated list or an array of recipients e-mail addresses that will appear on the To: field + */ + to?: string|string[]; + /** + * Comma separated list or an array of recipients e-mail addresses that will appear on the Cc: field + */ + cc?: string|string[]; + /** + * Comma separated list or an array of recipients e-mail addresses that will appear on the Bcc: field + */ + bcc?: string|string[]; + /** + * An e-mail address that will appear on the Reply-To: field + */ + replyTo?: string; + /** + * The message-id this message is replying + */ + inReplyTo?: string; + /** + * Message-id list (an array or space separated string) + */ + references?: string|string[]; + /** + * The subject of the e-mail + */ + subject?: string; + /** + * The plaintext version of the message as an Unicode string, Buffer, Stream or an object {path: '...'} + */ + text?: string|Buffer|NodeJS.ReadableStream|AttachmentObject; + /** + * The HTML version of the message as an Unicode string, Buffer, Stream or an object {path: '...'} + */ + html?: string|Buffer|NodeJS.ReadableStream|AttachmentObject; + /** + * An object or array of additional header fields (e.g. {"X-Key-Name": "key value"} or [{key: "X-Key-Name", value: "val1"}, {key: "X-Key-Name", value: "val2"}]) + */ + headers?: any; + /** + * An array of attachment objects (see below for details) + */ + attachments?: AttachmentObject[]; + /** + * An array of alternative text contents (in addition to text and html parts) (see below for details) + */ + alternatives?: AttachmentObject[]; + /** + * optional Message-Id value, random value will be generated if not set + */ + messageId?: string; + /** + * optional Date value, current UTC string will be used if not set + */ + date?: Date; + /** + * optional transfer encoding for the textual parts (defaults to 'quoted-printable') + */ + encoding?: string; + } + + export interface SentMessageInfo { + /** + * most transports should return the final Message-Id value used with this property + */ + messageId: string; + /** + * includes the envelope object for the message + */ + envelope: any; + /** + * is an array returned by SMTP transports (includes recipient addresses that were accepted by the server) + */ + accepted: string[]; + /** + * is an array returned by SMTP transports (includes recipient addresses that were rejected by the server) + */ + rejected: string[]; + /** + * is an array returned by Direct SMTP transport. Includes recipient addresses that were temporarily rejected together with the server response + */ + pending?: string[]; + /** + * is a string returned by SMTP transports and includes the last SMTP response from the server + */ + response: string; + } + + /** + * This is what you implement to create a new transporter yourself + */ + export interface Transport { + name: string; + version: string; + send(mail: SendMailOptions, callback?: (error: Error, info: SentMessageInfo) => void): void; + close(): void; + } + +} 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/page/page.d.ts b/page/page.d.ts index dd76823ecf..682322f3fa 100644 --- a/page/page.d.ts +++ b/page/page.d.ts @@ -86,6 +86,11 @@ declare namespace PageJS { * */ redirect(page: string): void; + /** + * Replace `path` with optional `state` object. + * + */ + replace(path: string, state?: any, init?: boolean, dispatch?: boolean): Context; /** * Navigate to the given path. * 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/pikaday/pikaday.d.ts b/pikaday/pikaday.d.ts index 3e4f80df9a..913ea69613 100644 --- a/pikaday/pikaday.d.ts +++ b/pikaday/pikaday.d.ts @@ -10,6 +10,14 @@ declare class Pikaday { constructor(options: Pikaday.PikadayOptions); + /** + * Extends the existing configuration options for Pikaday object with the options provided. + * Can be used to change/extend the configurations on runtime. + * @param options full/partial configuration options. + * @returns {} extended configurations. + */ + config(options: Pikaday.PikadayOptions): Pikaday.PikadayOptions; + /** * Returns the selected date in a string format. If Moment.js exists * (recommended) then Pikaday can return any format that Moment 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..dcbdb401cb --- /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): number[]; + /** + * 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: number): 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/react-bootstrap/react-bootstrap-tests.tsx b/react-bootstrap/react-bootstrap-tests.tsx index 2712853f28..e8646d79ea 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, SafeAnchor, + 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,576 @@ 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 → + +
+ +
+ + ← Previous + Next → + +
+ +
+ + Tab 1 content + Tab 2 content + Tab 3 content + +
+ +
+ + + + + + + + + Tab 1 content + + + Tab 2 content + + + + + +
+ +
+ + Previous + Next + +
+ +
+ + ← Previous Page + Next Page → + +
+ +
+ + ← Previous + Next → + +
+ +
+
+ +
+ +
+ + +
-
-
- -
- - -
+ buttonComponentClass={( props:any ) => + + } + maxButtons={10}/>
- - Holy guacamole! Best check yo self, you're not looking too good. - + + Holy guacamole! Best check yo self, you're not looking too good. +
- - - 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.

-
-
-
+ + + 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.

+
+
+
- - - <{'Col xs={12} md={8}'} /> - <{'Col xs={6} md={4}'} /> - + + + <{'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} md={4}'} /> + <{'Col xs={6} md={4}'} /> + <{'Col xs={6} md={4}'} /> + - - <{'Col xs={6} xsOffset={6}'} /> - + + <{'Col xs={6} xsOffset={6}'} /> + - - <{'Col md={6} mdPush={6}'} /> - <{'Col md={6} mdPull={6}'} /> - - + + <{'Col md={6} mdPush={6}'} /> + <{'Col md={6} mdPull={6}'} /> + +
- - - - - - - - - - - - - + + + + + + + + + + + + +
- - Item 1 - Item 2 - ... - + + Item 1 + Item 2 + ... +
- - Link 1 - Link 2 - - Trigger an alert - - + + Link 1 + Link 2 + + Trigger an alert + +
- - Link 1 - Link 2 - Link 3 - + + Link 1 + Link 2 + Link 3 +
- - Success - Info - Warning - Danger - + + Success + Info + Warning + Danger +
- - Some body text - Linked item - Danger styling - + + Some body text + Linked item + Danger styling +
-
-

Label

-

Label

-

Label

-

Label

-
Label
-

Label

-
+
+

Label

+

Label

+

Label

+

Label

+
Label
+

Label

+
-
-   -   -   -   -   - -
+
+   +   +   +   +   + +
-

Badges 42

+

Badges 42

- -

Hello, world!

-

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

-

-
+ +

Hello, world!

+

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

+

+
@@ -727,7 +796,7 @@ export class ReactBootstrapTest extends Component {
- Example page header Subtext for header + Example page header Subtext for header
@@ -735,247 +804,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..c39efed388 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 { //