From e3a835a4dc33c942eb5b01c52af8fc2d394435ed Mon Sep 17 00:00:00 2001 From: Flavio Torres Date: Tue, 26 Sep 2017 23:52:20 -0300 Subject: [PATCH 001/128] Parse.Relation.add and Parse.Relation.remove can accept a Array of Parse.Object --- types/parse/index.d.ts | 4 ++-- types/parse/parse-tests.ts | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index 82194e65a2..ee79e94955 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -280,13 +280,13 @@ declare namespace Parse { constructor(parent?: S, key?: string); //Adds a Parse.Object or an array of Parse.Objects to the relation. - add(object: T): void; + add(object: T | Array): void; // Returns a Parse.Query that is limited to objects in this relation. query(): Query; // Removes a Parse.Object or an array of Parse.Objects from this relation. - remove(object: T): void; + remove(object: T | Array): void; } /** diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index 76440e46d3..eba5adc91b 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -227,7 +227,15 @@ function test_analytics() { } function test_relation() { + var game1 = new Game(); + var game2 = new Game(); + new Parse.User().relation("games").query().find().then((g: Game[]) => { }); + new Parse.User().relation("games").add(game1) + new Parse.User().relation("games").add([game1, game2]) + + new Parse.User().relation("games").remove(game1) + new Parse.User().relation("games").remove([game1, game2]) } function test_user_acl_roles() { From 26d39cd9cf9cd16765f560cbe02b873ba5ba41a1 Mon Sep 17 00:00:00 2001 From: Flavio Torres Date: Tue, 9 Jan 2018 09:04:19 -0200 Subject: [PATCH 002/128] Parse.Object set and save methods can receive a object as parameter --- types/parse/index.d.ts | 8 +++++--- types/parse/parse-tests.ts | 9 ++++++++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index 8afefce1d5..0042e1d9e6 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -98,11 +98,11 @@ declare namespace Parse { reject(error: any): void; resolve(result: any): void; then(resolvedCallback: (...values: T[]) => IPromise, - rejectedCallback?: (reason: any) => IPromise): IPromise; + rejectedCallback?: (reason: any) => IPromise): IPromise; then(resolvedCallback: (...values: T[]) => U, - rejectedCallback?: (reason: any) => IPromise): IPromise; + rejectedCallback?: (reason: any) => IPromise): IPromise; then(resolvedCallback: (...values: T[]) => U, - rejectedCallback?: (reason: any) => U): IPromise; + rejectedCallback?: (reason: any) => U): IPromise; } interface Pointer { @@ -373,7 +373,9 @@ declare namespace Parse { remove(attr: string, item: any): any; save(attrs?: { [key: string]: any } | null, options?: Object.SaveOptions): Promise; save(key: string, value: any, options?: Object.SaveOptions): Promise; + save(attrs: object, options?: Object.SaveOptions): Promise; set(key: string, value: any, options?: Object.SetOptions): boolean; + set(attrs: object, options?: Object.SetOptions): boolean; setACL(acl: ACL, options?: SuccessFailureOptions): boolean; toPointer(): Pointer; unset(attr: string, options?: any): any; diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index dbfa82fa3f..2c122a295c 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -57,6 +57,12 @@ function test_object() { gameScore.set("cheatMode", false); + // Setting attrs using object + gameScore.set({ + level: '10', + difficult: 15 + }); + const score = gameScore.get("score"); const playerName = gameScore.get("playerName"); const cheatMode = gameScore.get("cheatMode"); @@ -274,6 +280,7 @@ function test_user_acl_roles() { game.setACL(new Parse.ACL(Parse.User.current())); game.save().then((game: Game) => { }); game.save(null, { useMasterKey: true }); + game.save({ score: '10' }, { useMasterKey: true }); const groupACL = new Parse.ACL(); @@ -366,7 +373,7 @@ function test_cloud_functions() { }); Parse.Cloud.beforeDelete('MyCustomClass', (request: Parse.Cloud.BeforeDeleteRequest, - response: Parse.Cloud.BeforeDeleteResponse) => { + response: Parse.Cloud.BeforeDeleteResponse) => { // result }); From 8656d6391434e77b76a5af0d8105922ca1029650 Mon Sep 17 00:00:00 2001 From: Flavio Torres Date: Tue, 9 Jan 2018 09:31:21 -0200 Subject: [PATCH 003/128] Parse.User signup method options fix --- types/parse/index.d.ts | 9 +++++++-- types/parse/parse-tests.ts | 8 ++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index 0042e1d9e6..1973c8938b 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -31,6 +31,11 @@ declare namespace Parse { interface SuccessFailureOptions extends SuccessOption, ErrorOption { } + interface SignUpOptions { + useMasterKey?: boolean; + installationId?: string; + } + interface SessionTokenOption { sessionToken?: string; } @@ -741,7 +746,7 @@ declare namespace Parse { class User extends Object { static current(): User | undefined; - static signUp(username: string, password: string, attrs: any, options?: SuccessFailureOptions): Promise; + static signUp(username: string, password: string, attrs: any, options?: SignUpOptions): Promise; static logIn(username: string, password: string, options?: SuccessFailureOptions): Promise; static logOut(): Promise; static allowCustomUserClass(isAllowed: boolean): void; @@ -749,7 +754,7 @@ declare namespace Parse { static requestPasswordReset(email: string, options?: SuccessFailureOptions): Promise; static extend(protoProps?: any, classProps?: any): any; - signUp(attrs: any, options?: SuccessFailureOptions): Promise; + signUp(attrs: any, options?: SignUpOptions): Promise; logIn(options?: SuccessFailureOptions): Promise; authenticated(): boolean; isCurrent(): boolean; diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index 2c122a295c..87194ba02c 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -252,6 +252,14 @@ function test_relation() { new Parse.User().relation("games").remove([game1, game2]) } +function test_user() { + const user = new Parse.User(); + user.set("username", "my name"); + user.set("password", "my pass"); + user.set("email", "email@example.com"); + user.signUp(null, { useMasterKey: true }); +} + function test_user_acl_roles() { const user = new Parse.User(); From d4db7918028efa97f6d046bb33789e4ae169027b Mon Sep 17 00:00:00 2001 From: Derek Wickern Date: Sat, 27 Jan 2018 19:04:30 -0800 Subject: [PATCH 004/128] ember-data: fix error when using async/await --- types/ember-data/index.d.ts | 4 ++-- types/ember-data/test/store.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/types/ember-data/index.d.ts b/types/ember-data/index.d.ts index a59ab4de97..e485edff21 100644 --- a/types/ember-data/index.d.ts +++ b/types/ember-data/index.d.ts @@ -854,7 +854,7 @@ declare module "ember-data" { */ interface PromiseArray extends Ember.ArrayProxy, - Ember.PromiseProxyMixin> {} + Ember.PromiseProxyMixin> {} class PromiseArray {} /** * A `PromiseObject` is an object that acts like both an `Ember.Object` @@ -865,7 +865,7 @@ declare module "ember-data" { */ interface PromiseObject extends Ember.ObjectProxy, - Ember.PromiseProxyMixin> {} + Ember.PromiseProxyMixin {} class PromiseObject {} /** * A PromiseManyArray is a PromiseArray that also proxies certain method calls diff --git a/types/ember-data/test/store.ts b/types/ember-data/test/store.ts index 46b0987981..a651cd23db 100644 --- a/types/ember-data/test/store.ts +++ b/types/ember-data/test/store.ts @@ -4,8 +4,10 @@ import { assertType } from "./lib/assert"; declare const store: DS.Store; +class Comment extends DS.Model {} class Post extends DS.Model { title = DS.attr('string'); + comments = DS.hasMany('comment'); } let post = store.createRecord('post', { @@ -74,6 +76,34 @@ const MyRoute = Ember.Route.extend({ } }); +const MyRouteAsync = Ember.Route.extend({ + async beforeModel(): Promise> { + const store = Ember.get(this, 'store'); + return await store.findAll('someStoreRecord'); + }, + async model(): Promise { + const store = this.get('store'); + return await store.findRecord('someStoreRecord', 1); + }, + async afterModel(): Promise> { + const post = await this.get('store').findRecord('post', 1); + return await post.get('comments'); + } +}); + +class MyRouteAsyncES6 extends Ember.Route { + async beforeModel(): Promise> { + return await this.store.findAll('someStoreRecord'); + } + async model(): Promise { + return await this.store.findRecord('someStoreRecord', 1); + } + async afterModel(): Promise> { + const post = await this.store.findRecord('post', 1); + return await post.get('comments'); + } +} + // GET to /users?filter[email]=tomster@example.com const tom = store.query('user', { filter: { From 45b0c5292e28b3a29cdf870ec1d231902293cb86 Mon Sep 17 00:00:00 2001 From: Derek Wickern Date: Mon, 29 Jan 2018 07:05:40 -0800 Subject: [PATCH 005/128] silence "no-return-await" --- types/ember-data/tslint.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/ember-data/tslint.json b/types/ember-data/tslint.json index 6d765664cf..bd25c193fd 100644 --- a/types/ember-data/tslint.json +++ b/types/ember-data/tslint.json @@ -13,6 +13,7 @@ "prefer-const": false, "no-unnecessary-generics": false, "no-declare-current-package": false, - "no-self-import": false + "no-self-import": false, + "no-return-await": false // used in tests } } From 0e0af52729eacebeceb0be751ff90d8d319115df Mon Sep 17 00:00:00 2001 From: Anatoly Belonog Date: Thu, 1 Feb 2018 19:05:56 +0700 Subject: [PATCH 006/128] [async-lock] update types and tests --- types/async-lock/async-lock-tests.ts | 7 ++++--- types/async-lock/index.d.ts | 4 ++-- types/async-lock/tsconfig.json | 0 types/async-lock/tslint.json | 0 4 files changed, 6 insertions(+), 5 deletions(-) mode change 100644 => 100755 types/async-lock/async-lock-tests.ts mode change 100644 => 100755 types/async-lock/index.d.ts mode change 100644 => 100755 types/async-lock/tsconfig.json mode change 100644 => 100755 types/async-lock/tslint.json diff --git a/types/async-lock/async-lock-tests.ts b/types/async-lock/async-lock-tests.ts old mode 100644 new mode 100755 index c6866d270b..64a1e89c75 --- a/types/async-lock/async-lock-tests.ts +++ b/types/async-lock/async-lock-tests.ts @@ -6,9 +6,9 @@ lock.acquire("key", (done) => { done(); }, (err, ret) => { /* ... */ }); -lock.acquire("key", (done) => { - done(); -}).then(() => { /* ... */ }); +lock.acquire("key", (done) => { done(); }) + .then(() => { /* ... */ }) + .catch(() => { /* ... */ }); lock.acquire("key", () => "stringValue") // Check returned value's type is inherited properly @@ -23,6 +23,7 @@ lock.acquire([ "key1", "key2" ], (done) => { }, (err, ret) => { /* ... */ }); lock.isBusy(); +lock.isBusy('key') const lock2 = new AsyncLock({ timeout : 5000 }); const lock3 = new AsyncLock({ maxPending : 5000 }); diff --git a/types/async-lock/index.d.ts b/types/async-lock/index.d.ts old mode 100644 new mode 100755 index 5527482748..37bfe33aaf --- a/types/async-lock/index.d.ts +++ b/types/async-lock/index.d.ts @@ -21,13 +21,13 @@ declare class AsyncLock { acquire(key: string | string[], fn: (() => T | PromiseLike) | ((done: AsyncLockDoneCallback) => any), - opts?: AsyncLockOptions): PromiseLike; + opts?: AsyncLockOptions): Promise; acquire(key: string | string[], fn: (done: AsyncLockDoneCallback) => any, cb: AsyncLockDoneCallback, opts?: AsyncLockOptions): void; - isBusy(): boolean; + isBusy(key?: string): boolean; } declare namespace AsyncLock { } diff --git a/types/async-lock/tsconfig.json b/types/async-lock/tsconfig.json old mode 100644 new mode 100755 diff --git a/types/async-lock/tslint.json b/types/async-lock/tslint.json old mode 100644 new mode 100755 From 8d89c445b273b94e9187d78dac18229aa3cee490 Mon Sep 17 00:00:00 2001 From: Anatoly Belonog Date: Thu, 1 Feb 2018 19:15:19 +0700 Subject: [PATCH 007/128] add version and update authors --- types/async-lock/index.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/async-lock/index.d.ts b/types/async-lock/index.d.ts index 37bfe33aaf..9e56e00a21 100755 --- a/types/async-lock/index.d.ts +++ b/types/async-lock/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for async-lock +// Type definitions for async-lock 1.1.0 // Project: https://github.com/rain1017/async-lock -// Definitions by: Elisée MAURER , Alejandro +// Definitions by: Elisée MAURER +// Alejandro +// Anatoly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 From b0f63edb426da8bc99cec9994d227a6bfa523303 Mon Sep 17 00:00:00 2001 From: Flarna Date: Wed, 7 Feb 2018 22:05:33 +0100 Subject: [PATCH 008/128] [sinon] allow SinonSpyCall for some asserts --- types/sinon/index.d.ts | 14 +++++++------- types/sinon/sinon-tests.ts | 12 ++++++++++++ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/types/sinon/index.d.ts b/types/sinon/index.d.ts index f0433a694e..9348f3a690 100644 --- a/types/sinon/index.d.ts +++ b/types/sinon/index.d.ts @@ -353,19 +353,19 @@ declare namespace Sinon { calledThrice(spy: SinonSpy): void; callCount(spy: SinonSpy, count: number): void; callOrder(...spies: SinonSpy[]): void; - calledOn(spy: SinonSpy, obj: any): void; + calledOn(spy: SinonSpy | SinonSpyCall, obj: any): void; alwaysCalledOn(spy: SinonSpy, obj: any): void; - calledWith(spy: SinonSpy, ...args: any[]): void; + calledWith(spy: SinonSpy | SinonSpyCall, ...args: any[]): void; alwaysCalledWith(spy: SinonSpy, ...args: any[]): void; neverCalledWith(spy: SinonSpy, ...args: any[]): void; - calledWithExactly(spy: SinonSpy, ...args: any[]): void; + calledWithExactly(spy: SinonSpy | SinonSpyCall, ...args: any[]): void; alwaysCalledWithExactly(spy: SinonSpy, ...args: any[]): void; - calledWithMatch(spy: SinonSpy, ...args: any[]): void; + calledWithMatch(spy: SinonSpy | SinonSpyCall, ...args: any[]): void; alwaysCalledWithMatch(spy: SinonSpy, ...args: any[]): void; neverCalledWithMatch(spy: SinonSpy, ...args: any[]): void; - threw(spy: SinonSpy): void; - threw(spy: SinonSpy, exception: string): void; - threw(spy: SinonSpy, exception: any): void; + threw(spy: SinonSpy | SinonSpyCall): void; + threw(spy: SinonSpy | SinonSpyCall, exception: string): void; + threw(spy: SinonSpy | SinonSpyCall, exception: any): void; alwaysThrew(spy: SinonSpy): void; alwaysThrew(spy: SinonSpy, exception: string): void; alwaysThrew(spy: SinonSpy, exception: any): void; diff --git a/types/sinon/sinon-tests.ts b/types/sinon/sinon-tests.ts index 2e2286e538..16ec014b21 100644 --- a/types/sinon/sinon-tests.ts +++ b/types/sinon/sinon-tests.ts @@ -88,6 +88,18 @@ function testNine() { sinon.assert.calledWithMatch(callback, { x: 5 }); sinon.assert.alwaysCalledWithMatch(callback, { y: 5 }); sinon.assert.neverCalledWithMatch(callback, { x: 6 }); + + callback.call("this", "that"); + callback.throws("Error"); + try { + callback(15); + } catch (e) { } + sinon.assert.calledWith(callback.firstCall, { x: 5, y: 5}); + sinon.assert.calledWithExactly(callback.firstCall, { x: 5, y: 5 }); + sinon.assert.calledWithMatch(callback.firstCall, { x: 5 }); + sinon.assert.calledOn(callback.secondCall, "this"); + sinon.assert.threw(callback.thirdCall); + sinon.assert.threw(callback.thirdCall, "Error"); } function testAssert() { From 424c62b965785ae396dda68f026f5d3c45a15089 Mon Sep 17 00:00:00 2001 From: Ryo Kawaguchi Date: Fri, 9 Feb 2018 21:22:29 +0900 Subject: [PATCH 009/128] Add missing properties to material-ui/DialogProps. --- types/material-ui/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 9624e6d4a2..030dd21bff 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -1051,6 +1051,8 @@ declare namespace __MaterialUI { open: boolean; overlayClassName?: string; overlayStyle?: React.CSSProperties; + paperClassName?: string; + paperProps?: any; repositionOnUpdate?: boolean; style?: React.CSSProperties; title?: React.ReactNode; From 5d912ee0850eb7ac08af1a0ac40291a808f33f9c Mon Sep 17 00:00:00 2001 From: Ryo Kawaguchi Date: Fri, 9 Feb 2018 22:58:42 +0900 Subject: [PATCH 010/128] Increment version. --- types/material-ui/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 030dd21bff..85a8f46f65 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for material-ui v0.20.0 +// Type definitions for material-ui v0.20.1 // Project: https://github.com/callemall/material-ui // Definitions by: Nathan Brown // Igor Beagorudsky From 24fd4930ae9f88ce50e026b261f710aa1cdf92fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Richard=20Jedli=C4=8Dka?= Date: Fri, 9 Feb 2018 15:35:38 +0100 Subject: [PATCH 011/128] Add module declaration Fix '.../node_modules/@types/fingerprintjs2/index.d.ts' is not a module. --- types/fingerprintjs2/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/fingerprintjs2/index.d.ts b/types/fingerprintjs2/index.d.ts index 94b705b807..afd500647c 100644 --- a/types/fingerprintjs2/index.d.ts +++ b/types/fingerprintjs2/index.d.ts @@ -41,3 +41,7 @@ interface Fingerprint2Options { excludePixelRatio?: boolean; excludeHardwareConcurrency?: boolean; } + +declare module "fingerprintjs2" { + export = Fingerprint2; +} From 1323c4c63a8a3fa35e2ec8810be1d14ebbf164a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Richard=20Jedli=C4=8Dka?= Date: Fri, 9 Feb 2018 15:48:26 +0100 Subject: [PATCH 012/128] Use export without a module declaration See https://github.com/Microsoft/dtslint/blob/master/docs/no-declare-current-package.md --- types/fingerprintjs2/index.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/types/fingerprintjs2/index.d.ts b/types/fingerprintjs2/index.d.ts index afd500647c..b4d8d5ff6c 100644 --- a/types/fingerprintjs2/index.d.ts +++ b/types/fingerprintjs2/index.d.ts @@ -42,6 +42,4 @@ interface Fingerprint2Options { excludeHardwareConcurrency?: boolean; } -declare module "fingerprintjs2" { - export = Fingerprint2; -} +export = Fingerprint2; From 32db52f565c5999fbaa6a23e1e3c9ca2bc835667 Mon Sep 17 00:00:00 2001 From: Zev Spitz Date: Sat, 10 Feb 2018 21:38:13 +0200 Subject: [PATCH 013/128] Default properties; extended samples --- types/activex-wia/activex-wia-tests.ts | 546 ++++++++++++++++++++++--- types/activex-wia/index.d.ts | 356 +++++++++------- types/activex-wia/tslint.json | 5 +- 3 files changed, 689 insertions(+), 218 deletions(-) diff --git a/types/activex-wia/activex-wia-tests.ts b/types/activex-wia/activex-wia-tests.ts index d8046ef319..a5babea924 100644 --- a/types/activex-wia/activex-wia-tests.ts +++ b/types/activex-wia/activex-wia-tests.ts @@ -1,79 +1,493 @@ +const collectionToArray = (col: { Item(key: any): T }): T[] => { + const results: T[] = []; + const enumerator = new Enumerator(col); + enumerator.moveFirst(); + while (!enumerator.atEnd()) { + results.push(enumerator.item()); + enumerator.moveNext(); + } + return results; +}; + // source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx +{ + const cd = new ActiveXObject('WIA.CommonDialog'); + const dm = new ActiveXObject('WIA.DeviceManager'); -// Convert a file -let commonDialog = new ActiveXObject('WIA.CommonDialog'); -let img = commonDialog.ShowAcquireImage(); + // Download new items as they are created + { + dm.RegisterEvent(WIA.EventID.wiaEventItemCreated, WIA.Miscellaneous.wiaAnyDeviceID); + ActiveXObject.on(dm, 'OnEvent', ['EventID', 'DeviceID', 'ItemID'], x => { + const dev = dm.DeviceInfos(x.DeviceID).Connect(); + const itm = dev.GetItem(x.ItemID); + const img = cd.ShowTransfer(itm); + const v = img.FileData; + // Picture type not available in Javascript + }); + } -// when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these: -let jpegFormatID = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}'; -if (img.FormatID !== jpegFormatID) { - const ip = new ActiveXObject('WIA.ImageProcess'); - ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID); - ip.Filters.Item(1).Properties.Item('FormatID').Value = jpegFormatID; - img = ip.Apply(img); -} -// with this: -/*if (img.FormatID !== WIA.FormatID.wiaFormatJPEG) { - let ip = new ActiveXObject('WIA.ImageProcess'); - ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID); - ip.Filters.Item(1).Properties.Item('FormatID').Value = WIA.FormatID.wiaFormatJPEG; - img = ip.Apply(img); -}*/ - -// Take a picture -let dev = commonDialog.ShowSelectDevice(); -if (dev.Type === WIA.WiaDeviceType.CameraDeviceType) { - // when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these: - const commandID = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}'; - const itm = dev.ExecuteCommand(commandID); - - // with this: - // let itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture); -} - -// Display detailed property information -dev = commonDialog.ShowSelectDevice(); -let e = new Enumerator(dev.Properties); // no foreach over ActiveX collections -e.moveFirst(); -while (!e.atEnd()) { - const p = e.item(); - let s = `${p.Name} (${p.PropertyID}) = `; - if (p.IsVector) { - s += '[vector of data]'; - } else { - s += p.Value; - if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType) { - if (p.Value !== p.SubTypeDefault) { - s += ` (Default = ${p.SubTypeDefault})`; - } + // Convert a file + { + let img = cd.ShowAcquireImage(); + if (img && img.FormatID !== WIA.FormatID.wiaFormatJPEG) { + const ip = new ActiveXObject('WIA.ImageProcess'); + ip.Filters.Add(ip.FilterInfos('Convert').FilterID); + ip.Filters(1).Properties('FormatID').Value = WIA.FormatID.wiaFormatJPEG; + img = ip.Apply(img); } } - if (p.IsReadOnly) { - s += ' [READ ONLY]'; - } else { - switch (p.SubType) { - case WIA.WiaSubType.FlagSubType: - case WIA.WiaSubType.ListSubType: - if (p.SubType === WIA.WiaSubType.FlagSubType) { - s += ' [valid flags include: '; + // Take a picture + { + const dev = cd.ShowSelectDevice(); + if (dev && dev.Type === WIA.WiaDeviceType.CameraDeviceType) { + const item = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture); + } + } + + // Display detailed property information + { + const dev = cd.ShowSelectDevice(); + if (dev) { + collectionToArray(dev.Properties).forEach(p => { + let s = `${p.Name} (${p.PropertyID}) = `; + if (p.IsVector) { + s += '[vector of data]'; } else { - s += ' [valid values include: '; - } - const count = p.SubTypeValues.Count; - for (let i = 1; i <= count; i++) { - s += p.SubTypeValues.Item(i); - if (i < count) { - s += ', '; + s += p.Value; + if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType + && p.Value !== p.SubTypeDefault) { + s += ` (Default = ${p.SubTypeDefault})`; } } - s += ']'; - break; - case WIA.WiaSubType.RangeSubType: - s += ` [valid values in the range from ${p.SubTypeMin} to ${p.SubTypeMax} in increments of ${p.SubTypeStep}]`; - break; + + if (p.IsReadOnly) { + s += ' [READ ONLY]'; + } else { + switch (p.SubType) { + case WIA.WiaSubType.FlagSubType: + case WIA.WiaSubType.ListSubType: + const count = p.SubTypeValues.Count; + const items: string[] = []; + for (let i = 1; i <= count; i++) { + items.push(p.SubTypeValues(i)); + } + const descr = p.SubType === WIA.WiaSubType.FlagSubType ? 'flags' : 'values'; + s += ` [valid ${descr} include: ${items.join(',')}]`; + break; + case WIA.WiaSubType.RangeSubType: + s += ` [valid values in the range from ${p.SubTypeMin} to ${p.SubTypeMax} in increments of ${p.SubTypeStep}]`; + break; + } + } + + WScript.Echo(s); + }); } } - WScript.Echo(s); + // Determine whether the selected device is a camera + { + const dev = cd.ShowSelectDevice(); + if (dev && dev.Type === WIA.WiaDeviceType.CameraDeviceType) { + WScript.Echo('Selectd device is a camera'); + } + } + + // Count root - level images for transfer + { + const dev = cd.ShowSelectDevice(); + if (dev) { + const count = collectionToArray(dev.Items).filter(f => { + const imageFlag = WIA.WiaItemFlag.ImageItemFlag; + return (f.Properties('Item Flags').Value & imageFlag) === imageFlag; + }).length; + WScript.Echo(`Selected device has ${count} top-level images`); + } + } + + // Display all imagefile properties + { + const img = cd.ShowAcquireImage(); + if (img) { + collectionToArray(img.Properties).forEach(p => { + let contents = ''; + if (p.IsVector) { + contents = '[vector data not emitted]'; + } else if (p.Type === WIA.WiaImagePropertyType.RationalImagePropertyType) { + contents = `${p.Value.Nunerator}/${p.Value.Denominator}`; + } else if (p.Type === WIA.WiaImagePropertyType.StringImagePropertyType) { + contents = `"${p.Value}"`; + } else { + contents = p.Value; + } + WScript.Echo(`${p.Name} (${p.PropertyID}) = ${contents}`); + }); + } + } + + // Determine the event type + { + const dev = cd.ShowSelectDevice(); + if (dev) { + const actionEvent = WIA.WiaEventFlag.ActionEvent; + collectionToArray(dev.Events).forEach(e => { + const msg = (e.Type & actionEvent) === actionEvent ? + `${e.Name} is an Action event` : + `${e.Name} is not an Action event`; + WScript.Echo(msg); + }); + } + } + + // Set rational numerator and denominator + { + const r = new ActiveXObject('WIA.Rational'); + r.Numerator = 1; + r.Denominator = 3; + WScript.Echo(`1/3 = ${r.Value}`); + r.Numerator = 2; + r.Denominator = 6; + WScript.Echo(`2/6 = ${r.Value}`); + } + + // Create and initialize a vector object + { + const v: WIA.Vector = new ActiveXObject('WIA.Vector'); + v.SetFromString('This is a test', true, false); + collectionToArray(v).forEach(chr => WScript.Echo(String.fromCharCode(chr))); + } + + // Display detailed image information + { + const img = new ActiveXObject('WIA.ImageFile'); + img.LoadFile('c:\\windows\\web\\Screen\\img102.jpg'); + + let s = ` +Width = ${img.Width} +Height = ${img.Height} +Depth = ${img.PixelDepth} +Horizontal resolution = ${img.HorizontalResolution} +Vertical resolution = ${img.VerticalResolution} +Frame count = ${img.FrameCount}} + `.trim(); + + let arr: string[] = []; + + if (img.IsIndexedPixelFormat) { arr.push('Pixel data contains palette indexes'); } + if (img.IsAlphaPixelFormat) { arr.push('Pixel data has alpha information'); } + if (img.IsExtendedPixelFormat) { arr.push('Pixel data has extended color information (16 bit/channel)'); } + if (img.IsAnimated) { arr.push('Image is animated'); } + + const propertyTests = [40091, 40092, 40093, 40094, 40095] + .filter(n => img.Properties.Exists(n)) + .map(n => { + const prp = img.Properties(n); + return `${prp.Name} = ${prp.Value.String}`; + }); + arr = arr.concat(propertyTests); + + if (arr.length) { + s += '\n' + arr.join('\n'); + } + + WScript.Echo(s); + } + + // Create an imageprocess object and enumerate filters + { + const ip = new ActiveXObject('WIA.ImageProcess'); + collectionToArray(ip.FilterInfos).forEach(fi => { + const s = [ + fi.Name, + new Array(51).join('='), + fi.Description + ].join('\n'); + WScript.Echo(s); + }); + } + + // Create an imageprocess object and create one of each available filter + { + const ip = new ActiveXObject('WIA.ImageProcess'); + + const stringValue = (v: any) => { + if (typeof v === 'string') { return `"${v}"`; } + return v; + }; + + const listValues = (v: any) => collectionToArray(v).join(', '); + + const listProperties = (filter: WIA.Filter) => { + let s = [ + `${filter.Name} (${filter.FilterID})`, + new Array(51).join('='), + filter.Description, + new Array(51).join('=') + ].map(line => line + '\n').join(''); + + s += collectionToArray(filter.Properties).map(p => { + let contents: string; + + switch (typeof p.Value) { + // these case clauses replace the IsObject function in VB6/VBScript + case 'boolean': + case 'string': + case 'number': + contents = stringValue(p.Value); + default: + switch (p.SubType) { + case WIA.WiaSubType.FlagSubType: + contents = ` // [valid values formed by using the OR operator with the following bit flags: ${listValues(p.SubTypeValues)}]`; + break; + case WIA.WiaSubType.ListSubType: + contents = ` // [valid values from the following list: ${listValues(p.SubTypeValues)}]`; + break; + case WIA.WiaSubType.RangeSubType: + contents = ` // [valid values between ${p.SubTypeMin} and ${p.SubTypeMax}, with a step of ${p.SubTypeStep}]`; + break; + default: + contents = ''; + break; + } + } + + return `ip.Filters(1).Properties("${p.Name}") = ${contents}`; + }).join('\n'); + + WScript.Echo(s); + }; + + collectionToArray(ip.FilterInfos).forEach(fi => { + ip.Filters.Add(fi.FilterID); + listProperties(ip.Filters(1)); + ip.Filters.Remove(1); + }); + } + + // List the supported transfer formats + { + const stringFormat = (fld: string) => { + switch (fld) { + case WIA.FormatID.wiaFormatBMP: return 'BMP'; + case WIA.FormatID.wiaFormatPNG: return 'PNG'; + case WIA.FormatID.wiaFormatGIF: return 'GIF'; + case WIA.FormatID.wiaFormatJPEG: return 'JPEG'; + case WIA.FormatID.wiaFormatTIFF: return 'TIFF'; + default: return 'Unknown'; + } + }; + + const dev = cd.ShowSelectDevice(); + const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true); + if (items) { + WScript.Echo(collectionToArray(items(1).Formats).map(stringFormat).join(', ')); + } + } + + // Enumerate supported commands in commands collection + { + const dev = cd.ShowSelectDevice(); + if (dev && collectionToArray(dev.Commands).some(dc => dc.CommandID === WIA.CommandID.wiaCommandTakePicture)) { + WScript.Echo('Selected device supports the TakePicture command'); + } + } + + // Enumerate root - level items and display their names + { + const dev = cd.ShowSelectDevice(); + if (dev) { + collectionToArray(dev.Items).forEach(item => { + let s: string = item.Properties("Item Name").Value; + if (item.Properties.Exists("Item Time Stamp")) { + const v: WIA.Vector = item.Properties("Item Time Stamp").Value; + if (v.Count === 8) { s += ` (${v.Date})`; } + } + WScript.Echo(s); + }); + } + } + + // Determine the number of items returned by ShowSelectItems + { + const dev = cd.ShowSelectDevice(); + const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true); + if (items) { + WScript.Echo(`You selected ${items.Count} items`); + } + } + + // Enumerate all the supported events for the selected device + { + const dev = cd.ShowSelectDevice(); + if (dev) { + const msg = collectionToArray(dev.Events) + .map(e => `\n${e.Name} (${e.EventID}): ${e.Description}`) + .join(''); + WScript.Echo('The selected device supports the following events: ' + msg); + } + } + + // List all available devices by name and deviceid + collectionToArray(dm.DeviceInfos).forEach(di => { + const name: string = di.Properties("Name").Value; + WScript.Echo(`${name} (${di.DeviceID})`); + }); + + // Display all the properties for the selected device + { + const dev = cd.ShowSelectDevice(); + if (dev) { + collectionToArray(dev.Properties).forEach(p => { + const name = `${p.Name} (${p.PropertyID})`; + let contents: string; + if (p.IsVector) { + contents = '[vector of data]'; + } else if (p.Type === WIA.WiaPropertyType.StringPropertyType) { + contents = `"${p.Value}"`; + } else { + contents = p.Value; + } + WScript.Echo(`${name} = ${contents}`); + }); + } + } + + // Enumerate the supported commands + { + const dev = cd.ShowSelectDevice(); + const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true); + if (items) { + const msg = collectionToArray(items(1).Commands) + .map(c => `${c.Name}: ${c.Description}\n`) + .join(''); + WScript.Echo(`The selected item supports the following commands:\n${msg}`); + } + } + + // Create an imagefile object that contains a blank page + { + const c = 0xFF0000FF; + const v: WIA.Vector = new ActiveXObject('WIA.Vector'); + for (let i = 0; i < 4; i++) { + v.Add(c); + } + const img = v.ImageFile(2, 2); + img.SaveFile('C:\\test.' + img.FileExtension); + } + + interface WshArgumentsBase { + Item(index: TKey): string; + (index: TKey): string; + length: number; + Count(): number; + } + + interface WshArguments extends WshArgumentsBase { // not sure if WshArguments takes a string as well, or only a number + Named: WshArgumentsBase; + Unnamed: WshArgumentsBase; + ShowUsage(): void; + } + + // Implement a windows script host script that runs automatically + { + const args = collectionToArray(WScript.Arguments as WshArguments) + .map(arg => arg.toLowerCase()); + + switch (args.length) { + case 1: + case 2: + const command = `${WScript.FullName} "${WScript.ScriptFullName}" connect`; + const name = 'QuickTransfer'; + const title = 'Quick Scripting Transfer'; + const icon = `${WScript.FullName}, 0`; + const eventID = WIA.EventID.wiaEventDeviceConnected; + const deviceID = args.length === 2 ? args[1] : WIA.Miscellaneous.wiaAnyDeviceID; + + if (args[0] === 'register') { + WScript.Echo('Registering event handler'); + dm.RegisterPersistentEvent(command, name, title, icon, eventID, deviceID); + WScript.Quit(); + } else if (args[0] === 'unregister') { + WScript.Echo('Unregistering event handler'); + dm.UnregisterPersistentEvent(command, name, title, icon, eventID, deviceID); + WScript.Quit(); + } + break; + case 3: + if (args[0] === 'connect') { + const deviceID = args[1].substr(12); + const device = dm.DeviceInfos(deviceID).Connect(); + collectionToArray(device.Items).forEach(item => { + const img = item.Transfer(); + img.SaveFile(`C:\\${item.Properties('Item Name').Value}.${img.FileExtension}`); + + // Uncomment the following lines to remove the picture from the camera after transfer + for (let i = 1; i < device.Items.Count; i++) { + const item2 = device.Items(i); + if (item2.ItemID !== item.ItemID) { continue; } + try { + // some cameras don't support deleting a picture + device.Items.Remove(i); + } catch (error) { + WScript.Echo(error); + } + } + }); + WScript.Quit(); + } + break; + } + + const usage = ` +Usage: + +To register, type: + + ${WScript.ScriptName} register [] + +To unregister, type: + + ${WScript.ScriptName} unregister [] + +Available device ids: +${collectionToArray(dm.DeviceInfos) + .map(device => `${device.DeviceID} '${device.Properties("Name").Value}'`) + .join('\n')} + `.trim(); + + WScript.Echo(usage); + } + + // Count the number of child items available for transfer + { + const device = cd.ShowSelectDevice(); + const items = device && cd.ShowSelectItems(device, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true); + const item = items && items(1); + if (item) { + const count = collectionToArray(item.Items).filter(childItem => { + const flags = childItem.Properties('Item Flags').Value as number; + return (flags & WIA.WiaItemFlag.TransferItemFlag) === WIA.WiaItemFlag.TransferItemFlag; + }).length; + WScript.Echo(`Selected device has ${count} child items that can be transferred.`); + } + } + + // Use a vector object + { + const v: WIA.Vector = new ActiveXObject('WIA.Vector'); + v.Add(1); + v.Add(42); + v.Add(3); + v.Remove(1); + v.Remove(2); + WScript.Echo(`v(1) = ${v(1)}`); + v.Clear(); + v.Add('This'); + v.Add('is'); + v.Add('Cool'); + v.Remove(1); + v.Remove(2); + WScript.Echo(`v(1) = ${v(1)}`); + } } diff --git a/types/activex-wia/index.d.ts b/types/activex-wia/index.d.ts index 7d7cbae727..ae21c9c77c 100644 --- a/types/activex-wia/index.d.ts +++ b/types/activex-wia/index.d.ts @@ -2,22 +2,22 @@ // Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms630368(v=vs.85).aspx // Definitions by: Zev Spitz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Typescript Version: 2.4 +// TypeScript Version: 2.6 declare namespace WIA { /** String versions of globally unique identifiers (GUIDs) that identify common Device and Item commands. */ - // uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017) - /*const enum CommandID { + // tslint:disable-next-line no-const-enum + const enum CommandID { wiaCommandChangeDocument = '{04E725B0-ACAE-11D2-A093-00C04F72DC3C}', wiaCommandDeleteAllItems = '{E208C170-ACAD-11D2-A093-00C04F72DC3C}', wiaCommandSynchronize = '{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}', wiaCommandTakePicture = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}', - wiaCommandUnloadDocument = '{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}' - }*/ + wiaCommandUnloadDocument = '{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}', + } /** String versions of globally unique identifiers (GUIDs) that identify DeviceManager events. */ - // uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017) - /*const enum EventID { + // tslint:disable-next-line no-const-enum + const enum EventID { wiaEventDeviceConnected = '{A28BBADE-64B6-11D2-A231-00C04FA31809}', wiaEventDeviceDisconnected = '{143E4E83-6497-11D2-A231-00C04FA31809}', wiaEventItemCreated = '{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}', @@ -30,64 +30,69 @@ declare namespace WIA { wiaEventScanImage3 = '{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}', wiaEventScanImage4 = '{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}', wiaEventScanOCRImage = '{9D095B89-37D6-4877-AFED-62A297DC6DBE}', - wiaEventScanPrintImage = '{B441F425-8C6E-11D2-977A-0000F87A926F}' - }*/ + wiaEventScanPrintImage = '{B441F425-8C6E-11D2-977A-0000F87A926F}', + } /** String versions of globally unique identifiers (GUIDs) that indicate the file format of an image. */ - // uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017) - /*const enum FormatID { + // tslint:disable-next-line no-const-enum + const enum FormatID { wiaFormatBMP = '{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}', wiaFormatGIF = '{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}', wiaFormatJPEG = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}', wiaFormatPNG = '{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}', - wiaFormatTIFF = '{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}' - }*/ + wiaFormatTIFF = '{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}', + } /** Miscellaneous string constants */ - // uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017) - /*const enum Miscellaneous { + // tslint:disable-next-line no-const-enum + const enum Miscellaneous { wiaAnyDeviceID = '*', - wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}' - }*/ + wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}', + } /** * The WiaDeviceType enumeration specifies the type of device attached to a user's computer. Use the Type property on the DeviceInfo object or the Device - * object to obtain these values from the device. + * object to obtain these values from the device. */ + // tslint:disable-next-line no-const-enum const enum WiaDeviceType { CameraDeviceType = 2, ScannerDeviceType = 1, UnspecifiedDeviceType = 0, - VideoDeviceType = 3 + VideoDeviceType = 3, } /** - * A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with DeviceEv - * ent.Type and a member from the WiaEventFlags enumeration. + * A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with + * DeviceEvent.Type and a member from the WiaEventFlags enumeration. */ + // tslint:disable-next-line no-const-enum const enum WiaEventFlag { ActionEvent = 2, - NotificationEvent = 1 + NotificationEvent = 1, } /** The WiaImageBias enumeration helps specify what type of data the image is intended to represent. */ + // tslint:disable-next-line no-const-enum const enum WiaImageBias { MaximizeQuality = 131072, - MinimizeSize = 65536 + MinimizeSize = 65536, } /** The WiaImageIntent enumeration helps specify what type of data the image is intended to represent. */ + // tslint:disable-next-line no-const-enum const enum WiaImageIntent { ColorIntent = 1, GrayscaleIntent = 2, TextIntent = 4, - UnspecifiedIntent = 0 + UnspecifiedIntent = 0, } /** - * The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection o - * f an ImageFile object. + * The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection + * of an ImageFile object. */ + // tslint:disable-next-line no-const-enum const enum WiaImagePropertyType { ByteImagePropertyType = 1001, LongImagePropertyType = 1004, @@ -103,13 +108,14 @@ declare namespace WIA { VectorOfUndefinedImagePropertyType = 1100, VectorOfUnsignedIntegersImagePropertyType = 1102, VectorOfUnsignedLongsImagePropertyType = 1104, - VectorOfUnsignedRationalsImagePropertyType = 1106 + VectorOfUnsignedRationalsImagePropertyType = 1106, } /** - * An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with Item.Properties("Item - * Flags") and a member from the WiaItemFlags enumeration. + * An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with + * Item.Properties("Item Flags") and a member from the WiaItemFlags enumeration. */ + // tslint:disable-next-line no-const-enum const enum WiaItemFlag { AnalyzeItemFlag = 16, AudioItemFlag = 32, @@ -129,13 +135,14 @@ declare namespace WIA { StorageItemFlag = 4096, TransferItemFlag = 8192, VideoItemFlag = 65536, - VPanoramaItemFlag = 1024 + VPanoramaItemFlag = 1024, } /** - * The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a Dev - * ice or Item object. + * The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a + * Device or Item object. */ + // tslint:disable-next-line no-const-enum const enum WiaPropertyType { BooleanPropertyType = 1, BytePropertyType = 2, @@ -173,28 +180,32 @@ declare namespace WIA { VectorOfUnsignedIntegersPropertyType = 104, VectorOfUnsignedLargeIntegersPropertyType = 109, VectorOfUnsignedLongsPropertyType = 106, - VectorOfVariantsPropertyType = 119 + VectorOfVariantsPropertyType = 119, } /** - * The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for t - * he property. + * The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for + * the property. */ + // tslint:disable-next-line no-const-enum const enum WiaSubType { FlagSubType = 3, ListSubType = 2, RangeSubType = 1, - UnspecifiedSubType = 0 + UnspecifiedSubType = 0, } /** * The CommonDialog control is an invisible-at-runtime control that contains all the methods that display a User Interface. A CommonDialog control can be - * created using "WIA.CommonDialog" in a call to CreateObject or by dropping a CommonDialog on a form. + * created using "WIA.CommonDialog" in a call to CreateObject or by dropping a CommonDialog on a form. */ - interface CommonDialog { + class CommonDialog { + private constructor(); + private 'WIA.CommonDialog_typekey': CommonDialog; + /** - * Displays one or more dialog boxes that enable the user to acquire an image from a hardware device for image acquisition and returns an ImageFile object - * on success, otherwise Nothing + * Displays one or more dialog boxes that enable the user to acquire an image from a hardware device for image acquisition and returns an ImageFile + * object on success, otherwise Nothing * @param WIA.WiaDeviceType [DeviceType=0] * @param WIA.WiaImageIntent [Intent=0] * @param WIA.WiaImageBias [Bias=131072] @@ -203,11 +214,11 @@ declare namespace WIA { * @param boolean [UseCommonUI=true] * @param boolean [CancelError=false] */ - ShowAcquireImage( - DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean): ImageFile; + ShowAcquireImage(DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, + CancelError?: boolean): ImageFile | null; /** Launches the Windows Scanner and Camera Wizard and returns Nothing. Future versions may return a collection of ImageFile objects. */ - ShowAcquisitionWizard(Device: Device): any; + ShowAcquisitionWizard(Device: Device): null; /** * Displays the properties dialog box for the specified Device @@ -222,38 +233,41 @@ declare namespace WIA { ShowItemProperties(Item: Item, CancelError?: boolean): void; /** Launches the Photo Printing Wizard with the absolute path of a specific file or Vector of absolute paths to files */ - ShowPhotoPrintingWizard(Files: any): void; + ShowPhotoPrintingWizard(Files: string | Vector): void; /** - * Displays a dialog box that enables the user to select a hardware device for image acquisition. Returns the selected Device object on success, otherwise - * Nothing + * Displays a dialog box that enables the user to select a hardware device for image acquisition. Returns the selected Device object on success, + * otherwise Nothing * @param WIA.WiaDeviceType [DeviceType=0] * @param boolean [AlwaysSelectDevice=false] * @param boolean [CancelError=false] */ - ShowSelectDevice(DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean): Device; + ShowSelectDevice(DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean): Device | null; /** - * Displays a dialog box that enables the user to select an item for transfer from a hardware device for image acquisition. Returns the selection as an It - * ems collection on success, otherwise Nothing + * Displays a dialog box that enables the user to select an item for transfer from a hardware device for image acquisition. Returns the selection as an + * Items collection on success, otherwise Nothing * @param WIA.WiaImageIntent [Intent=0] * @param WIA.WiaImageBias [Bias=131072] * @param boolean [SingleSelect=true] * @param boolean [UseCommonUI=true] * @param boolean [CancelError=false] */ - ShowSelectItems(Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean): Items; + ShowSelectItems(Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean): Items | null; /** * Displays a progress dialog box while transferring the specified Item to the local machine. See Item.Transfer for additional information. * @param string [FormatID='{00000000-0000-0000-0000-000000000000}'] * @param boolean [CancelError=false] */ - ShowTransfer(Item: Item, FormatID?: string, CancelError?: boolean): any; + ShowTransfer(Item: Item, FormatID?: string, CancelError?: boolean): ImageFile; } /** The Device object represents an active connection to an imaging device. */ - interface Device { + class Device { + private constructor(); + private 'WIA.Device_typekey': Device; + /** A collection of all commands for this imaging device */ readonly Commands: DeviceCommands; @@ -264,8 +278,8 @@ declare namespace WIA { readonly Events: DeviceEvents; /** - * Issues the command specified by CommandID to the imaging device. CommandIDs are device dependent. Valid CommandIDs for this Device are contained in the - * Commands collection. + * Issues the command specified by CommandID to the imaging device. CommandIDs are device dependent. Valid CommandIDs for this Device are contained in + * the Commands collection. */ ExecuteCommand(CommandID: string): Item; @@ -280,13 +294,13 @@ declare namespace WIA { /** Returns the Type of Device */ readonly Type: WiaDeviceType; - - /** Returns the underlying IWiaItem interface for this Device object */ - readonly WiaItem: any; } /** The DeviceCommand object describes a CommandID that can be used when calling ExecuteCommand on a Device or Item object. */ - interface DeviceCommand { + class DeviceCommand { + private constructor(); + private 'WIA.DeviceCommand_typekey': DeviceCommand; + /** Returns the commandID for this Command */ readonly CommandID: string; @@ -298,8 +312,8 @@ declare namespace WIA { } /** - * The DeviceCommands object is a collection of all the supported DeviceCommands for an imaging device. See the Commands property of a Device or Item obje - * ct for more details on determining the collection of supported device commands. + * The DeviceCommands object is a collection of all the supported DeviceCommands for an imaging device. See the Commands property of a Device or Item + * object for more details on determining the collection of supported device commands. */ interface DeviceCommands { /** Returns the number of members in the collection */ @@ -307,10 +321,16 @@ declare namespace WIA { /** Returns the specified item in the collection by position */ Item(Index: number): DeviceCommand; + + /** Returns the specified item in the collection by position */ + (Index: number): DeviceCommand; } /** The DeviceEvent object describes an EventID that can be used when calling RegisterEvent or RegisterPersistentEvent on a DeviceManager object. */ - interface DeviceEvent { + class DeviceEvent { + private constructor(); + private 'WIA.DeviceEvent_typekey': DeviceEvent; + /** Returns the event Description */ readonly Description: string; @@ -325,8 +345,8 @@ declare namespace WIA { } /** - * The DeviceEvents object is a collection of all the supported DeviceEvent for an imaging device. See the Events property of a Device object for more det - * ails on determining the collection of supported device events. + * The DeviceEvents object is a collection of all the supported DeviceEvent for an imaging device. See the Events property of a Device object for more + * details on determining the collection of supported device events. */ interface DeviceEvents { /** Returns the number of members in the collection */ @@ -334,13 +354,19 @@ declare namespace WIA { /** Returns the specified item in the collection by position */ Item(Index: number): DeviceEvent; + + /** Returns the specified item in the collection by position */ + (Index: number): DeviceEvent; } /** - * The DeviceInfo object is a container that describes the unchanging (static) properties of an imaging device that is currently connected to the computer - * . + * The DeviceInfo object is a container that describes the unchanging (static) properties of an imaging device that is currently connected to the + * computer. */ - interface DeviceInfo { + class DeviceInfo { + private constructor(); + private 'WIA.DeviceInfo_typekey': DeviceInfo; + /** Establish a connection with this device and return a Device object */ Connect(): Device; @@ -355,59 +381,68 @@ declare namespace WIA { } /** - * The DeviceInfos object is a collection of all the imaging devices currently connected to the computer. See the DeviceInfos property on the DeviceManage - * r object for detail on accessing the DeviceInfos object. + * The DeviceInfos object is a collection of all the imaging devices currently connected to the computer. See the DeviceInfos property on the + * DeviceManager object for detail on accessing the DeviceInfos object. */ interface DeviceInfos { /** Returns the number of members in the collection */ readonly Count: number; /** Returns the specified item in the collection either by position or Device ID */ - Item(Index: any): DeviceInfo; + Item(Index: number | string): DeviceInfo; + + /** Returns the specified item in the collection either by position or Device ID */ + (Index: number | string): DeviceInfo; } /** - * The DeviceManager control is an invisible-at-runtime control that manages the imaging devices connected to the computer. A DeviceManager control can be - * created using "WIA.DeviceManager" in a call to CreateObject or by dropping a DeviceManager on a form. + * The DeviceManager control is an invisible-at-runtime control that manages the imaging devices connected to the computer. A DeviceManager control can + * be created using "WIA.DeviceManager" in a call to CreateObject or by dropping a DeviceManager on a form. */ - interface DeviceManager { + class DeviceManager { + private constructor(); + private 'WIA.DeviceManager_typekey': DeviceManager; + /** A collection of all imaging devices connected to this computer */ readonly DeviceInfos: DeviceInfos; /** * Registers the specified EventID for the specified DeviceID. If DeviceID is "*" then OnEvent will be called whenever the event specified occurs for any - * device. Otherwise, OnEvent will only be called if the event specified occurs on the device specified. + * device. Otherwise, OnEvent will only be called if the event specified occurs on the device specified. * @param string [DeviceID='*'] */ RegisterEvent(EventID: string, DeviceID?: string): void; /** - * Registers the specified Command to launch when the specified EventID for the specified DeviceID occurs. Command can be either a ClassID or the full pat - * h name and the appropriate command-line arguments needed to invoke the application. + * Registers the specified Command to launch when the specified EventID for the specified DeviceID occurs. Command can be either a ClassID or the full + * path name and the appropriate command-line arguments needed to invoke the application. * @param string [DeviceID='*'] */ RegisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void; /** - * Unregisters the specified EventID for the specified DeviceID. UnregisterEvent should only be called for EventID and DeviceID for which you called Regis - * terEvent. + * Unregisters the specified EventID for the specified DeviceID. UnregisterEvent should only be called for EventID and DeviceID for which you called + * RegisterEvent. * @param string [DeviceID='*'] */ UnregisterEvent(EventID: string, DeviceID?: string): void; /** - * Unregisters the specified Command for the specified EventID for the specified DeviceID. UnregisterPersistentEvent should only be called for the Command - * , Name, Description, Icon, EventID and DeviceID for which you called RegisterPersistentEvent. + * Unregisters the specified Command for the specified EventID for the specified DeviceID. UnregisterPersistentEvent should only be called for the + * Command, Name, Description, Icon, EventID and DeviceID for which you called RegisterPersistentEvent. * @param string [DeviceID='*'] */ UnregisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void; } /** - * The Filter object represents a unit of modification on an ImageFile. To use a Filter, add it to the Filters collection, then set the filter's propertie - * s and finally use the Apply method of the ImageProcess object to filter an ImageFile. + * The Filter object represents a unit of modification on an ImageFile. To use a Filter, add it to the Filters collection, then set the filter's + * properties and finally use the Apply method of the ImageProcess object to filter an ImageFile. */ - interface Filter { + class Filter { + private constructor(); + private 'WIA.Filter_typekey': Filter; + /** Returns a Description of what the filter does */ readonly Description: string; @@ -422,10 +457,13 @@ declare namespace WIA { } /** - * The FilterInfo object is a container that describes a Filter object without requiring a Filter to be Added to the process chain. See the FilterInfos pr - * operty on the ImageProcess object for details on accessing FilterInfo objects. + * The FilterInfo object is a container that describes a Filter object without requiring a Filter to be Added to the process chain. See the FilterInfos + * property on the ImageProcess object for details on accessing FilterInfo objects. */ - interface FilterInfo { + class FilterInfo { + private constructor(); + private 'WIA.FilterInfo_typekey': FilterInfo; + /** Returns a technical Description of what the filter does and how to use it in a filter chain */ readonly Description: string; @@ -437,15 +475,18 @@ declare namespace WIA { } /** - * The FilterInfos object is a collection of all the available FilterInfo objects. See the FilterInfos property on the ImageProcess object for detail on a - * ccessing the FilterInfos object. + * The FilterInfos object is a collection of all the available FilterInfo objects. See the FilterInfos property on the ImageProcess object for detail on + * accessing the FilterInfos object. */ interface FilterInfos { /** Returns the number of members in the collection */ readonly Count: number; /** Returns the specified item in the collection either by position or name */ - Item(Index: any): FilterInfo; + Item(Index: number | string): FilterInfo; + + /** Returns the specified item in the collection either by position or name */ + (Index: number | string): FilterInfo; } /** The Filters object is a collection of the Filters that will be applied to an ImageFile when you call the Apply method on the ImageProcess object. */ @@ -464,11 +505,14 @@ declare namespace WIA { /** Removes the designated filter */ Remove(Index: number): void; + + /** Returns the specified item in the collection by position or FilterID */ + (Index: number): Filter; } /** - * The Formats object is a collection of supported FormatIDs that you can use when calling Transfer on an Item object or ShowTransfer on a CommonDialog ob - * ject for this Item. + * The Formats object is a collection of supported FormatIDs that you can use when calling Transfer on an Item object or ShowTransfer on a CommonDialog + * object for this Item. */ interface Formats { /** Returns the number of members in the collection */ @@ -476,13 +520,19 @@ declare namespace WIA { /** Returns the specified item in the collection by position */ Item(Index: number): string; + + /** Returns the specified item in the collection by position */ + (Index: number): string; } /** - * The ImageFile object is a container for images transferred to your computer when you call Transfer or ShowTransfer. It also supports image files throug - * h LoadFile. An ImageFile object can be created using "WIA.ImageFile" in a call to CreateObject. + * The ImageFile object is a container for images transferred to your computer when you call Transfer or ShowTransfer. It also supports image files + * through LoadFile. An ImageFile object can be created using "WIA.ImageFile" in a call to CreateObject. */ - interface ImageFile { + class ImageFile { + private constructor(); + private 'WIA.ImageFile_typekey': ImageFile; + /** Returns/Sets the current frame in the image */ ActiveFrame: number; @@ -539,7 +589,10 @@ declare namespace WIA { } /** The ImageProcess object manages the filter chain. An ImageProcess object can be created using "WIA.ImageProcess" in a call to CreateObject. */ - interface ImageProcess { + class ImageProcess { + private constructor(); + private 'WIA.ImageProcess_typekey': ImageProcess; + /** Takes the specified ImageFile and returns the new ImageFile with all the filters applied on success */ Apply(Source: ImageFile): ImageFile; @@ -551,10 +604,13 @@ declare namespace WIA { } /** - * The Item object is a container for an item on an imaging device object. See the Items property on the Device or Item object for details on accessing It - * em objects. + * The Item object is a container for an item on an imaging device object. See the Items property on the Device or Item object for details on accessing + * Item objects. */ - interface Item { + class Item { + private constructor(); + private 'WIA.Item_typekey': Item; + /** A collection of all commands for this item */ readonly Commands: DeviceCommands; @@ -574,17 +630,15 @@ declare namespace WIA { readonly Properties: Properties; /** - * Returns an ImageFile object, in this version, in the format specified in FormatID if supported, otherwise using the preferred format for this imaging d - * evice. Future versions may return a collection of ImageFile objects. + * Returns an ImageFile object, in this version, in the format specified in FormatID if supported, otherwise using the preferred format for this imaging + * device. Future versions may return a collection of ImageFile objects. * @param string [FormatID='{00000000-0000-0000-0000-000000000000}'] */ - Transfer(FormatID?: string): any; - - /** Returns the underlying IWiaItem interface for this Item object */ - readonly WiaItem: any; + Transfer(FormatID?: string): ImageFile; } /** The Items object contains a collection of Item objects. See the Items property on the Device or Item object for details on accessing the Items object. */ + // tslint:disable-next-line interface-name interface Items { /** Adds a new Item with the specified Name and Flags. The Flags value is created by using the OR operation with members of the WiaItemFlags enumeration. */ Add(Name: string, Flags: number): void; @@ -597,28 +651,37 @@ declare namespace WIA { /** Removes the designated Item */ Remove(Index: number): void; + + /** Returns the specified item in the collection by position */ + (Index: number): Item; } /** - * The Properties object is a collection of all the Property objects associated with a given Device, DeviceInfo, Filter, ImageFile or Item object. See the - * Properties property on any of these objects for detail on accessing the Properties object. + * The Properties object is a collection of all the Property objects associated with a given Device, DeviceInfo, Filter, ImageFile or Item object. See + * the Properties property on any of these objects for detail on accessing the Properties object. */ interface Properties { /** Returns the number of members in the collection */ readonly Count: number; /** Indicates whether the specified Property exists in the collection */ - Exists(Index: any): boolean; + Exists(Index: number | string): boolean; /** Returns the specified item in the collection either by position or name. */ - Item(Index: any): Property; + Item(Index: number | string): Property; + + /** Returns the specified item in the collection either by position or name. */ + (Index: number | string): Property; } /** - * The Property object is a container for a property associated with a Device, DeviceInfo, Filter, ImageFile or Item object. See the Properties property o - * n any of these objects for details on accessing Property objects. + * The Property object is a container for a property associated with a Device, DeviceInfo, Filter, ImageFile or Item object. See the Properties property + * on any of these objects for details on accessing Property objects. */ - interface Property { + class Property { + private constructor(); + private 'WIA.Property_typekey': Property; + /** Indicates whether the Property Value is read only */ readonly IsReadOnly: boolean; @@ -657,10 +720,13 @@ declare namespace WIA { } /** - * The Rational object is a container for the rational values found in Exif tags. It is a supported element type of the Vector object and may be created u - * sing "WIA.Rational" in a call to CreateObject. + * The Rational object is a container for the rational values found in Exif tags. It is a supported element type of the Vector object and may be created + * using "WIA.Rational" in a call to CreateObject. */ - interface Rational { + class Rational { + private constructor(); + private 'WIA.Rational_typekey': Rational; + /** Returns/Sets the Rational Value Denominator */ Denominator: number; @@ -672,19 +738,19 @@ declare namespace WIA { } /** - * The Vector object is a collection of values of the same type. It is used throughout the library in many different ways. The Vector object may be create - * d using "WIA.Vector" in a call to CreateObject. + * The Vector object is a collection of values of the same type. It is used throughout the library in many different ways. The Vector object may be + * created using "WIA.Vector" in a call to CreateObject. */ - interface Vector { + interface Vector { /** - * If Index is not zero, Inserts a new element into the Vector collection before the specified Index. If Index is zero, Appends a new element to the Vecto - * r collection. + * If Index is not zero, Inserts a new element into the Vector collection before the specified Index. If Index is zero, Appends a new element to the + * Vector collection. * @param number [Index=0] */ - Add(Value: any, Index?: number): void; + Add(Value: TItem, Index?: number): void; /** Returns/Sets the Vector of Bytes as an array of bytes */ - BinaryData: any; + BinaryData: SafeArray; /** Removes all elements. */ Clear(): void; @@ -696,30 +762,30 @@ declare namespace WIA { Date: VarDate; /** - * Used to get the Thumbnail property of an ImageFile which is an image file, The thumbnail property of an Item which is RGB data, or creating an ImageFil - * e from raw ARGB data. Returns an ImageFile object on success. See the Picture method for more details. + * Used to get the Thumbnail property of an ImageFile which is an image file, The thumbnail property of an Item which is RGB data, or creating an + * ImageFile from raw ARGB data. Returns an ImageFile object on success. See the Picture method for more details. * @param number [Width=0] * @param number [Height=0] */ ImageFile(Width?: number, Height?: number): ImageFile; - /** Returns/Sets the specified item in the vector by position */ - Item(Index: number): any; + /** Returns the specified item in the vector by position */ + Item(Index: number): TItem; /** - * If the Vector of Bytes contains an image file, then Width and Height are ignored. Otherwise a Vector of Bytes must be RGB data and a Vector of Longs mu - * st be ARGB data. Returns a Picture object on success. See the ImageFile method for more details. + * If the Vector of Bytes contains an image file, then Width and Height are ignored. Otherwise a Vector of Bytes must be RGB data and a Vector of Longs + * must be ARGB data. Returns a Picture object on success. See the ImageFile method for more details. * @param number [Width=0] * @param number [Height=0] */ Picture(Width?: number, Height?: number): any; /** Removes the designated element and returns it if successful */ - Remove(Index: number): any; + Remove(Index: number): TItem | null; /** - * Stores the string Value into the Vector of Bytes including the NULL terminator. Value may be truncated unless Resizable is True. The string will be sto - * red as an ANSI string unless Unicode is True, in which case it will be stored as a Unicode string. + * Stores the string Value into the Vector of Bytes including the NULL terminator. Value may be truncated unless Resizable is True. The string will be + * stored as an ANSI string unless Unicode is True, in which case it will be stored as a Unicode string. * @param boolean [Resizable=true] * @param boolean [Unicode=true] */ @@ -730,30 +796,24 @@ declare namespace WIA { * @param boolean [Unicode=true] */ String(Unicode?: boolean): string; + + /** Returns the specified item in the vector by position */ + (Index: number): TItem; } } interface ActiveXObject { + new(progid: K): ActiveXObjectNameMap[K]; on(obj: WIA.DeviceManager, event: 'OnEvent', argNames: ['EventID', 'DeviceID', 'ItemID'], handler: ( - this: WIA.DeviceManager, parameter: { - EventID: string, DeviceID: string, ItemID: string}) => void): void; - set(obj: WIA.Vector, propertyName: 'Item', parameterTypes: [number], newValue: any): void; - new(progid: 'WIA.CommonDialog'): WIA.CommonDialog; - new(progid: 'WIA.DeviceManager'): WIA.DeviceManager; - new(progid: 'WIA.ImageFile'): WIA.ImageFile; - new(progid: 'WIA.ImageProcess'): WIA.ImageProcess; - new(progid: 'WIA.Rational'): WIA.Rational; - new(progid: 'WIA.Vector'): WIA.Vector; + this: WIA.DeviceManager, parameter: { readonly EventID: string, readonly DeviceID: string, readonly ItemID: string }) => void): void; + set(obj: WIA.Vector, propertyName: 'Item', parameterTypes: [number], newValue: TItem): void; } -interface EnumeratorConstructor { - new(col: WIA.DeviceCommands): WIA.DeviceCommand; - new(col: WIA.DeviceEvents): WIA.DeviceEvent; - new(col: WIA.DeviceInfos): WIA.DeviceInfo; - new(col: WIA.FilterInfos): WIA.FilterInfo; - new(col: WIA.Filters): WIA.Filter; - new(col: WIA.Formats): string; - new(col: WIA.Items): WIA.Item; - new(col: WIA.Properties): WIA.Property; - new(col: WIA.Vector): any; +interface ActiveXObjectNameMap { + 'WIA.CommonDialog': WIA.CommonDialog; + 'WIA.DeviceManager': WIA.DeviceManager; + 'WIA.ImageFile': WIA.ImageFile; + 'WIA.ImageProcess': WIA.ImageProcess; + 'WIA.Rational': WIA.Rational; + 'WIA.Vector': WIA.Vector; } diff --git a/types/activex-wia/tslint.json b/types/activex-wia/tslint.json index 3224b40b8b..f93cf8562a 100644 --- a/types/activex-wia/tslint.json +++ b/types/activex-wia/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-const-enum": false - } + "extends": "dtslint/dt.json" } From 2dace74657d9141276b7199ae3bf1a13002d89e9 Mon Sep 17 00:00:00 2001 From: Chris Krycho Date: Sat, 10 Feb 2018 19:28:26 -0700 Subject: [PATCH 014/128] Ember Data: merge latest. --- types/ember-data/index.d.ts | 545 ++++++++++++---------- types/ember-data/test/adapter.ts | 12 + types/ember-data/test/belongs-to.ts | 10 +- types/ember-data/test/has-many.ts | 45 +- types/ember-data/test/injections.ts | 8 + types/ember-data/test/record-reference.ts | 8 +- types/ember-data/test/relationships.ts | 13 +- types/ember-data/test/serializer.ts | 3 +- types/ember-data/test/store.ts | 80 +++- types/ember-data/tsconfig.json | 9 +- types/ember-data/tslint.json | 1 + 11 files changed, 430 insertions(+), 304 deletions(-) diff --git a/types/ember-data/index.d.ts b/types/ember-data/index.d.ts index e485edff21..9531372a87 100644 --- a/types/ember-data/index.d.ts +++ b/types/ember-data/index.d.ts @@ -2,12 +2,18 @@ // Project: https://github.com/emberjs/data // Definitions by: Derek Wickern // Mike North +// Chris Krycho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -declare module "ember-data" { - import Ember from "ember"; +declare module 'ember-data' { + import Ember from 'ember'; import RSVP from 'rsvp'; + + export interface ModelRegistry {} + export interface AdapterRegistry {} + export interface SerializerRegistry {} + namespace DS { /** * Convert an hash of errors into an array with errors in JSON-API format. @@ -21,47 +27,47 @@ declare module "ember-data" { * `DS.belongsTo` is used to define One-To-One and One-To-Many * relationships on a [DS.Model](/api/data/classes/DS.Model.html). */ - function belongsTo( - modelName: string, + function belongsTo( + modelName: K, options: { async: false; inverse?: string | null; polymorphic?: boolean; } - ): Ember.ComputedProperty; - function belongsTo( - modelName: string, + ): Ember.ComputedProperty; + function belongsTo( + modelName: K, options?: { async?: true; inverse?: string | null; polymorphic?: boolean; } - ): Ember.ComputedProperty>; + ): Ember.ComputedProperty>; /** * `DS.hasMany` is used to define One-To-Many and Many-To-Many * relationships on a [DS.Model](/api/data/classes/DS.Model.html). */ - function hasMany( - type: string, + function hasMany( + type: K, options: { async: false; inverse?: string | null; polymorphic?: boolean; } - ): Ember.ComputedProperty>; - function hasMany( - type: string, + ): Ember.ComputedProperty>; + function hasMany( + type: K, options?: { async?: true; inverse?: string | null; polymorphic?: boolean; } - ): Ember.ComputedProperty>; + ): Ember.ComputedProperty>; /** * This method normalizes a modelName into the format Ember Data uses * internally. */ - function normalizeModelName(modelName: string): string; + function normalizeModelName(modelName: K): string; const VERSION: string; interface AttrOptions { @@ -77,19 +83,19 @@ declare module "ember-data" { * [DS.Transform](/api/data/classes/DS.Transform.html). */ function attr( - type: "string", + type: 'string', options?: AttrOptions ): Ember.ComputedProperty; function attr( - type: "boolean", + type: 'boolean', options?: AttrOptions ): Ember.ComputedProperty; function attr( - type: "number", + type: 'number', options?: AttrOptions ): Ember.ComputedProperty; function attr( - type: "date", + type: 'date', options?: AttrOptions ): Ember.ComputedProperty; function attr( @@ -118,89 +124,89 @@ declare module "ember-data" { /** * Builds a URL for a given type and optional ID. */ - buildURL( - modelName?: string, + buildURL( + modelName?: K, id?: string | any[] | {} | null, - snapshot?: Snapshot | any[] | null, + snapshot?: Snapshot | any[] | null, requestType?: string, query?: {} ): string; /** * Builds a URL for a `store.findRecord(type, id)` call. */ - urlForFindRecord( + urlForFindRecord( id: string, - modelName: string, - snapshot: Snapshot + modelName: K, + snapshot: Snapshot ): string; /** * Builds a URL for a `store.findAll(type)` call. */ - urlForFindAll( - modelName: string, - snapshot: SnapshotRecordArray + urlForFindAll( + modelName: K, + snapshot: SnapshotRecordArray ): string; /** * Builds a URL for a `store.query(type, query)` call. */ - urlForQuery(query: {}, modelName: string): string; + urlForQuery(query: {}, modelName: K): string; /** * Builds a URL for a `store.queryRecord(type, query)` call. */ - urlForQueryRecord(query: {}, modelName: string): string; + urlForQueryRecord(query: {}, modelName: K): string; /** * Builds a URL for coalesceing multiple `store.findRecord(type, id)` * records into 1 request when the adapter's `coalesceFindRequests` * property is true. */ - urlForFindMany( + urlForFindMany( ids: any[], - modelName: string, + modelName: K, snapshots: any[] ): string; /** * Builds a URL for fetching a async hasMany relationship when a url * is not provided by the server. */ - urlForFindHasMany( + urlForFindHasMany( id: string, - modelName: string, - snapshot: Snapshot + modelName: K, + snapshot: Snapshot ): string; /** * Builds a URL for fetching a async belongsTo relationship when a url * is not provided by the server. */ - urlForFindBelongsTo( + urlForFindBelongsTo( id: string, - modelName: string, - snapshot: Snapshot + modelName: K, + snapshot: Snapshot ): string; /** * Builds a URL for a `record.save()` call when the record was created * locally using `store.createRecord()`. */ - urlForCreateRecord(modelName: string, snapshot: Snapshot): string; + urlForCreateRecord(modelName: K, snapshot: Snapshot): string; /** * Builds a URL for a `record.save()` call when the record has been update locally. */ - urlForUpdateRecord( + urlForUpdateRecord( id: string, - modelName: string, - snapshot: Snapshot + modelName: K, + snapshot: Snapshot ): string; /** * Builds a URL for a `record.save()` call when the record has been deleted locally. */ - urlForDeleteRecord( + urlForDeleteRecord( id: string, - modelName: string, - snapshot: Snapshot + modelName: K, + snapshot: Snapshot ): string; /** * Determines the pathname for a given type. */ - pathForType(modelName: string): string; + pathForType(modelName: K): string; } /** * A `DS.AdapterError` is used by an adapter to signal that an error occurred @@ -502,11 +508,11 @@ declare module "ember-data" { /** * Get the reference for the specified belongsTo relationship. */ - belongsTo(name: string): BelongsToReference; + belongsTo(name: keyof ModelRegistry): BelongsToReference; /** * Get the reference for the specified hasMany relationship. */ - hasMany(name: string): HasManyReference; + hasMany(name: keyof ModelRegistry): HasManyReference; /** * Given a callback, iterates over each of the relationships in the model, * invoking the callback with the name of each relationship and its relationship @@ -517,15 +523,15 @@ declare module "ember-data" { * Represents the model's class name as a string. This can be used to look up the model's class name through * `DS.Store`'s modelFor method. */ - static modelName: string; + static modelName: keyof ModelRegistry; /** * For a given relationship name, returns the model type of the relationship. */ - static typeForRelationship(name: string, store: Store): Model; + static typeForRelationship(name: K, store: Store): ModelRegistry[K]; /** * Find the relationship which is the inverse of the one asked for. */ - static inverseFor(name: string, store: Store): {}; + static inverseFor(name: K, store: Store): {}; /** * The model's relationships as a map, keyed on the type of the * relationship. The value of each entry is an array containing a descriptor @@ -885,7 +891,7 @@ declare module "ember-data" { */ createRecord(inputProperties?: {}): T; } - class SnapshotRecordArray { + class SnapshotRecordArray { /** * Number of records in the array */ @@ -905,18 +911,18 @@ declare module "ember-data" { /** * The type of the underlying records for the snapshots in the array, as a DS.Model */ - type: Model; + type: ModelRegistry[K]; /** * Get snapshots of the underlying record array */ snapshots(): any[]; } - class Snapshot { + class Snapshot { /** * The underlying record for this snapshot. Can be used to access methods and * properties defined on the record. */ - record: Model; + record: ModelRegistry[K]; /** * The id of the snapshot's underlying record */ @@ -928,15 +934,15 @@ declare module "ember-data" { /** * The name of the type of the underlying record for this snapshot, as a string. */ - modelName: string; + modelName: K; /** * The type of the underlying record for this snapshot, as a DS.Model. */ - type: Model; + type: ModelRegistry[K]; /** * Returns the value of an attribute. */ - attr(keyName: string): {}; + attr(keyName: L): {}; /** * Returns all attributes and their corresponding values. */ @@ -948,14 +954,14 @@ declare module "ember-data" { /** * Returns the current value of a belongsTo relationship. */ - belongsTo( - keyName: string, + belongsTo( + keyName: L, options?: {} - ): Snapshot | string | null | undefined; + ): Snapshot | string | null | undefined; /** * Returns the current value of a hasMany relationship. */ - hasMany(keyName: string, options?: {}): any[] | undefined; + hasMany(keyName: L, options?: {}): any[] | undefined; /** * Iterates through all the attributes of the model, calling the passed * function on each attribute. @@ -971,6 +977,7 @@ declare module "ember-data" { */ serialize(options: {}): {}; } + /** * The store contains all of the data for records loaded from the server. * It is also responsible for creating instances of `DS.Model` that wrap @@ -988,10 +995,10 @@ declare module "ember-data" { * Create a new record in the current store. The properties passed * to this method are set on the newly created record. */ - createRecord( - modelName: string, + createRecord( + modelName: K, inputProperties?: {} - ): T; + ): ModelRegistry[K]; /** * For symmetry, a record can be deleted via the store. */ @@ -1004,83 +1011,86 @@ declare module "ember-data" { /** * This method returns a record for a given type and id combination. */ - findRecord( - modelName: string, + findRecord( + modelName: K, id: string | number, options?: {} - ): PromiseObject & T; + ): PromiseObject & ModelRegistry[K]; /** * Get the reference for the specified record. */ - getReference( - modelName: string, + getReference( + modelName: K, id: string | number - ): RecordReference; + ): RecordReference; /** * Get a record by a given type and ID without triggering a fetch. */ - peekRecord( - modelName: string, + peekRecord( + modelName: K, id: string | number - ): T | null; + ): ModelRegistry[K] | null; /** * This method returns true if a record for a given modelName and id is already * loaded in the store. Use this function to know beforehand if a findRecord() * will result in a request or that it will be a cache hit. */ - hasRecordForId(modelName: string, id: string | number): boolean; + hasRecordForId( + modelName: K, + id: string | number + ): boolean; /** * This method delegates a query to the adapter. This is the one place where * adapter-level semantics are exposed to the application. */ - query( - modelName: string, + query( + modelName: K, query: any - ): AdapterPopulatedRecordArray & PromiseArray; + ): AdapterPopulatedRecordArray & PromiseArray; /** * This method makes a request for one record, where the `id` is not known * beforehand (if the `id` is known, use [`findRecord`](#method_findRecord) * instead). */ - queryRecord( - modelName: string, + queryRecord( + modelName: K, query: any - ): RSVP.Promise; + ): RSVP.Promise; /** * `findAll` asks the adapter's `findAll` method to find the records for the * given type, and returns a promise which will resolve with all records of * this type present in the store, even if the adapter only returns a subset * of them. */ - findAll( - modelName: string, + findAll( + modelName: K, options?: { reload?: boolean; backgroundReload?: boolean; include?: string; adapterOptions?: any; } - ): PromiseArray; + ): PromiseArray; /** * This method returns a filtered array that contains all of the * known records for a given type in the store. */ - peekAll(modelName: string): RecordArray; + peekAll(modelName: K): RecordArray; /** * This method unloads all records in the store. * It schedules unloading to happen during the next run loop. */ - unloadAll(modelName: string): void; + unloadAll(modelName: K): void; /** * DEPRECATED: * This method has been deprecated and is an alias for store.hasRecordForId, which should * be used instead. */ - recordIsLoaded(modelName: string, id: string): boolean; + recordIsLoaded(modelName: K, id: string): boolean; /** * Returns the model class for the particular `modelName`. */ - modelFor(modelName: string): M; + modelFor(modelName: K): ModelRegistry[K]; /** * Push some data for a given type into the store. */ @@ -1088,25 +1098,25 @@ declare module "ember-data" { /** * Push some raw data into the store. */ - pushPayload(modelName: string, inputPayload: {}): any; + pushPayload(modelName: K, inputPayload: {}): any; pushPayload(inputPayload: {}): any; /** * `normalize` converts a json payload into the normalized form that * [push](#method_push) expects. */ - normalize(modelName: string, payload: {}): {}; + normalize(modelName: K, payload: {}): {}; /** * Returns an instance of the adapter for a given type. For * example, `adapterFor('person')` will return an instance of * `App.PersonAdapter`. */ - adapterFor(modelName: string): A; + adapterFor(modelName: K): AdapterRegistry[K]; /** * Returns an instance of the serializer for a given type. For * example, `serializerFor('person')` will return an instance of * `App.PersonSerializer`. */ - serializerFor(modelName: string): S; + serializerFor(modelName: K): SerializerRegistry[K]; } /** * The `JSONAPIAdapter` is the default adapter used by Ember Data. It @@ -1132,7 +1142,11 @@ declare module "ember-data" { /** * Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. */ - ajax(url: string, type: string, options?: object): RSVP.Promise; + ajax( + url: string, + type: string, + options?: object + ): RSVP.Promise; /** * Generate ajax options */ @@ -1170,38 +1184,42 @@ declare module "ember-data" { * Called by the store in order to fetch the JSON for a given * type and ID. */ - findRecord( + findRecord( store: Store, - type: Model, + type: ModelRegistry[K], id: string, - snapshot: Snapshot + snapshot: Snapshot ): RSVP.Promise; /** * Called by the store in order to fetch a JSON array for all * of the records for a given type. */ - findAll( + findAll( store: Store, - type: Model, + type: ModelRegistry[K], sinceToken: string, - snapshotRecordArray: SnapshotRecordArray + snapshotRecordArray: SnapshotRecordArray ): RSVP.Promise; /** * Called by the store in order to fetch a JSON array for * the records that match a particular query. */ - query(store: Store, type: Model, query: {}): RSVP.Promise; + query(store: Store, type: ModelRegistry[K], query: {}): RSVP.Promise; /** * Called by the store in order to fetch a JSON object for * the record that matches a particular query. */ - queryRecord(store: Store, type: Model, query: {}): RSVP.Promise; + queryRecord( + store: Store, + type: ModelRegistry[K], + query: {} + ): RSVP.Promise; /** * Called by the store in order to fetch several records together if `coalesceFindRequests` is true */ - findMany( + findMany( store: Store, - type: Model, + type: ModelRegistry[K], ids: any[], snapshots: any[] ): RSVP.Promise; @@ -1210,9 +1228,9 @@ declare module "ember-data" { * the unloaded records in a has-many relationship that were originally * specified as a URL (inside of `links`). */ - findHasMany( + findHasMany( store: Store, - snapshot: Snapshot, + snapshot: Snapshot, url: string, relationship: {} ): RSVP.Promise; @@ -1221,36 +1239,36 @@ declare module "ember-data" { * belongs-to relationship that was originally specified as a URL (inside of * `links`). */ - findBelongsTo( + findBelongsTo( store: Store, - snapshot: Snapshot, + snapshot: Snapshot, url: string ): RSVP.Promise; /** * Called by the store when a newly created record is * saved via the `save` method on a model record instance. */ - createRecord( + createRecord( store: Store, - type: Model, - snapshot: Snapshot + type: ModelRegistry[K], + snapshot: Snapshot ): RSVP.Promise; /** * Called by the store when an existing record is saved * via the `save` method on a model record instance. */ - updateRecord( + updateRecord( store: Store, - type: Model, - snapshot: Snapshot + type: ModelRegistry[K], + snapshot: Snapshot ): RSVP.Promise; /** * Called by the store when a record is deleted. */ - deleteRecord( + deleteRecord( store: Store, - type: Model, - snapshot: Snapshot + type: ModelRegistry[K], + snapshot: Snapshot ): RSVP.Promise; /** * Organize records into groups, each of which is to be passed to separate @@ -1295,89 +1313,89 @@ declare module "ember-data" { /** * Builds a URL for a given type and optional ID. */ - buildURL( - modelName?: string, + buildURL( + modelName?: K, id?: string | any[] | {} | null, - snapshot?: Snapshot | any[] | null, + snapshot?: Snapshot | any[] | null, requestType?: string, query?: {} ): string; /** * Builds a URL for a `store.findRecord(type, id)` call. */ - urlForFindRecord( + urlForFindRecord( id: string, - modelName: string, - snapshot: Snapshot + modelName: K, + snapshot: Snapshot ): string; /** * Builds a URL for a `store.findAll(type)` call. */ - urlForFindAll( - modelName: string, - snapshot: SnapshotRecordArray + urlForFindAll( + modelName: K, + snapshot: SnapshotRecordArray ): string; /** * Builds a URL for a `store.query(type, query)` call. */ - urlForQuery(query: {}, modelName: string): string; + urlForQuery(query: {}, modelName: K): string; /** * Builds a URL for a `store.queryRecord(type, query)` call. */ - urlForQueryRecord(query: {}, modelName: string): string; + urlForQueryRecord(query: {}, modelName: K): string; /** * Builds a URL for coalesceing multiple `store.findRecord(type, id)` * records into 1 request when the adapter's `coalesceFindRequests` * property is true. */ - urlForFindMany( + urlForFindMany( ids: any[], - modelName: string, + modelName: K, snapshots: any[] ): string; /** * Builds a URL for fetching a async hasMany relationship when a url * is not provided by the server. */ - urlForFindHasMany( + urlForFindHasMany( id: string, - modelName: string, - snapshot: Snapshot + modelName: K, + snapshot: Snapshot ): string; /** * Builds a URL for fetching a async belongsTo relationship when a url * is not provided by the server. */ - urlForFindBelongsTo( + urlForFindBelongsTo( id: string, - modelName: string, - snapshot: Snapshot + modelName: K, + snapshot: Snapshot ): string; /** * Builds a URL for a `record.save()` call when the record was created * locally using `store.createRecord()`. */ - urlForCreateRecord(modelName: string, snapshot: Snapshot): string; + urlForCreateRecord(modelName: K, snapshot: Snapshot): string; /** * Builds a URL for a `record.save()` call when the record has been update locally. */ - urlForUpdateRecord( + urlForUpdateRecord( id: string, - modelName: string, - snapshot: Snapshot + modelName: K, + snapshot: Snapshot ): string; /** * Builds a URL for a `record.save()` call when the record has been deleted locally. */ - urlForDeleteRecord( + urlForDeleteRecord( id: string, - modelName: string, - snapshot: Snapshot + modelName: K, + snapshot: Snapshot ): string; /** * Determines the pathname for a given type. */ - pathForType(modelName: string): string; + pathForType(modelName: K): string; } /** * ## Using Embedded Records @@ -1391,16 +1409,16 @@ declare module "ember-data" { /** * Serialize `belongsTo` relationship when it is configured as an embedded object. */ - serializeBelongsTo( - snapshot: Snapshot, + serializeBelongsTo( + snapshot: Snapshot, json: {}, relationship: {} ): any; /** * Serializes `hasMany` relationships when it is configured as embedded objects. */ - serializeHasMany( - snapshot: Snapshot, + serializeHasMany( + snapshot: Snapshot, json: {}, relationship: {} ): any; @@ -1408,9 +1426,9 @@ declare module "ember-data" { * When serializing an embedded record, modify the property (in the json payload) * that refers to the parent record (foreign key for relationship). */ - removeEmbeddedForeignKey( - snapshot: Snapshot, - embeddedSnapshot: Snapshot, + removeEmbeddedForeignKey( + snapshot: Snapshot, + embeddedSnapshot: Snapshot, relationship: {}, json: {} ): any; @@ -1428,7 +1446,7 @@ declare module "ember-data" { /** * Converts the model name to a pluralized version of the model name. */ - payloadKeyFromModelName(modelName: string): string; + payloadKeyFromModelName(modelName: K): string; /** * `keyForAttribute` can be used to define rules for how to convert an * attribute name in your model to a key in your JSON. @@ -1458,7 +1476,7 @@ declare module "ember-data" { * `payloadTypeFromModelName` can be used to change the mapping for the type in * the payload, taken from the model name. */ - payloadTypeFromModelName(modelname: string): string; + payloadTypeFromModelName(modelName: K): string; } /** * Ember Data 2.0 Serializer: @@ -1620,8 +1638,8 @@ declare module "ember-data" { /** * Check if the given hasMany relationship should be serialized */ - shouldSerializeHasMany( - snapshot: Snapshot, + shouldSerializeHasMany( + snapshot: Snapshot, key: string, relationshipType: string ): boolean; @@ -1629,7 +1647,7 @@ declare module "ember-data" { * Called when a record is saved in order to convert the * record into JSON. */ - serialize(snapshot: Snapshot, options: {}): {}; + serialize(snapshot: Snapshot, options: {}): {}; /** * You can use this method to customize how a serialized record is added to the complete * JSON hash to be sent to the server. By default the JSON Serializer does not namespace @@ -1638,18 +1656,18 @@ declare module "ember-data" { * Otherwise you can override this method to customize how the record is added to the hash. * The hash property should be modified by reference. */ - serializeIntoHash( + serializeIntoHash( hash: {}, - typeClass: Model, - snapshot: Snapshot, + typeClass: ModelRegistry[K], + snapshot: Snapshot, options?: {} ): any; /** * `serializeAttribute` can be used to customize how `DS.attr` * properties are serialized */ - serializeAttribute( - snapshot: Snapshot, + serializeAttribute( + snapshot: Snapshot, json: {}, key: string, attribute: {} @@ -1658,8 +1676,8 @@ declare module "ember-data" { * `serializeBelongsTo` can be used to customize how `DS.belongsTo` * properties are serialized. */ - serializeBelongsTo( - snapshot: Snapshot, + serializeBelongsTo( + snapshot: Snapshot, json: {}, relationship: {} ): any; @@ -1667,8 +1685,8 @@ declare module "ember-data" { * `serializeHasMany` can be used to customize how `DS.hasMany` * properties are serialized. */ - serializeHasMany( - snapshot: Snapshot, + serializeHasMany( + snapshot: Snapshot, json: {}, relationship: {} ): any; @@ -1678,8 +1696,8 @@ declare module "ember-data" { * `{ polymorphic: true }` is pass as the second argument to the * `DS.belongsTo` function. */ - serializePolymorphicType( - snapshot: Snapshot, + serializePolymorphicType( + snapshot: Snapshot, json: {}, relationship: {} ): any; @@ -1726,7 +1744,7 @@ declare module "ember-data" { * serializeId can be used to customize how id is serialized * For example, your server may expect integer datatype of id */ - serializeId(snapshot: Snapshot, json: {}, primaryKey: string): any; + serializeId(snapshot: Snapshot, json: {}, primaryKey: string): any; } /** * Normally, applications will use the `RESTSerializer` by implementing @@ -1764,17 +1782,17 @@ declare module "ember-data" { * Called when a record is saved in order to convert the * record into JSON. */ - serialize(snapshot: Snapshot, options: {}): {}; + serialize(snapshot: Snapshot, options: {}): {}; /** * You can use this method to customize the root keys serialized into the JSON. * The hash property should be modified by reference (possibly using something like _.extend) * By default the REST Serializer sends the modelName of a model, which is a camelized * version of the name. */ - serializeIntoHash( + serializeIntoHash( hash: {}, typeClass: Model, - snapshot: Snapshot, + snapshot: Snapshot, options?: {} ): any; /** @@ -1782,14 +1800,14 @@ declare module "ember-data" { * request. By default, the RESTSerializer returns a camelized version of the * model's name. */ - payloadKeyFromModelName(modelName: string): string; + payloadKeyFromModelName(modelName: K): string; /** * You can use this method to customize how polymorphic objects are serialized. * By default the REST Serializer creates the key by appending `Type` to * the attribute and value from the model's camelcased model name. */ - serializePolymorphicType( - snapshot: Snapshot, + serializePolymorphicType( + snapshot: Snapshot, json: {}, relationship: {} ): any; @@ -1811,7 +1829,7 @@ declare module "ember-data" { * `payloadTypeFromModelName` can be used to change the mapping for the type in * the payload, taken from the model name. */ - payloadTypeFromModelName(modelName: string): string; + payloadTypeFromModelName(modelName: K): string; } /** * The `DS.BooleanTransform` class is used to serialize and deserialize @@ -1883,27 +1901,27 @@ declare module "ember-data" { * method should return a promise that will resolve to a JavaScript object that will be * normalized by the serializer. */ - findRecord( + findRecord( store: Store, - type: Model, + type: ModelRegistry[K], id: string, - snapshot: Snapshot + snapshot: Snapshot ): RSVP.Promise; /** * The `findAll()` method is used to retrieve all records for a given type. */ - findAll( + findAll( store: Store, - type: Model, + type: ModelRegistry[K], sinceToken: string, - snapshotRecordArray: SnapshotRecordArray + snapshotRecordArray: SnapshotRecordArray ): RSVP.Promise; /** * This method is called when you call `query` on the store. */ - query( + query( store: Store, - type: Model, + type: ModelRegistry[K], query: {}, recordArray: AdapterPopulatedRecordArray ): RSVP.Promise; @@ -1911,48 +1929,52 @@ declare module "ember-data" { * The `queryRecord()` method is invoked when the store is asked for a single * record through a query object. */ - queryRecord(store: Store, type: Model, query: {}): RSVP.Promise; + queryRecord( + store: Store, + type: ModelRegistry[K], + query: {} + ): RSVP.Promise; /** * If the globally unique IDs for your records should be generated on the client, * implement the `generateIdForRecord()` method. This method will be invoked * each time you create a new record, and the value returned from it will be * assigned to the record's `primaryKey`. */ - generateIdForRecord( + generateIdForRecord( store: Store, - type: Model, + type: ModelRegistry[K], inputProperties: {} ): string | number; /** * Proxies to the serializer's `serialize` method. */ - serialize(snapshot: Snapshot, options: {}): {}; + serialize(snapshot: Snapshot, options: {}): {}; /** * Implement this method in a subclass to handle the creation of * new records. */ - createRecord( + createRecord( store: Store, - type: Model, - snapshot: Snapshot + type: ModelRegistry[K], + snapshot: Snapshot ): RSVP.Promise; /** * Implement this method in a subclass to handle the updating of * a record. */ - updateRecord( + updateRecord( store: Store, - type: Model, - snapshot: Snapshot + type: ModelRegistry[K], + snapshot: Snapshot ): RSVP.Promise; /** * Implement this method in a subclass to handle the deletion of * a record. */ - deleteRecord( + deleteRecord( store: Store, - type: Model, - snapshot: Snapshot + type: ModelRegistry[K], + snapshot: Snapshot ): RSVP.Promise; /** * By default the store will try to coalesce all `fetchRecord` calls within the same runloop @@ -1966,9 +1988,9 @@ declare module "ember-data" { * requests to find multiple records at once if coalesceFindRequests * is true. */ - findMany( + findMany( store: Store, - type: Model, + type: ModelRegistry[K], ids: any[], snapshots: any[] ): RSVP.Promise; @@ -1982,33 +2004,33 @@ declare module "ember-data" { * reload a record from the adapter when a record is requested by * `store.findRecord`. */ - shouldReloadRecord(store: Store, snapshot: Snapshot): boolean; + shouldReloadRecord(store: Store, snapshot: Snapshot): boolean; /** * This method is used by the store to determine if the store should * reload all records from the adapter when records are requested by * `store.findAll`. */ - shouldReloadAll( + shouldReloadAll( store: Store, - snapshotRecordArray: SnapshotRecordArray + snapshotRecordArray: SnapshotRecordArray ): boolean; /** * This method is used by the store to determine if the store should * reload a record after the `store.findRecord` method resolves a * cached record. */ - shouldBackgroundReloadRecord( + shouldBackgroundReloadRecord( store: Store, - snapshot: Snapshot + snapshot: Snapshot ): boolean; /** * This method is used by the store to determine if the store should * reload a record array after the `store.findAll` method resolves * with a cached record array. */ - shouldBackgroundReloadAll( + shouldBackgroundReloadAll( store: Store, - snapshotRecordArray: SnapshotRecordArray + snapshotRecordArray: SnapshotRecordArray ): boolean; } /** @@ -2038,7 +2060,7 @@ declare module "ember-data" { * The `serialize` method is used when a record is saved in order to convert * the record into the form that your external data source expects. */ - serialize(snapshot: Snapshot, options: {}): {}; + serialize(snapshot: Snapshot, options: {}): {}; /** * The `normalize` method is used to convert a payload received from your * external data source into the normalized form `store.push()` expects. You @@ -2048,11 +2070,12 @@ declare module "ember-data" { normalize(typeClass: Model, hash: {}): {}; } } + export default DS; } -declare module "ember" { - import DS from "ember-data"; +declare module 'ember' { + import DS from 'ember-data'; namespace Ember { /* * The store is automatically injected into these objects @@ -2069,91 +2092,101 @@ declare module "ember" { store: DS.Store; } } + + // It is also available to inject anywhere + module '@ember/service' { + interface Registry { + 'store': DS.Store; + } + } } declare module 'ember-data/adapter' { - import DS from 'ember-data'; - export default DS.Adapter; + import DS from 'ember-data'; + export default DS.Adapter; + export { AdapterRegistry } from 'ember-data'; } declare module 'ember-data/adapters/errors' { - import DS from 'ember-data'; - const AdapterError: typeof DS.AdapterError; - const InvalidError: typeof DS.InvalidError; - const UnauthorizedError: typeof DS.UnauthorizedError; - const ForbiddenError: typeof DS.ForbiddenError; - const NotFoundError: typeof DS.NotFoundError; - const ConflictError: typeof DS.ConflictError; - const ServerError: typeof DS.ServerError; - const TimeoutError: typeof DS.TimeoutError; - const AbortError: typeof DS.AbortError; - const errorsHashToArray: typeof DS.errorsHashToArray; - const errorsArrayToHash: typeof DS.errorsArrayToHash; + import DS from 'ember-data'; + const AdapterError: typeof DS.AdapterError; + const InvalidError: typeof DS.InvalidError; + const UnauthorizedError: typeof DS.UnauthorizedError; + const ForbiddenError: typeof DS.ForbiddenError; + const NotFoundError: typeof DS.NotFoundError; + const ConflictError: typeof DS.ConflictError; + const ServerError: typeof DS.ServerError; + const TimeoutError: typeof DS.TimeoutError; + const AbortError: typeof DS.AbortError; + const errorsHashToArray: typeof DS.errorsHashToArray; + const errorsArrayToHash: typeof DS.errorsArrayToHash; } declare module 'ember-data/adapters/json-api' { - import DS from 'ember-data'; - export default DS.JSONAPIAdapter; + import DS from 'ember-data'; + export default DS.JSONAPIAdapter; } declare module 'ember-data/adapters/rest' { - import DS from 'ember-data'; - export default DS.RESTAdapter; + import DS from 'ember-data'; + export default DS.RESTAdapter; } declare module 'ember-data/attr' { - import DS from 'ember-data'; - export default DS.attr; + import DS from 'ember-data'; + export default DS.attr; } declare module 'ember-data/model' { - import DS from 'ember-data'; - export default DS.Model; + import DS from 'ember-data'; + export default DS.Model; + export { ModelRegistry } from 'ember-data'; } declare module 'ember-data/relationships' { - import DS from 'ember-data'; - const hasMany: typeof DS.hasMany; - const belongsTo: typeof DS.belongsTo; + import DS from 'ember-data'; + const hasMany: typeof DS.hasMany; + const belongsTo: typeof DS.belongsTo; } declare module 'ember-data/serializer' { - import DS from 'ember-data'; - export default DS.Serializer; + import DS from 'ember-data'; + export default DS.Serializer; + export { SerializerRegistry } from 'ember-data'; } declare module 'ember-data/serializers/embedded-records-mixin' { - import DS from 'ember-data'; - export default DS.EmbeddedRecordsMixin; + import DS from 'ember-data'; + export default DS.EmbeddedRecordsMixin; } declare module 'ember-data/serializers/json-api' { - import DS from 'ember-data'; - export default DS.JSONAPISerializer; + import DS from 'ember-data'; + export default DS.JSONAPISerializer; } declare module 'ember-data/serializers/json' { - import DS from 'ember-data'; - export default DS.JSONSerializer; + import DS from 'ember-data'; + export default DS.JSONSerializer; } declare module 'ember-data/serializers/rest' { - import DS from 'ember-data'; - export default DS.RESTSerializer; + import DS from 'ember-data'; + export default DS.RESTSerializer; } -declare module "ember-data/store" { - import DS from "ember-data"; +declare module 'ember-data/store' { + import DS from 'ember-data'; export default DS.Store; } -declare module "ember-data/transform" { - import DS from "ember-data"; +declare module 'ember-data/transform' { + import DS from 'ember-data'; export default DS.Transform; } -declare module "ember-data/transforms/boolean" { - import DS from "ember-data"; +declare module 'ember-data/transforms/boolean' { + import DS from 'ember-data'; export default DS.BooleanTransform; } -declare module "ember-data/transforms/date" { - import DS from "ember-data"; +declare module 'ember-data/transforms/date' { + import DS from 'ember-data'; export default DS.DateTransform; } -declare module "ember-data/transforms/number" { - import DS from "ember-data"; +declare module 'ember-data/transforms/number' { + import DS from 'ember-data'; export default DS.NumberTransform; } -declare module "ember-data/transforms/string" { - import DS from "ember-data"; +declare module 'ember-data/transforms/string' { + import DS from 'ember-data'; export default DS.StringTransform; } -declare module "ember-data/transforms/transform" { - import DS from "ember-data"; +declare module 'ember-data/transforms/transform' { + import DS from 'ember-data'; export default DS.Transform; } diff --git a/types/ember-data/test/adapter.ts b/types/ember-data/test/adapter.ts index 17f69bcd9c..101ac3e42f 100644 --- a/types/ember-data/test/adapter.ts +++ b/types/ember-data/test/adapter.ts @@ -1,6 +1,11 @@ import Ember from 'ember'; import DS from 'ember-data'; +class Session extends Ember.Service {} +declare module '@ember/service' { + interface Registry { 'session': Session; } +} + const JsonApi = DS.JSONAPIAdapter.extend({ // Application specific overrides go here }); @@ -55,6 +60,13 @@ const UseAjaxOptionsWithOptionalThirdParams = DS.JSONAPIAdapter.extend({ } }); +declare module 'ember-data' { + interface ModelRegistry { + 'rootModel': any; + 'super-user': any; + } +} + // https://github.com/emberjs/data/blob/c9d8212c857ca78218ad98d11621819b38dba98f/tests/unit/adapters/build-url-mixin/build-url-test.js const BuildURLAdapter = DS.RESTAdapter.extend({ worksWithOnlyModelNameAndId() { diff --git a/types/ember-data/test/belongs-to.ts b/types/ember-data/test/belongs-to.ts index 9e59aa6128..bd1037a65e 100644 --- a/types/ember-data/test/belongs-to.ts +++ b/types/ember-data/test/belongs-to.ts @@ -3,8 +3,14 @@ import { assertType } from './lib/assert'; class Folder extends DS.Model { name = DS.attr('string'); - children = DS.hasMany('folder', { inverse: 'parent' }); - parent = DS.belongsTo('folder', { inverse: 'children' }); + children = DS.hasMany('folder', { inverse: 'parent' }); + parent = DS.belongsTo('folder', { inverse: 'children' }); +} + +declare module 'ember-data' { + interface ModelRegistry { + folder: Folder; + } } const folder = Folder.create(); diff --git a/types/ember-data/test/has-many.ts b/types/ember-data/test/has-many.ts index 7fb586ff4a..e24fb1b814 100644 --- a/types/ember-data/test/has-many.ts +++ b/types/ember-data/test/has-many.ts @@ -1,43 +1,56 @@ import DS from 'ember-data'; import { assertType } from './lib/assert'; -class Comment extends DS.Model { +class BlogComment extends DS.Model { text = DS.attr('string'); } +declare module 'ember-data' { + interface ModelRegistry { + 'blog-comment': BlogComment; + } +} + class BlogPost extends DS.Model { title = DS.attr('string'); - commentsAsync = DS.hasMany('comment'); - commentsSync = DS.hasMany('comment', { async: false }); + commentsAsync = DS.hasMany('blog-comment'); + commentsSync = DS.hasMany('blog-comment', { async: false }); } -const post = BlogPost.create(); +const blogPost = BlogPost.create(); -assertType>(post.get('commentsSync').reload()); -assertType(post.get('commentsSync').createRecord()); +assertType>(blogPost.get('commentsSync').reload()); +assertType(blogPost.get('commentsSync').createRecord()); -const comment = post.get('commentsSync').get('firstObject'); -assertType(comment); +const comment = blogPost.get('commentsSync').get('firstObject'); +assertType(comment); if (comment) { assertType(comment.get('text')); } -assertType>(post.get('commentsAsync').reload()); -assertType(post.get('commentsAsync').createRecord()); -assertType(post.get('commentsAsync').get('firstObject')); +assertType>(blogPost.get('commentsAsync').reload()); +assertType(blogPost.get('commentsAsync').createRecord()); +assertType(blogPost.get('commentsAsync').get('firstObject')); -const commentAsync = post.get('commentsAsync').get('firstObject'); -assertType(commentAsync); +const commentAsync = blogPost.get('commentsAsync').get('firstObject'); +assertType(commentAsync); if (commentAsync) { assertType(commentAsync.get('text')); } -assertType(post.get('commentsAsync').get('isFulfilled')); +assertType(blogPost.get('commentsAsync').get('isFulfilled')); -post.get('commentsAsync').then(comments => { - assertType(comments.get('firstObject')); +blogPost.get('commentsAsync').then(comments => { + assertType(comments.get('firstObject')); assertType(comments.get('firstObject')!.get('text')); }); +class PaymentMethod extends DS.Model {} +declare module 'ember-data' { + interface ModelRegistry { + 'payment-method': PaymentMethod; + } +} + class Polymorphic extends DS.Model { paymentMethods = DS.hasMany('payment-method', { polymorphic: true }); } diff --git a/types/ember-data/test/injections.ts b/types/ember-data/test/injections.ts index 4c0a6e4e6b..3e32a2b805 100644 --- a/types/ember-data/test/injections.ts +++ b/types/ember-data/test/injections.ts @@ -1,6 +1,14 @@ import Ember from 'ember'; import DS from 'ember-data'; +class MyModel extends DS.Model {} + +declare module 'ember-data' { + interface ModelRegistry { + 'my-model': MyModel; + } +} + Ember.Route.extend({ model(): any { return this.store.findAll('my-model'); diff --git a/types/ember-data/test/record-reference.ts b/types/ember-data/test/record-reference.ts index bb4fda42d4..f5bf973402 100644 --- a/types/ember-data/test/record-reference.ts +++ b/types/ember-data/test/record-reference.ts @@ -7,7 +7,13 @@ class User extends DS.Model { username = DS.attr('string'); } -let userRef = store.getReference('user', 1); +declare module 'ember-data' { + interface ModelRegistry { + user: User; + } +} + +let userRef = store.getReference('user', 1); // get the record of the reference (null if not yet available) let user = userRef.value(); diff --git a/types/ember-data/test/relationships.ts b/types/ember-data/test/relationships.ts index a878428bc4..fb89d4410c 100644 --- a/types/ember-data/test/relationships.ts +++ b/types/ember-data/test/relationships.ts @@ -16,14 +16,21 @@ class Comment extends DS.Model { author = DS.attr('string'); } -class BlogPost extends DS.Model { +class RelationalPost extends DS.Model { title = DS.attr('string'); tag = DS.attr('string'); - comments = DS.hasMany('comment', { async: true }); + comments = DS.hasMany('comment', { async: true }); relatedPosts = DS.hasMany('post'); } -let blogPost = store.peekRecord('blog-post', 1); +declare module 'ember-data' { + interface ModelRegistry { + 'relational-post': RelationalPost; + comment: Comment; + } +} + +let blogPost = store.peekRecord('relational-post', 1); blogPost!.get('comments').then((comments) => { // now we can work with the comments let author: string = comments.get('firstObject')!.get('author'); diff --git a/types/ember-data/test/serializer.ts b/types/ember-data/test/serializer.ts index 986020144f..baaa65ae9e 100644 --- a/types/ember-data/test/serializer.ts +++ b/types/ember-data/test/serializer.ts @@ -4,7 +4,8 @@ import DS from 'ember-data'; const JsonApi = DS.JSONAPISerializer.extend({}); const Customized = DS.JSONAPISerializer.extend({ - serialize(snapshot: DS.Snapshot, options: {}) { + serialize(snapshot: DS.Snapshot<'user'>, options: {}) { + const lookup = snapshot.belongsTo('username'); let json: any = this._super(...Array.from(arguments)); json.data.attributes.cost = { diff --git a/types/ember-data/test/store.ts b/types/ember-data/test/store.ts index a651cd23db..892242be99 100644 --- a/types/ember-data/test/store.ts +++ b/types/ember-data/test/store.ts @@ -4,13 +4,20 @@ import { assertType } from "./lib/assert"; declare const store: DS.Store; -class Comment extends DS.Model {} +class PostComment extends DS.Model {} class Post extends DS.Model { title = DS.attr('string'); - comments = DS.hasMany('comment'); + comments = DS.hasMany('comment'); } -let post = store.createRecord('post', { +declare module 'ember-data' { + interface ModelRegistry { + 'post': Post; + 'post-comment': PostComment; + } +} + +let post = store.createRecord('post', { title: 'Rails is Omakase', body: 'Lorem ipsum' }); @@ -20,7 +27,7 @@ post.save().then((saved) => { assertType(saved); }); -store.findRecord('post', 1).then(function(post) { +store.findRecord('post', 1).then(function(post) { post.get('title'); // => "Rails is Omakase" post.set('title', 'A new post'); post.save(); // => PATCH to '/posts/1' @@ -30,21 +37,30 @@ class User extends DS.Model { username = DS.attr('string'); } -store.queryRecord('user', {}).then(function(user) { +class Author extends User {} + +declare module 'ember-data' { + interface ModelRegistry { + 'user': User; + 'author': Author; + } +} + +store.queryRecord('user', {}).then(function(user) { let username = user.get('username'); console.log(`Currently logged in as ${username}`); }); -store.findAll('blog-post'); // => GET /blog-posts +store.findAll('post'); // => GET /posts store.findAll('author', { reload: true }).then(function(authors) { authors.getEach('id'); // ['first', 'second'] }); store.findAll('post', { - adapterOptions: { subscribe: false } + adapterOptions: { subscribe: false }, }); store.findAll('post', { include: 'comments,comments.author' }); -store.peekAll('blog-post'); // => no network request +store.peekAll('post'); // => no network request if (store.hasRecordForId('post', 1)) { let maybePost = store.peekRecord('post', 1); @@ -57,13 +73,19 @@ class Message extends DS.Model { hasBeenSeen = DS.attr('boolean'); } -const messages = store.peekAll('message'); +declare module 'ember-data' { + interface ModelRegistry { + message: Message; + } +} + +const messages = store.peekAll('message'); messages.forEach(function(message) { message.set('hasBeenSeen', true); }); messages.save(); -const people = store.peekAll('person'); +const people = store.peekAll('user'); people.get('isUpdating'); // false people.update().then(function() { people.get('isUpdating'); // false @@ -79,27 +101,27 @@ const MyRoute = Ember.Route.extend({ const MyRouteAsync = Ember.Route.extend({ async beforeModel(): Promise> { const store = Ember.get(this, 'store'); - return await store.findAll('someStoreRecord'); + return await store.findAll('post-comment'); }, async model(): Promise { const store = this.get('store'); - return await store.findRecord('someStoreRecord', 1); + return await store.findRecord('post-comment', 1); }, - async afterModel(): Promise> { - const post = await this.get('store').findRecord('post', 1); + async afterModel(): Promise> { + const post = await this.get('store').findRecord('post', 1); return await post.get('comments'); } }); class MyRouteAsyncES6 extends Ember.Route { async beforeModel(): Promise> { - return await this.store.findAll('someStoreRecord'); + return await this.store.findAll('post-comment'); } async model(): Promise { - return await this.store.findRecord('someStoreRecord', 1); + return await this.store.findRecord('post-comment', 1); } - async afterModel(): Promise> { - const post = await this.store.findRecord('post', 1); + async afterModel(): Promise> { + const post = await this.store.findRecord('post', 1); return await post.get('comments'); } } @@ -145,8 +167,22 @@ store.push({ }] }); -class UserAdapter extends DS.Adapter { } -class UserSerializer extends DS.Serializer { } +class UserAdapter extends DS.Adapter { + thisAdapterOnlyMethod(): void {} +} +class UserSerializer extends DS.Serializer { + thisSerializerOnlyMethod(): void {} +} -assertType(store.adapterFor('user')); -assertType(store.serializerFor('user')); +declare module 'ember-data' { + interface AdapterRegistry { + user: UserAdapter; + } + + interface SerializerRegistry { + user: UserSerializer; + } +} + +assertType(store.adapterFor('user')); +assertType(store.serializerFor('user')); diff --git a/types/ember-data/tsconfig.json b/types/ember-data/tsconfig.json index 15f77391aa..0845f9e795 100644 --- a/types/ember-data/tsconfig.json +++ b/types/ember-data/tsconfig.json @@ -10,10 +10,13 @@ "strictNullChecks": true, "strictFunctionTypes": false, "baseUrl": "../", - "typeRoots": ["../"], + "typeRoots": [ + "../" + ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true }, "files": [ "index.d.ts", @@ -31,4 +34,4 @@ "test/injections.ts", "test/error.ts" ] -} +} \ No newline at end of file diff --git a/types/ember-data/tslint.json b/types/ember-data/tslint.json index bd25c193fd..70eef4d46e 100644 --- a/types/ember-data/tslint.json +++ b/types/ember-data/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { + "strict-export-declare-modifiers": false, // Heavy use of Function type in this older package. "ban-types": false, "jsdoc-format": false, From 185f38ea6a215227f29879ca7270ca66ac8844ca Mon Sep 17 00:00:00 2001 From: Ben Stevens Date: Sun, 11 Feb 2018 17:41:29 +0000 Subject: [PATCH 015/128] Add 3D Secure and Payment Request types to stripe-v3 --- types/stripe-v3/index.d.ts | 167 ++++++++++++++++++++++++++--- types/stripe-v3/stripe-v3-tests.ts | 86 +++++++++++++++ 2 files changed, 236 insertions(+), 17 deletions(-) diff --git a/types/stripe-v3/index.d.ts b/types/stripe-v3/index.d.ts index 76666e747a..c2a6f8a550 100644 --- a/types/stripe-v3/index.d.ts +++ b/types/stripe-v3/index.d.ts @@ -12,18 +12,23 @@ declare var Stripe: stripe.StripeStatic; declare namespace stripe { interface StripeStatic { - (publicKey: string): Stripe; + (publicKey: string, options?: StripeOptions): Stripe; version: number; } interface Stripe { elements(options?: elements.ElementsCreateOptions): elements.Elements; createToken(element: elements.Element, options?: TokenOptions): Promise; + createToken(name: 'bank_account', options: BankAccountTokenOptions): Promise; + createToken(name: 'pii', options: PiiTokenOptions): Promise; + createSource(element: elements.Element, options?: {owner?: OwnerInfo}): Promise; createSource(options: SourceOptions): Promise; + retrieveSource(options: RetrieveSourceOptions): Promise; + paymentRequest(options: paymentRequest.StripePaymentRequestOptions): paymentRequest.StripePaymentRequest; } interface StripeOptions { - stripeAccount: string; + stripeAccount?: string; } interface TokenOptions { @@ -37,6 +42,33 @@ declare namespace stripe { currency?: string; } + interface BankAccountTokenOptions { + country: string; + currency: string; + routing_number: string; + account_number: string; + account_holder_name: string; + account_holder_type: string; + } + + interface PiiTokenOptions { + personal_id_number: string; + } + + interface OwnerInfo { + address?: { + city?: string; + country?: string; + line1?: string; + line2?: string; + postal_code?: string; + state?: string; + }; + name?: string; + email?: string; + phone?: string; + } + interface SourceOptions { type: string; flow?: 'redirect' | 'receiver' | 'code_verification' | 'none'; @@ -45,19 +77,7 @@ declare namespace stripe { }; currency?: string; amount?: number; - owner?: { - address?: { - city?: string; - country?: string; - line1?: string; - line2?: string; - postal_code?: string; - state?: string; - }; - name?: string; - email?: string; - phone?: string; - }; + owner?: OwnerInfo; metadata?: {}; statement_descriptor?: string; redirect?: { @@ -65,6 +85,9 @@ declare namespace stripe { }; token?: string; usage?: 'reusable' | 'single_use'; + three_d_secure?: { + card: string; + }; } interface Token { @@ -106,6 +129,15 @@ declare namespace stripe { last4: string; mandate_reference: string; }; + card?: Card; + status?: string; + redirect?: { + status: string; + url: string; + }; + three_d_secure?: { + authenticated: boolean; + }; } interface SourceResponse { @@ -165,6 +197,94 @@ declare namespace stripe { metadata: any; name?: string; tokenization_method?: tokenizationType; + three_d_secure?: 'required' | 'recommended' | 'optional' | 'not_supported'; + } + + interface RetrieveSourceOptions { + id: string; + client_secret: string; + } + + // Container for all payment request related types + namespace paymentRequest { + interface StripePaymentRequestUpdateOptions { + currency: string; + total: { + amount: number; + label: string; + pending?: boolean; + }; + displayItems?: Array<{ + amount: number; + label: string; + pending?: boolean; + }>; + shippingOptions?: ShippingOption[]; + } + + interface StripePaymentRequestOptions extends StripePaymentRequestUpdateOptions { + country: string; + requestPayerName?: boolean; + requestPayerEmail?: boolean; + requestPayerPhone?: boolean; + requestShipping?: boolean; + } + + interface UpdateDetails { + status: 'success' | 'fail' | 'invalid_shipping_address'; + total?: { + amount: number; + label: string; + pending?: boolean; + }; + displayItems?: Array<{ + amount: number; + label: string; + pending?: boolean; + }>; + shippingOptions?: ShippingOption[]; + } + + interface ShippingOption { + id: string; + label: string; + detail?: string; + amount: number; + } + + interface ShippingAddress { + country: string; + addressLine: string[]; + region: string; + city: string; + postalCode: string; + recipient: string; + phone: string; + sortingCode?: string; + dependentLocality?: string; + } + + interface StripePaymentResponse { + token?: Token; + source?: Source; + complete: (status: string) => void; + payerName?: string; + payerEmail?: string; + payerPhone?: string; + shippingAddress?: ShippingAddress; + shippingOption?: ShippingOption; + methodName: string; + } + + interface StripePaymentRequest { + canMakePayment(): Promise<{applePay?: boolean} | null>; + show(): void; + update(options: StripePaymentRequestUpdateOptions): void; + on(event: 'token' | 'source', handler: (response: StripePaymentResponse) => void): void; + on(event: 'cancel', handler: () => void): void; + on(event: 'shippingaddresschange', handler: (response: {updateWith: (options: UpdateDetails) => void, shippingAddress: ShippingAddress}) => void): void; + on(event: 'shippingoptionchange', handler: (response: {updateWith: (options: UpdateDetails) => void, shippingOption: ShippingOption}) => void): void; + } } // Container for all elements related types @@ -181,6 +301,7 @@ declare namespace stripe { // Cannot find name 'HTMLElement' mount(domElement: any): void; on(event: eventTypes, handler: handler): void; + on(event: 'click', handler: (response: {preventDefault: () => void}) => void): void; focus(): void; blur(): void; clear(): void; @@ -202,9 +323,9 @@ declare namespace stripe { locale?: string; } - type elementsType = 'card' | 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'postalCode'; + type elementsType = 'card' | 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'postalCode' | 'paymentRequestButton'; interface Elements { - create(type: elementsType, options: ElementsOptions): Element; + create(type: elementsType, options?: ElementsOptions): Element; } interface ElementsOptions { @@ -219,13 +340,16 @@ declare namespace stripe { hidePostalCode?: boolean; hideIcon?: boolean; iconStyle?: 'solid' | 'default'; + placeholder?: string; style?: { base?: Style; complete?: Style; empty?: Style; invalid?: Style; + paymentRequestButton?: PaymentRequestButtonStyleOptions; }; value?: string | { [objectKey: string]: string; }; + paymentRequest?: paymentRequest.StripePaymentRequest; } interface Style extends StyleOptions { @@ -234,11 +358,13 @@ declare namespace stripe { '::placeholder'?: StyleOptions; '::selection'?: StyleOptions; ':-webkit-autofill'?: StyleOptions; + '::-ms-clear'?: StyleOptions; } interface Font { family?: string; src?: string; + display?: string; style?: string; unicodeRange?: string; weight?: string; @@ -255,9 +381,16 @@ declare namespace stripe { iconColor?: string; lineHeight?: string; letterSpacing?: string; + textAlign?: string; textDecoration?: string; textShadow?: string; textTransform?: string; } + + interface PaymentRequestButtonStyleOptions { + type?: 'default' | 'donate' | 'buy'; + theme: 'dark' | 'light' | 'light-outline'; + height: string; + } } } diff --git a/types/stripe-v3/stripe-v3-tests.ts b/types/stripe-v3/stripe-v3-tests.ts index ccf86e5215..6e8740c5b2 100644 --- a/types/stripe-v3/stripe-v3-tests.ts +++ b/types/stripe-v3/stripe-v3-tests.ts @@ -42,7 +42,93 @@ describe("Stripe", () => { (error: stripe.Error) => { console.error(error); }); + // test 3D secure + const threeDSecureFrame = document.getElementById('3d-secure-frame'); + const ownerInfo = { + name: 'Jimmy', + address: { + line1: '1 High Street', + postal_code: 'XYZ' + } + }; + stripe.createSource(card, { owner: ownerInfo }).then(result => { + if (result.error) { + console.log(result.error.message); + return Promise.resolve(null); + } + if (!result.source) { + console.log('error'); + return Promise.resolve(null); + } + if (!result.source.card || result.source.card.three_d_secure === 'not_supported') { + // make regular payment... + return Promise.resolve(null); + } + return stripe.createSource({ + type: 'three_d_secure', + amount: 100, + currency: 'usd', + three_d_secure: { + card: result.source.id + }, + redirect: { + return_url: location.origin + '/3d-secure-processing-page' + } + }); + }).then(threeDSource => { + if (!threeDSource) { + return Promise.resolve(null); + } + if (threeDSource.error) { + if (threeDSource.error.code === 'payment_method_not_available') { + // make regular payment... + return Promise.resolve(null); + } + console.log('error'); + return Promise.resolve(null); + } + if (!threeDSource.source || threeDSource.source.status === 'failed' || !threeDSource.source.redirect) { + // make regular payment... + return Promise.resolve(null); + } + if (threeDSource.source.redirect.status === 'succeeded') { + // make charge... + return Promise.resolve(null); + } + threeDSecureFrame.setAttribute('src', threeDSource.source.redirect.url); + // now wait until chargeable then make the charge + return Promise.resolve(null); + }); card.destroy(); + // test payment request + const paymentRequest = stripe.paymentRequest({ + country: 'US', + currency: 'usd', + total: { + label: 'Demo total', + amount: 1000, + } + }); + const prButton = elements.create('paymentRequestButton', { paymentRequest }); + paymentRequest.canMakePayment().then(result => { + if (result) { + prButton.mount('#payment-request-button'); + } else { + document.getElementById('payment-request-button')!.style.display = 'none'; + } + }); + paymentRequest.on('token', ev => { + const body = JSON.stringify({token: ev.token!.id}); + // post to server... + Promise.resolve({ok: true}) + .then(response => { + if (response.ok) { + ev.complete('success'); + } else { + ev.complete('fail'); + } + }); + }); }); }); From 7f68bf98d706393dff02b0c80011f08518d54dd0 Mon Sep 17 00:00:00 2001 From: Ben Stevens Date: Sun, 11 Feb 2018 20:55:56 +0000 Subject: [PATCH 016/128] fix react-stripe-elements compatibility with updated stripe-v3 --- types/react-stripe-elements/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/react-stripe-elements/index.d.ts b/types/react-stripe-elements/index.d.ts index 72dea90475..6ef00684ca 100644 --- a/types/react-stripe-elements/index.d.ts +++ b/types/react-stripe-elements/index.d.ts @@ -45,8 +45,6 @@ export namespace ReactStripeElements { interface ElementProps extends ElementsOptions { className?: string; - paymentRequest?: object; - elementRef?(): void; onChange?(event: ElementChangeResponse): void; From f0e9ea8b77f8843670601d058105c2b60603382a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Kostrzyn=CC=81ski?= Date: Mon, 12 Feb 2018 12:06:51 +0100 Subject: [PATCH 017/128] update(react-faux-dom): Update types to reflect new library version. --- types/react-faux-dom/index.d.ts | 15 +++++++-------- types/react-faux-dom/react-faux-dom-tests.tsx | 9 +++++++++ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/types/react-faux-dom/index.d.ts b/types/react-faux-dom/index.d.ts index 59c771527d..9f79ce9ca1 100644 --- a/types/react-faux-dom/index.d.ts +++ b/types/react-faux-dom/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for react-faux-dom 3.2 +// Type definitions for react-faux-dom 4.1 // Project: https://github.com/Olical/react-faux-dom // Definitions by: Ali Taheri Moghaddar // Cleve Littlefield +// Michał Kostrzyński // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -19,11 +20,6 @@ export const defaultView: { getComputedStyle(node: Element): { getPropertyValue(name: string): string }; }; -export namespace mixins { - const core: any; - const anim: any; -} - export function createElement(nodeName: string): Element; export function createElementNS(namespace: string, nodeName: string): Element; @@ -31,8 +27,11 @@ export function createElementNS(namespace: string, nodeName: string): Element; export function compareDocumentPosition(): number; export interface ReactFauxDomProps { - connectFauxDOM?(node: string, name: string, discardNode?: any): Element; - animateFauxDOM?(duration: number): void; + connectFauxDOM(node: string, name: string, discardNode?: any): Element; + drawFauxDOM(): void; + animateFauxDOM(duration: number): void; + stopAnimatingFauxDOM(): void; + isAnimatingFauxDOM(): boolean; } export function withFauxDOM

(WrappedComponent: any): React.ClassicComponentClass

; diff --git a/types/react-faux-dom/react-faux-dom-tests.tsx b/types/react-faux-dom/react-faux-dom-tests.tsx index 2d864744bc..8bdd06a1e8 100644 --- a/types/react-faux-dom/react-faux-dom-tests.tsx +++ b/types/react-faux-dom/react-faux-dom-tests.tsx @@ -34,9 +34,18 @@ class MyReactComponent extends React.Component { .append('div') .html('Hello World!'); this.props.animateFauxDOM(800); + console.log(this.props.isAnimatingFauxDOM()); } } + componentDidUpdate() { + this.props.drawFauxDOM(); + } + + componentWillUnmount() { + this.props.stopAnimatingFauxDOM(); + } + render() { return

Here is some fancy data:

From 4359c578e731cec83a038865c2572bc50072c23f Mon Sep 17 00:00:00 2001 From: Ben Stevens Date: Mon, 12 Feb 2018 21:25:23 +0000 Subject: [PATCH 018/128] make requested changes --- types/stripe-v3/index.d.ts | 40 ++++++++++++++---------------- types/stripe-v3/stripe-v3-tests.ts | 22 ++++++++-------- 2 files changed, 29 insertions(+), 33 deletions(-) diff --git a/types/stripe-v3/index.d.ts b/types/stripe-v3/index.d.ts index c2a6f8a550..ea4fa9e05e 100644 --- a/types/stripe-v3/index.d.ts +++ b/types/stripe-v3/index.d.ts @@ -173,6 +173,9 @@ declare namespace stripe { type checkType = 'pass' | 'fail' | 'unavailable' | 'unchecked'; type fundingType = 'credit' | 'debit' | 'prepaid' | 'unknown'; type tokenizationType = 'apple_pay' | 'android_pay'; + enum ThreeDSecureSupport { + Required = 'required', Recommended = 'recommended', Optional = 'optional', NotSupported = 'not_supported' + } interface Card { id: string; object: string; @@ -197,7 +200,7 @@ declare namespace stripe { metadata: any; name?: string; tokenization_method?: tokenizationType; - three_d_secure?: 'required' | 'recommended' | 'optional' | 'not_supported'; + three_d_secure?: ThreeDSecureSupport; } interface RetrieveSourceOptions { @@ -207,18 +210,16 @@ declare namespace stripe { // Container for all payment request related types namespace paymentRequest { + interface DisplayItem { + amount: number; + label: string; + pending?: boolean; + } + interface StripePaymentRequestUpdateOptions { currency: string; - total: { - amount: number; - label: string; - pending?: boolean; - }; - displayItems?: Array<{ - amount: number; - label: string; - pending?: boolean; - }>; + total: DisplayItem; + displayItems?: Array; shippingOptions?: ShippingOption[]; } @@ -230,18 +231,13 @@ declare namespace stripe { requestShipping?: boolean; } + enum UpdateDetailsStatus { + Success = 'success', Fail = 'fail', InvalidShippingAddress = 'invalid_shipping_address' + } interface UpdateDetails { - status: 'success' | 'fail' | 'invalid_shipping_address'; - total?: { - amount: number; - label: string; - pending?: boolean; - }; - displayItems?: Array<{ - amount: number; - label: string; - pending?: boolean; - }>; + status: UpdateDetailsStatus; + total?: DisplayItem; + displayItems?: Array; shippingOptions?: ShippingOption[]; } diff --git a/types/stripe-v3/stripe-v3-tests.ts b/types/stripe-v3/stripe-v3-tests.ts index 6e8740c5b2..c3d696fceb 100644 --- a/types/stripe-v3/stripe-v3-tests.ts +++ b/types/stripe-v3/stripe-v3-tests.ts @@ -5,8 +5,8 @@ declare function it(desc: string, fn: () => void): void; describe("Stripe", () => { it("should excercise all Stripe API", () => { - const stripe = Stripe('public-key'); - const elements = stripe.elements(); + const stripeInstance = Stripe('public-key'); + const elements = stripeInstance.elements(); const style = { base: { color: '#32325d', @@ -31,7 +31,7 @@ describe("Stripe", () => { card.on('change', (resp: stripe.elements.ElementChangeResponse) => { console.log(resp.brand); }); - stripe.createToken(card, { + stripeInstance.createToken(card, { name: 'Jimmy', address_city: 'Toronto', address_country: 'Canada' @@ -51,20 +51,20 @@ describe("Stripe", () => { postal_code: 'XYZ' } }; - stripe.createSource(card, { owner: ownerInfo }).then(result => { + stripeInstance.createSource(card, { owner: ownerInfo }).then(result => { if (result.error) { - console.log(result.error.message); + // handle error return Promise.resolve(null); } if (!result.source) { - console.log('error'); + // handle error return Promise.resolve(null); } - if (!result.source.card || result.source.card.three_d_secure === 'not_supported') { + if (!result.source.card || result.source.card.three_d_secure === stripe.ThreeDSecureSupport.NotSupported) { // make regular payment... return Promise.resolve(null); } - return stripe.createSource({ + return stripeInstance.createSource({ type: 'three_d_secure', amount: 100, currency: 'usd', @@ -84,14 +84,14 @@ describe("Stripe", () => { // make regular payment... return Promise.resolve(null); } - console.log('error'); + // handle error return Promise.resolve(null); } if (!threeDSource.source || threeDSource.source.status === 'failed' || !threeDSource.source.redirect) { // make regular payment... return Promise.resolve(null); } - if (threeDSource.source.redirect.status === 'succeeded') { + if (threeDSource.source.status === 'chargeable') { // make charge... return Promise.resolve(null); } @@ -101,7 +101,7 @@ describe("Stripe", () => { }); card.destroy(); // test payment request - const paymentRequest = stripe.paymentRequest({ + const paymentRequest = stripeInstance.paymentRequest({ country: 'US', currency: 'usd', total: { From 6be187477440f5b655bee0cbbdd676bbb1a3ce54 Mon Sep 17 00:00:00 2001 From: Ben Stevens Date: Mon, 12 Feb 2018 21:39:34 +0000 Subject: [PATCH 019/128] revert enums and change Arra to T[] --- types/stripe-v3/index.d.ts | 14 ++++---------- types/stripe-v3/stripe-v3-tests.ts | 14 +++++++------- 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/types/stripe-v3/index.d.ts b/types/stripe-v3/index.d.ts index ea4fa9e05e..55cc5962df 100644 --- a/types/stripe-v3/index.d.ts +++ b/types/stripe-v3/index.d.ts @@ -173,9 +173,6 @@ declare namespace stripe { type checkType = 'pass' | 'fail' | 'unavailable' | 'unchecked'; type fundingType = 'credit' | 'debit' | 'prepaid' | 'unknown'; type tokenizationType = 'apple_pay' | 'android_pay'; - enum ThreeDSecureSupport { - Required = 'required', Recommended = 'recommended', Optional = 'optional', NotSupported = 'not_supported' - } interface Card { id: string; object: string; @@ -200,7 +197,7 @@ declare namespace stripe { metadata: any; name?: string; tokenization_method?: tokenizationType; - three_d_secure?: ThreeDSecureSupport; + three_d_secure?: 'required' | 'recommended' | 'optional' | 'not_supported'; } interface RetrieveSourceOptions { @@ -219,7 +216,7 @@ declare namespace stripe { interface StripePaymentRequestUpdateOptions { currency: string; total: DisplayItem; - displayItems?: Array; + displayItems?: DisplayItem[]; shippingOptions?: ShippingOption[]; } @@ -231,13 +228,10 @@ declare namespace stripe { requestShipping?: boolean; } - enum UpdateDetailsStatus { - Success = 'success', Fail = 'fail', InvalidShippingAddress = 'invalid_shipping_address' - } interface UpdateDetails { - status: UpdateDetailsStatus; + status: 'success' | 'fail' | 'invalid_shipping_address'; total?: DisplayItem; - displayItems?: Array; + displayItems?: DisplayItem[]; shippingOptions?: ShippingOption[]; } diff --git a/types/stripe-v3/stripe-v3-tests.ts b/types/stripe-v3/stripe-v3-tests.ts index c3d696fceb..201bad8678 100644 --- a/types/stripe-v3/stripe-v3-tests.ts +++ b/types/stripe-v3/stripe-v3-tests.ts @@ -5,8 +5,8 @@ declare function it(desc: string, fn: () => void): void; describe("Stripe", () => { it("should excercise all Stripe API", () => { - const stripeInstance = Stripe('public-key'); - const elements = stripeInstance.elements(); + const stripe = Stripe('public-key'); + const elements = stripe.elements(); const style = { base: { color: '#32325d', @@ -31,7 +31,7 @@ describe("Stripe", () => { card.on('change', (resp: stripe.elements.ElementChangeResponse) => { console.log(resp.brand); }); - stripeInstance.createToken(card, { + stripe.createToken(card, { name: 'Jimmy', address_city: 'Toronto', address_country: 'Canada' @@ -51,7 +51,7 @@ describe("Stripe", () => { postal_code: 'XYZ' } }; - stripeInstance.createSource(card, { owner: ownerInfo }).then(result => { + stripe.createSource(card, { owner: ownerInfo }).then(result => { if (result.error) { // handle error return Promise.resolve(null); @@ -60,11 +60,11 @@ describe("Stripe", () => { // handle error return Promise.resolve(null); } - if (!result.source.card || result.source.card.three_d_secure === stripe.ThreeDSecureSupport.NotSupported) { + if (!result.source.card || result.source.card.three_d_secure === 'not_supported') { // make regular payment... return Promise.resolve(null); } - return stripeInstance.createSource({ + return stripe.createSource({ type: 'three_d_secure', amount: 100, currency: 'usd', @@ -101,7 +101,7 @@ describe("Stripe", () => { }); card.destroy(); // test payment request - const paymentRequest = stripeInstance.paymentRequest({ + const paymentRequest = stripe.paymentRequest({ country: 'US', currency: 'usd', total: { From 14a405a1ae908aec5340d45b3e97bef5593a9c14 Mon Sep 17 00:00:00 2001 From: Zev Spitz Date: Tue, 13 Feb 2018 09:17:34 +0200 Subject: [PATCH 020/128] Fixes after running code --- types/activex-wia/activex-wia-tests.ts | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/types/activex-wia/activex-wia-tests.ts b/types/activex-wia/activex-wia-tests.ts index a5babea924..1375dceb27 100644 --- a/types/activex-wia/activex-wia-tests.ts +++ b/types/activex-wia/activex-wia-tests.ts @@ -1,3 +1,10 @@ +// tslint:disable-next-line:no-bad-reference +/// +// tslint:disable-next-line:no-bad-reference +/// + +// Note -- running these tests under cscript requires polyfills for some array methods, like forEach + const collectionToArray = (col: { Item(key: any): T }): T[] => { const results: T[] = []; const enumerator = new Enumerator(col); @@ -155,7 +162,16 @@ const collectionToArray = (col: { Item(key: any): T }): T[] => { { const v: WIA.Vector = new ActiveXObject('WIA.Vector'); v.SetFromString('This is a test', true, false); - collectionToArray(v).forEach(chr => WScript.Echo(String.fromCharCode(chr))); + + // when iterated using Enumerator / collectionToArray, each item comes back as an Automation Byte + // https://stackoverflow.com/questions/48757982/wia-vector-returns-something-which-is-not-a-number + // so the following falls, because fromCharCode is expecting a number + // collectionToArray(v).forEach(item => WScript.Echo(String.fromCharCode(item))); + + // Instead, use the Vector's Item method, or the Vector's default property: + for (let i = 1; i <= v.Count; i++) { + WScript.Echo(String.fromCharCode(v(i))); + } } // Display detailed image information @@ -367,13 +383,14 @@ Frame count = ${img.FrameCount}} // Create an imagefile object that contains a blank page { - const c = 0xFF0000FF; + // This fails with the error: `The Vector's Type is not compatible with this operation` + /*const c = 0xFF0000FF; const v: WIA.Vector = new ActiveXObject('WIA.Vector'); for (let i = 0; i < 4; i++) { v.Add(c); } const img = v.ImageFile(2, 2); - img.SaveFile('C:\\test.' + img.FileExtension); + img.SaveFile('C:\\test.' + img.FileExtension);*/ } interface WshArgumentsBase { From d198c2ff9a5b976a4992701612ac49f539509128 Mon Sep 17 00:00:00 2001 From: Zev Spitz Date: Tue, 13 Feb 2018 11:23:51 +0200 Subject: [PATCH 021/128] Fixes after test run --- types/activex-wia/activex-wia-tests.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/types/activex-wia/activex-wia-tests.ts b/types/activex-wia/activex-wia-tests.ts index 1375dceb27..c33385af14 100644 --- a/types/activex-wia/activex-wia-tests.ts +++ b/types/activex-wia/activex-wia-tests.ts @@ -1,9 +1,4 @@ -// tslint:disable-next-line:no-bad-reference -/// -// tslint:disable-next-line:no-bad-reference -/// - -// Note -- running these tests under cscript requires polyfills for some array methods, like forEach +// Note -- running these tests under cscript requires some ES5 polyfills const collectionToArray = (col: { Item(key: any): T }): T[] => { const results: T[] = []; From b7d2e66ca0db2c6540c30b108081b848759c1549 Mon Sep 17 00:00:00 2001 From: Edgar Simson Date: Tue, 13 Feb 2018 13:33:07 +0200 Subject: [PATCH 022/128] opentype.js: update to 0.7.3, add more tests --- types/opentype.js/index.d.ts | 426 +++++++++++++++++-------- types/opentype.js/opentype.js-tests.ts | 86 ++++- 2 files changed, 363 insertions(+), 149 deletions(-) diff --git a/types/opentype.js/index.d.ts b/types/opentype.js/index.d.ts index 24df752461..8dff7e3135 100644 --- a/types/opentype.js/index.d.ts +++ b/types/opentype.js/index.d.ts @@ -1,65 +1,153 @@ -// Type definitions for opentype.js +// Type definitions for opentype.js 0.7.3 // Project: https://github.com/nodebox/opentype.js // Definitions by: Dan Marshall +// Edgar Simson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 export as namespace opentype; -interface Contour extends Array { -} - -export class Encoding { - charset: string; - charToGlyphIndex(c: string): number; - font: Font; -} - -interface Field { - name: string; - type: string; - value: any; -} +/****************************************** + * FONT + ******************************************/ export class Font { - private nametoGlyphIndex; - private supported; - constructor(options: FontOptions); + names: FontNames; + unitsPerEm: number; ascender: number; - cffEncoding: Encoding; + descender: number; + createdTimestamp: number; + tables: { [tableName: string]: Table }; + supported: boolean; + glyphs: GlyphSet; + encoding: Encoding; + substitution: Substitution; + + readonly defaultRenderOptions: RenderOptions; + + constructor(options: FontConstructorOptions); + charToGlyph(c: string): Glyph; charToGlyphIndex(s: string): number; - descender: number; - download(): void; - draw(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; - drawMetrics(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; - drawPoints(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; - encoding: Encoding; - forEachGlyph(text: string, x: number, y: number, fontSize: number, options: RenderOptions, callback: { (glyph: Glyph, x: number, y: number, fontSize: number, options?: RenderOptions): void; }): void; + download(fileName?: string): void; + draw( + ctx: CanvasRenderingContext2D, + text: string, + x?: number, + y?: number, + fontSize?: number, + options?: RenderOptions + ): void; + drawMetrics( + ctx: CanvasRenderingContext2D, + text: string, + x?: number, + y?: number, + fontSize?: number, + options?: RenderOptions + ): void; + drawPoints( + ctx: CanvasRenderingContext2D, + text: string, + x?: number, + y?: number, + fontSize?: number, + options?: RenderOptions + ): void; + forEachGlyph( + text: string, + x: number | undefined, + y: number | undefined, + fontSize: number | undefined, + options: RenderOptions | undefined, + callback: { + ( + glyph: Glyph, + x: number, + y: number, + fontSize: number, + options?: RenderOptions + ): void; + } + ): number; + getAdvanceWidth( + text: string, + fontSize?: number, + options?: RenderOptions + ): number; getEnglishName(name: string): string; - getGposKerningValue: { (leftGlyph: Glyph | number, rightGlyph: Glyph | number): number; }; - getKerningValue(leftGlyph: Glyph | number, rightGlyph: Glyph | number): number; - getPath(text: string, x: number, y: number, fontSize: number, options?: RenderOptions): Path; - getPaths(text: string, x: number, y: number, fontSize: number, options?: RenderOptions): Path[]; - glyphs: GlyphSet; + getKerningValue( + leftGlyph: Glyph | number, + rightGlyph: Glyph | number + ): number; + getPath( + text: string, + x: number, + y: number, + fontSize: number, + options?: RenderOptions + ): Path; + getPaths( + text: string, + x: number, + y: number, + fontSize: number, + options?: RenderOptions + ): Path[]; glyphIndexToName(gid: number): string; glyphNames: GlyphNames; hasChar(c: string): boolean; kerningPairs: KerningPairs; - names: FontNames; nameToGlyph(name: string): Glyph; nameToGlyphIndex(name: string): number; numberOfHMetrics: number; numGlyphs: number; outlinesFormat: string; stringToGlyphs(s: string): Glyph[]; - tables: { [tableName: string]: Table; }; toArrayBuffer(): ArrayBuffer; toBuffer(): ArrayBuffer; toTables(): Table; - unitsPerEm: number; validate(): void; } +export type FontConstructorOptions = FontConstructorOptionsBase & + Partial & { + glyphs: Glyph[]; + }; + +interface FontOptions { + empty?: boolean; + familyName: string; + styleName: string; + fullName?: string; + postScriptName?: string; + designer?: string; + designerURL?: string; + manufacturer?: string; + manufacturerURL?: string; + license?: string; + licenseURL?: string; + version?: string; + description?: string; + copyright?: string; + trademark?: string; + unitsPerEm: number; + ascender: number; + descender: number; + createdTimestamp: number; + weightClass?: string; + widthClass?: string; + fsSelection?: string; +} + +interface FontConstructorOptionsBase { + familyName: string; + styleName: string; + unitsPerEm: number; + ascender: number; + descender: number; +} + interface FontNames { copyright: LocalizedName; description: LocalizedName; @@ -77,28 +165,33 @@ interface FontNames { version: LocalizedName; } -interface FontOptions { - copyright?: string; - ascender?: number; - descender?: number; - description?: string; - designer?: string; - designerURL?: string; - empty?: boolean; - familyName?: string; - fullName?: string; - glyphs?: Glyph[] | GlyphSet; - license?: string; - licenseURL?: string; - manufacturer?: string; - manufacturerURL?: string; - postScriptName?: string; - styleName?: string; - unitsPerEm?: number; - trademark?: string; - version?: string; +interface Table { + [propName: string]: any; + encode(): number[]; + fields: Field[]; + sizeOf(): number; + tables: Table[]; + tableName: string; } +interface KerningPairs { + [pair: string]: number; +} + +interface LocalizedName { + [lang: string]: string; +} + +interface Field { + name: string; + type: string; + value: any; +} + +/****************************************** + * GLYPH + ******************************************/ + export class Glyph { private index; private xMin; @@ -106,22 +199,49 @@ export class Glyph { private yMin; private yMax; private points; - constructor(options: GlyphOptions); - addUnicode(unicode: number): void; - advanceWidth: number; - bindConstructorValues(options: GlyphOptions): void; - draw(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; - drawMetrics(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; - drawPoints(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; - getContours(): Contour[]; - getMetrics(): Metrics; - getPath(x: number, y: number, fontSize: number): Path; + name: string; - path: Path | { (): Path; }; + path: Path | { (): Path }; unicode: number; unicodes: number[]; -} + advanceWidth: number; + constructor(options: GlyphOptions); + + addUnicode(unicode: number): void; + bindConstructorValues(options: GlyphOptions): void; + draw( + ctx: CanvasRenderingContext2D, + x?: number, + y?: number, + fontSize?: number, + options?: RenderOptions + ): void; + drawMetrics( + ctx: CanvasRenderingContext2D, + x?: number, + y?: number, + fontSize?: number, + options?: RenderOptions + ): void; + drawPoints( + ctx: CanvasRenderingContext2D, + x?: number, + y?: number, + fontSize?: number, + options?: RenderOptions + ): void; + getBoundingBox(): BoundingBox; + getContours(): Contour; + getMetrics(): Metrics; + getPath( + x?: number, + y?: number, + fontSize?: number, + options?: RenderOptions, + font?: Font + ): Path; +} interface GlyphOptions { advanceWidth?: number; index?: number; @@ -146,68 +266,10 @@ export class GlyphNames { export class GlyphSet { private font; private glyphs; - constructor(font: Font, glyphs: Glyph[] | { (): Glyph; }[]); + constructor(font: Font, glyphs: Glyph[] | { (): Glyph }[]); get(index: number): Glyph; length: number; - push(index: number, loader: { (): Glyph; }): void; -} - -interface KerningPairs { - [pair: string]: number; -} - -export function load(url: string, callback: { (error: any, font?: Font): void; }): void; - -export function loadSync(url: string): Font; - -interface LocalizedName { - [lang: string]: string; -} - -interface Metrics { - leftSideBearing: number; - rightSideBearing?: number; - xMax: number; - xMin: number; - yMax: number; - yMin: number; -} - -export function parse(buffer: any): Font; - -export class Path { - private fill; - private stroke; - private strokeWidth; - constructor(); - bezierCurveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): void; - close: () => void; - closePath(): void; - commands: PathCommand[]; - curveTo: (x1: number, y1: number, x2: number, y2: number, x: number, y: number) => void; - draw(ctx: CanvasRenderingContext2D): void; - extend(pathOrCommands: Path | PathCommand[]): void; - lineTo(x: number, y: number): void; - moveTo(x: number, y: number): void; - quadraticCurveTo(x1: number, y1: number, x: number, y: number): void; - quadTo: (x1: number, y1: number, x: number, y: number) => void; - toPathData(decimalPlaces: number): string; - toSVG(decimalPlaces: number): string; - unitsPerEm: number; -} - -interface PathCommand { - type: string; - x?: number; - y?: number; - x1?: number; - y1?: number; - x2?: number; - y2?: number; -} - -interface Point { - lastPointOfContour?: boolean; + push(index: number, loader: { (): Glyph }): void; } interface Post { @@ -227,14 +289,110 @@ interface Post { } interface RenderOptions { - kerning: boolean; + script?: string; + language?: string; + kerning?: boolean; + xScale?: number; + yScale?: number; + features?: { + [key: string]: boolean; + }; } -interface Table { - [propName: string]: any; - encode(): number[]; - fields: Field[]; - sizeOf(): number; - tables: Table[]; - tableName: string; +export interface Metrics { + leftSideBearing: number; + rightSideBearing?: number; + xMax: number; + xMin: number; + yMax: number; + yMin: number; } + +export interface Contour extends Array {} + +interface Point { + lastPointOfContour?: boolean; +} + +/****************************************** + * PATH + ******************************************/ + +export class Path { + private fill; + private stroke; + private strokeWidth; + constructor(); + bezierCurveTo( + x1: number, + y1: number, + x2: number, + y2: number, + x: number, + y: number + ): void; + close: () => void; + closePath(): void; + commands: PathCommand[]; + curveTo: ( + x1: number, + y1: number, + x2: number, + y2: number, + x: number, + y: number + ) => void; + draw(ctx: CanvasRenderingContext2D): void; + extend(pathOrCommands: Path | PathCommand[] | BoundingBox): void; + getBoundingBox(): BoundingBox; + lineTo(x: number, y: number): void; + moveTo(x: number, y: number): void; + quadraticCurveTo(x1: number, y1: number, x: number, y: number): void; + quadTo: (x1: number, y1: number, x: number, y: number) => void; + toDOMElement(decimalPlaces: number): SVGPathElement; + toPathData(decimalPlaces: number): string; + toSVG(decimalPlaces: number): string; + unitsPerEm: number; +} + +interface PathCommand { + type: string; + x?: number; + y?: number; + x1?: number; + y1?: number; + x2?: number; + y2?: number; +} + +/****************************************** + * UTIL CLASSES + ******************************************/ + +export class BoundingBox { + // TODO add methods +} + +export class Encoding { + charset: string; + charToGlyphIndex(c: string): number; + font: Font; +} + +export class Substitution { + constructor(font: Font); + // TODO add methods +} + +/****************************************** + * STATIC + ******************************************/ + +export function load( + url: string, + callback: { (error: any, font?: Font): void } +): void; + +export function loadSync(url: string): Font; + +export function parse(buffer: any): Font; diff --git a/types/opentype.js/opentype.js-tests.ts b/types/opentype.js/opentype.js-tests.ts index e4b9942bd9..6e1639a1b0 100644 --- a/types/opentype.js/opentype.js-tests.ts +++ b/types/opentype.js/opentype.js-tests.ts @@ -5,7 +5,7 @@ var ctx: CanvasRenderingContext2D; opentype.load('fonts/Roboto-Black.ttf', function(err, font) { if (err) { - alert('Font could not be loaded: ' + err); + alert('Font could not be loaded: ' + err); } else { var path = font.getPath('Hello, World!', 0, 150, 72); // If you just want to draw the text you can also use font.draw(ctx, text, x, y, fontSize). @@ -25,8 +25,6 @@ var notdefGlyph = new opentype.Glyph({ }); var aPath = new opentype.Path(); -aPath.moveTo(100, 0); -aPath.lineTo(100, 700); // more drawing instructions... var aGlyph = new opentype.Glyph({ name: 'A', @@ -42,22 +40,80 @@ var font = new opentype.Font({ unitsPerEm: 1000, ascender: 800, descender: -200, - glyphs: glyphs}); + + glyphs: glyphs +}); font.download(); -font.getPath('text', x, y, fontSize); -font.draw(ctx, 'text', x, y, fontSize); -font.drawPoints(ctx, 'text', x, y, fontSize); -font.drawMetrics(ctx, 'text', x, y, fontSize); -font.stringToGlyphs('string'); -font.charToGlyph('c'); -font.getKerningValue(notdefGlyph, aGlyph); +var hasChar: boolean = font.hasChar('a'); +var charIndex: number = font.charToGlyphIndex('a'); +var charGlyph: opentype.Glyph = font.charToGlyph('a'); +var charGlyphs: opentype.Glyph[] = font.stringToGlyphs('abc'); +var nameIndex: number = font.nameToGlyphIndex('a'); +var nameGlyph: opentype.Glyph = font.nameToGlyph('a'); +var indexName: string = font.glyphIndexToName(1); +var kerning: number = font.getKerningValue(notdefGlyph, aGlyph); +font.defaultRenderOptions.kerning = false; +var forEachWidth: number = font.forEachGlyph( + 'text', + x, + y, + fontSize, + { + kerning: true + }, + (glyph: opentype.Glyph, x: number, y: number, fontSize: number) => { + console.log({ + glyph, + x, + y, + fontSize + }); + } +); +var fontPath: opentype.Path = font.getPath('text', x, y, fontSize, {}); +var fontPaths: opentype.Path[] = font.getPaths('text', x, y, fontSize, {}); +var fontWidth: number = font.getAdvanceWidth('text', fontSize, { yScale: 0.5 }); +font.draw(ctx, 'text'); +font.drawPoints(ctx, 'text', x, y, fontSize, { yScale: 0.5 }); +font.drawMetrics(ctx, 'text', x, y, fontSize, { xScale: 1.1, yScale: 0.5 }); +var engName: string = font.getEnglishName('a'); +font.validate(); +var tables: opentype.Table = font.toTables(); +var ab: ArrayBuffer = font.toArrayBuffer(); +font.download(); +font.download('fileName.ttf'); -aGlyph.getPath(x, y, fontSize); -aGlyph.draw(ctx, x, y, fontSize); +aGlyph.bindConstructorValues({ advanceWidth: 1 }); +aGlyph.addUnicode(42); +var glyphBBox: opentype.BoundingBox = aGlyph.getBoundingBox(); +var glyphPathBasic: opentype.Path = aGlyph.getPath(); +var glyphPathFull: opentype.Path = aGlyph.getPath( + x, + y, + fontSize, + { xScale: 1, yScale: 2 }, + font +); +var glyphContours: opentype.Contour = aGlyph.getContours(); +var glyphMetrics: opentype.Metrics = aGlyph.getMetrics(); +aGlyph.draw(ctx, x, y, fontSize, {}); aGlyph.drawPoints(ctx, x, y, fontSize); aGlyph.drawMetrics(ctx, x, y, fontSize); +aPath.moveTo(100, 0); +aPath.lineTo(100, 700); +aPath.curveTo(100, 700, 200, 800, 150, 750); +aPath.bezierCurveTo(100, 700, 200, 800, 150, 750); +aPath.quadTo(100, 700, 200, 800); +aPath.quadraticCurveTo(100, 700, 200, 800); +aPath.close(); +aPath.closePath(); +aPath.extend(aPath); +aPath.extend(aPath.commands); +aPath.extend(aPath.getBoundingBox()); +var pathBBox: opentype.BoundingBox = aPath.getBoundingBox(); aPath.draw(ctx); -aPath.toPathData(7); -aPath.toSVG(7); +var pathData: string = aPath.toPathData(7); +var pathSvg: string = aPath.toSVG(7); +var pathDom: SVGPathElement = aPath.toDOMElement(7); From 8ede6478dd989e27a0de8008e74f6b0001fc9900 Mon Sep 17 00:00:00 2001 From: Manuel Guilbault Date: Tue, 13 Feb 2018 13:37:12 +0100 Subject: [PATCH 023/128] bootstrap-datepicker: add enableOnReadonly option --- types/bootstrap-datepicker/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/bootstrap-datepicker/index.d.ts b/types/bootstrap-datepicker/index.d.ts index a1beefa467..dfe358854e 100644 --- a/types/bootstrap-datepicker/index.d.ts +++ b/types/bootstrap-datepicker/index.d.ts @@ -58,6 +58,7 @@ interface DatepickerOptions { daysOfWeekHighlighted?:string|number[]; defaultViewDate?:Date|string|DatepickerViewDate; updateViewDate?:boolean; + enableOnReadonly?: boolean; } interface DatepickerViewDate { From 4d5c4c7a970b2ccfdc337c805d78711a74e72b9f Mon Sep 17 00:00:00 2001 From: Ethan Date: Tue, 13 Feb 2018 18:03:14 -0500 Subject: [PATCH 024/128] mongoose: fix Model.baseModelName --- types/mongoose/index.d.ts | 10 ++++++++-- types/mongoose/mongoose-tests.ts | 2 +- types/mongoose/v4/index.d.ts | 2 +- types/mongoose/v4/mongoose-tests.ts | 2 +- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index cb8ca38408..5994c15d2f 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1,6 +1,12 @@ // Type definitions for Mongoose 5.0.1 // Project: http://mongoosejs.com/ -// Definitions by: simonxca , horiuchi , sindrenm , lukasz-zak , Alorel , jendrikw +// Definitions by: simonxca +// horiuchi +// sindrenm +// lukasz-zak +// Alorel +// jendrikw +// Ethan Resnick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -2712,7 +2718,7 @@ declare module "mongoose" { * If this is a discriminator model, baseModelName is the * name of the base model. */ - baseModelName: String; + baseModelName: string | undefined; /** Collection the model uses. */ collection: Collection; diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 80050dad33..bf2f61f4a3 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -1479,7 +1479,7 @@ MongoModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, cb); MongoModel.where('age').gte(21).lte(65).exec(cb); MongoModel.where('age').gte(21).lte(65).where('name', /^b/i); new (mongoModel.base.model(''))(); -mongoModel.baseModelName.toLowerCase(); +mongoModel.baseModelName && mongoModel.baseModelName.toLowerCase(); mongoModel.collection.$format(99); mongoModel.collection.initializeOrderedBulkOp; mongoModel.collection.findOne; diff --git a/types/mongoose/v4/index.d.ts b/types/mongoose/v4/index.d.ts index 5f416b513a..4a4b7d224e 100644 --- a/types/mongoose/v4/index.d.ts +++ b/types/mongoose/v4/index.d.ts @@ -2730,7 +2730,7 @@ declare module "mongoose" { * If this is a discriminator model, baseModelName is the * name of the base model. */ - baseModelName: String; + baseModelName: string | undefined; /** Collection the model uses. */ collection: Collection; diff --git a/types/mongoose/v4/mongoose-tests.ts b/types/mongoose/v4/mongoose-tests.ts index 92adb61d83..64214fe983 100644 --- a/types/mongoose/v4/mongoose-tests.ts +++ b/types/mongoose/v4/mongoose-tests.ts @@ -1471,7 +1471,7 @@ MongoModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, cb); MongoModel.where('age').gte(21).lte(65).exec(cb); MongoModel.where('age').gte(21).lte(65).where('name', /^b/i); new (mongoModel.base.model(''))(); -mongoModel.baseModelName.toLowerCase(); +mongoModel.baseModelName && mongoModel.baseModelName.toLowerCase(); mongoModel.collection.$format(99); mongoModel.collection.initializeOrderedBulkOp; mongoModel.collection.findOne; From 2c31712ec57a29a1df39ac0aaa5095fb7130b157 Mon Sep 17 00:00:00 2001 From: Jonathan Siebern Date: Thu, 15 Feb 2018 14:32:31 +0100 Subject: [PATCH 025/128] DateTime.until needs to return a typeof Interval https://github.com/moment/luxon/blob/master/src/datetime.js#L1650 --- types/luxon/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index fac0b90fe6..0d66b9750c 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/moment/luxon#readme // Definitions by: Colby DeHart // Hyeonseok Yang +// Jonathan Siebern // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -209,7 +210,7 @@ declare module 'luxon' { toSQLTime(options?: Object): string; toString(): string; toUTC(offset?: number, options?: ZoneOptions): DateTime; - until(other: DateTime): Duration; + until(other: DateTime): Interval; valueOf(): number; } From 032b7a2ef4489b82878956f5b637ab5e553d0603 Mon Sep 17 00:00:00 2001 From: Jonathan Siebern Date: Thu, 15 Feb 2018 14:37:58 +0100 Subject: [PATCH 026/128] Update Luxon Version --- types/luxon/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 0d66b9750c..2275e331f0 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for luxon 0.2 +// Type definitions for luxon 0.4.0 // Project: https://github.com/moment/luxon#readme // Definitions by: Colby DeHart // Hyeonseok Yang From 8564c357bb3fdb9b6bd5e17a5991f323e188e8f2 Mon Sep 17 00:00:00 2001 From: Flavio Torres Date: Thu, 15 Feb 2018 14:18:23 -0200 Subject: [PATCH 027/128] Added Beforefind readPreference options --- types/parse/index.d.ts | 22 +++++++++++++++------- types/parse/parse-tests.ts | 8 ++++++++ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index d186211983..95331fe0d7 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -6,7 +6,7 @@ // Flavio Negrão // Wes Grimes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// /// @@ -907,22 +907,30 @@ declare namespace Parse { object: Object; } - interface BeforeFindTriggerRequest extends TriggerRequest { - query?: Query - count?: boolean - } interface AfterSaveRequest extends TriggerRequest { } interface AfterDeleteRequest extends TriggerRequest { } interface BeforeDeleteRequest extends TriggerRequest { } interface BeforeDeleteResponse extends FunctionResponse { } interface BeforeSaveRequest extends TriggerRequest { } - interface BeforeFindRequest extends BeforeFindTriggerRequest { } interface BeforeSaveResponse extends FunctionResponse { success: () => void; } + + // Read preference describes how MongoDB driver route read operations to the members of a replica set. + enum ReadPreferenceOption { + Primary = 'PRIMARY', + PrimaryPreferred = 'PRIMARY_PREFERRED', + Secondary = 'SECONDARY', + SecondaryPreferred = 'SECONDARY_PREFERRED', + Nearest = 'NEAREST' + } + interface BeforeFindRequest extends TriggerRequest { - query: Query; + query: Query + count: boolean + isGet: boolean + readPreference?: ReadPreferenceOption } function afterDelete(arg1: any, func?: (request: AfterDeleteRequest) => void): void; diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index 06ec062880..b8d0d0dd0e 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -390,6 +390,14 @@ function test_cloud_functions() { let user = request.user; // the user let isMaster = request.master; // if the query is run with masterKey let isCount = request.count; // if the query is a count operation (available on parse-server 2.4.0 or up) + let isGet = request.isGet; // if the query is a get operation + + // All possible read preferences + request.readPreference = Parse.Cloud.ReadPreferenceOption.Primary + request.readPreference = Parse.Cloud.ReadPreferenceOption.PrimaryPreferred + request.readPreference = Parse.Cloud.ReadPreferenceOption.Secondary + request.readPreference = Parse.Cloud.ReadPreferenceOption.SecondaryPreferred + request.readPreference = Parse.Cloud.ReadPreferenceOption.Nearest }); } From 7af3a74feca151d9c91de5c7321dec46e4537123 Mon Sep 17 00:00:00 2001 From: Flavio Torres Date: Thu, 15 Feb 2018 16:04:08 -0200 Subject: [PATCH 028/128] updated requirements to TypeScript Version: 2.4 --- types/parse-mockdb/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/parse-mockdb/index.d.ts b/types/parse-mockdb/index.d.ts index bff2e81935..94a1f63bb1 100644 --- a/types/parse-mockdb/index.d.ts +++ b/types/parse-mockdb/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/HustleInc/parse-mockdb // Definitions by: David Poetzsch-Heffter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// From 6aa8712fd31366a643db6abdcfb1d3da2f98647b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 16 Feb 2018 00:17:19 -0800 Subject: [PATCH 029/128] Fixed range for styled-component. --- types/grid-styled/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/grid-styled/package.json b/types/grid-styled/package.json index c381522c0d..f8a379b117 100644 --- a/types/grid-styled/package.json +++ b/types/grid-styled/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "styled-components": ">=2.0 || >=3.0" + "styled-components": "2.x - 3.x" } } From 8f35c97473e5fda1ccb4b7392c3f8cc3089ba0bb Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Fri, 16 Feb 2018 11:41:21 +0000 Subject: [PATCH 030/128] Cytoscape: fix filter() signature --- types/cytoscape/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/cytoscape/index.d.ts b/types/cytoscape/index.d.ts index ad0c8de371..b04ac2276e 100644 --- a/types/cytoscape/index.d.ts +++ b/types/cytoscape/index.d.ts @@ -427,7 +427,7 @@ declare namespace cytoscape { /** * Get elements in the graph matching the specified selector or filter function. */ - filter(selector: Selector | ((i: number, ele: Singular) => boolean)): CollectionElements; + filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionElements) => boolean)): CollectionElements; /** * Allow for manipulation of elements without triggering multiple style calculations or multiple redraws. @@ -2231,7 +2231,7 @@ declare namespace cytoscape { * ele - The element being considered. * http://js.cytoscape.org/#eles.filter */ - filter(selector: Selector | ((i: number, ele: CollectionElements) => boolean)): CollectionElements; + filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionElements) => boolean)): CollectionElements; /** * Get the nodes that match the specified selector. * From 0a53cd74f51582904f200e342fece664cb932e1b Mon Sep 17 00:00:00 2001 From: Aleh Zasypkin Date: Fri, 16 Feb 2018 12:53:09 +0100 Subject: [PATCH 031/128] ora: `promise` method should belong to `oraFactory`, not `Ora` class. --- types/ora/index.d.ts | 5 +++-- types/ora/ora-tests.ts | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/types/ora/index.d.ts b/types/ora/index.d.ts index 05c4c9b460..f5dd605073 100644 --- a/types/ora/index.d.ts +++ b/types/ora/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Basarat Ali Syed // Christian Rackerseder // BendingBender +// Aleh Zasypkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -118,14 +119,14 @@ declare class Ora { text: string; color: Color; - - promise(action: PromiseLike, options?: Options | string): Ora; } interface oraFactory { (options?: Options | string): Ora; new (options?: Options | string): Ora; + + promise(action: PromiseLike, options?: Options | string): Ora; } declare const ora: oraFactory; diff --git a/types/ora/ora-tests.ts b/types/ora/ora-tests.ts index ca5db9d70d..56a0d498c3 100644 --- a/types/ora/ora-tests.ts +++ b/types/ora/ora-tests.ts @@ -41,7 +41,7 @@ spinner.stopAndPersist({text: 'all done'}); spinner.stopAndPersist({symbol: '@', text: 'all done'}); const resolves = Promise.resolve(1); -spinner.promise(resolves, { +Ora.promise(resolves, { stream: new PassThrough(), text: 'foo', color: 'blue', From 8b0ad3367aad198e0aebeb1af7c7d093d25c7801 Mon Sep 17 00:00:00 2001 From: Edgar Simson Date: Sat, 17 Feb 2018 04:07:02 +0200 Subject: [PATCH 032/128] Require TS 2.1 for maker.js because of opentype.js --- types/maker.js/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/maker.js/index.d.ts b/types/maker.js/index.d.ts index ff6a7bd69e..e8be054a36 100644 --- a/types/maker.js/index.d.ts +++ b/types/maker.js/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Microsoft/maker.js // Definitions by: Dan Marshall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// /// From 6ce7d76242d00983b26675291702521ddd5d5310 Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Sat, 17 Feb 2018 11:23:32 +0100 Subject: [PATCH 033/128] resolve: add option preserveSymlinks --- types/resolve/index.d.ts | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/types/resolve/index.d.ts b/types/resolve/index.d.ts index 11a46b97a3..af32bf4097 100644 --- a/types/resolve/index.d.ts +++ b/types/resolve/index.d.ts @@ -63,40 +63,46 @@ declare function resolveSync(id: string, opts?: resolve.SyncOpts): string; /** * Return whether a package is in core - * - * @param id */ -declare function resolveIsCore(id: string): boolean; +declare function resolveIsCore(id: string): boolean | undefined; declare namespace resolve { interface Opts { - // directory to begin resolving from (defaults to __dirname) + /** directory to begin resolving from (defaults to __dirname) */ basedir?: string; - // package.json data applicable to the module being loaded + /** package.json data applicable to the module being loaded */ package?: any; - // array of file extensions to search in order (defaults to ['.js']) + /** array of file extensions to search in order (defaults to ['.js']) */ extensions?: string | string[]; - // transform the parsed package.json contents before looking at the "main" field + /** transform the parsed package.json contents before looking at the "main" field */ packageFilter?: (pkg: any, pkgfile: string) => any; - // transform a path within a package + /** transform a path within a package */ pathFilter?: (pkg: any, path: string, relativePath: string) => string; - // require.paths array to use if nothing is found on the normal node_modules recursive walk (probably don't use this) + /** require.paths array to use if nothing is found on the normal node_modules recursive walk (probably don't use this) */ paths?: string | string[]; - // directory (or directories) in which to recursively look for modules. (default to 'node_modules') + /** directory (or directories) in which to recursively look for modules. (default to 'node_modules') */ moduleDirectory?: string | string[] + /** + * if true, doesn't resolve `basedir` to real path before resolving. + * This is the way Node resolves dependencies when executed with the --preserve-symlinks flag. + * + * Note: this property is currently true by default but it will be changed to false in the next major version because Node's resolution + * algorithm does not preserve symlinks by default. + */ + preserveSymlinks?: boolean; } export interface AsyncOpts extends Opts { - // how to read files asynchronously (defaults to fs.readFile) + /** how to read files asynchronously (defaults to fs.readFile) */ readFile?: (file: string, cb: readFileCallback) => void; - // function to asynchronously test whether a file exists + /** function to asynchronously test whether a file exists */ isFile?: (file: string, cb: isFileCallback) => void; } export interface SyncOpts extends Opts { - // how to read files synchronously (defaults to fs.readFileSync) + /** how to read files synchronously (defaults to fs.readFileSync) */ readFileSync?: (file: string, charset: string) => string | Buffer; - // function to synchronously test whether a file exists + /** function to synchronously test whether a file exists */ isFile?: (file: string) => boolean; } From a1133810eba5485839de5f14c164e5b7f4cdb508 Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Sat, 17 Feb 2018 11:26:27 +0100 Subject: [PATCH 034/128] Add test --- types/resolve/resolve-tests.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/resolve/resolve-tests.ts b/types/resolve/resolve-tests.ts index 1ebaa5bfb4..909d2a77b3 100644 --- a/types/resolve/resolve-tests.ts +++ b/types/resolve/resolve-tests.ts @@ -41,7 +41,8 @@ function test_options_async() { return cb(null, stat.isFile()); } }); - } + }, + preserveSymlinks: false, }, function(error, resolved, pkg) { if (error) { console.error(error.message); @@ -72,7 +73,8 @@ function test_options_sync() { } catch (error) { return false; } - } + }, + preserveSymlinks: true, }); console.log(resolved); resolved = resolve.sync('typescript', { From a9956ccc9717d38f6b9b1ddfcf26b7204ba682a9 Mon Sep 17 00:00:00 2001 From: Jakub Synowiec Date: Sat, 17 Feb 2018 16:08:37 +0100 Subject: [PATCH 035/128] Wrap in module --- types/electron-store/index.d.ts | 145 ++++++++++++++++---------------- 1 file changed, 74 insertions(+), 71 deletions(-) diff --git a/types/electron-store/index.d.ts b/types/electron-store/index.d.ts index e270fb2b8e..1bf43b71a8 100644 --- a/types/electron-store/index.d.ts +++ b/types/electron-store/index.d.ts @@ -1,79 +1,82 @@ // Type definitions for electron-store 1.2 // Project: https://github.com/sindresorhus/electron-store // Definitions by: Daniel Perez Alvarez +// Jakub Synowiec // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface ElectronStoreOptions { - /** - * Default config. - */ - defaults?: {}; +declare module 'electron-store' { + interface ElectronStoreOptions { + /** + * Default config. + */ + defaults?: {}; - /** - * Name of the config file (without extension). - */ - name?: string; + /** + * Name of the config file (without extension). + */ + name?: string; - /** - * Storage file location. *Don't specify this unless absolutely necessary!* - */ - cwd?: string; + /** + * Storage file location. *Don't specify this unless absolutely necessary!* + */ + cwd?: string; + } + + class ElectronStore implements Iterable<[string, string | number | boolean | symbol | {}]> { + constructor(options?: ElectronStoreOptions); + + /** + * Sets an item. + */ + set(key: string, value: any): void; + + /** + * Sets multiple items at once. + */ + set(object: {}): void; + + /** + * Retrieves an item. + */ + get(key: string, defaultValue?: any): any; + + /** + * Checks if an item exists. + */ + has(key: string): boolean; + + /** + * Deletes an item. + */ + delete(key: string): void; + + /** + * Deletes all items. + */ + clear(): void; + + /** + * Open the storage file in the user's editor. + */ + openInEditor(): void; + + /** + * Gets the item count. + */ + size: number; + + /** + * Gets all the config as an object or replace the current config with an object. + */ + store: {}; + + /** + * Gets the path to the config file. + */ + path: string; + + [Symbol.iterator](): Iterator<[string, string | number | boolean | symbol | {}]>; + } + + export = ElectronStore; } - -declare class ElectronStore implements Iterable<[string, string | number | boolean | symbol | {}]> { - constructor(options?: ElectronStoreOptions); - - /** - * Sets an item. - */ - set(key: string, value: any): void; - - /** - * Sets multiple items at once. - */ - set(object: {}): void; - - /** - * Retrieves an item. - */ - get(key: string, defaultValue?: any): any; - - /** - * Checks if an item exists. - */ - has(key: string): boolean; - - /** - * Deletes an item. - */ - delete(key: string): void; - - /** - * Deletes all items. - */ - clear(): void; - - /** - * Open the storage file in the user's editor. - */ - openInEditor(): void; - - /** - * Gets the item count. - */ - size: number; - - /** - * Gets all the config as an object or replace the current config with an object. - */ - store: {}; - - /** - * Gets the path to the config file. - */ - path: string; - - [Symbol.iterator](): Iterator<[string, string | number | boolean | symbol | {}]>; -} - -export = ElectronStore; From 3189dabe5c3659e81e9b5da76e4050edf586e476 Mon Sep 17 00:00:00 2001 From: Jakub Synowiec Date: Sat, 17 Feb 2018 16:09:46 +0100 Subject: [PATCH 036/128] Add types for JSON-serializable values --- types/electron-store/index.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/types/electron-store/index.d.ts b/types/electron-store/index.d.ts index 1bf43b71a8..c99f0775d6 100644 --- a/types/electron-store/index.d.ts +++ b/types/electron-store/index.d.ts @@ -5,6 +5,14 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'electron-store' { + type JSONValue = string | number | boolean | JSONObject | JSONArray; + + interface JSONObject { + [x: string]: JSONValue; + } + + interface JSONArray extends Array {} + interface ElectronStoreOptions { /** * Default config. From 6fc5287a015fbf530b34d58e1155c81bb9491ade Mon Sep 17 00:00:00 2001 From: Jakub Synowiec Date: Sat, 17 Feb 2018 16:12:58 +0100 Subject: [PATCH 037/128] Add generic type for options and class --- types/electron-store/index.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/types/electron-store/index.d.ts b/types/electron-store/index.d.ts index c99f0775d6..cde9890c55 100644 --- a/types/electron-store/index.d.ts +++ b/types/electron-store/index.d.ts @@ -13,11 +13,11 @@ declare module 'electron-store' { interface JSONArray extends Array {} - interface ElectronStoreOptions { + interface ElectronStoreOptions { /** * Default config. */ - defaults?: {}; + defaults?: T; /** * Name of the config file (without extension). @@ -30,8 +30,8 @@ declare module 'electron-store' { cwd?: string; } - class ElectronStore implements Iterable<[string, string | number | boolean | symbol | {}]> { - constructor(options?: ElectronStoreOptions); + class ElectronStore implements Iterable<[keyof T, JSONValue]> { + constructor(options?: ElectronStoreOptions); /** * Sets an item. @@ -83,7 +83,7 @@ declare module 'electron-store' { */ path: string; - [Symbol.iterator](): Iterator<[string, string | number | boolean | symbol | {}]>; + [Symbol.iterator](): Iterator<[keyof T, JSONValue]>; } export = ElectronStore; From 4dd280734ca80b2c1903f3234da2be317ff657b3 Mon Sep 17 00:00:00 2001 From: Jakub Synowiec Date: Sat, 17 Feb 2018 16:15:49 +0100 Subject: [PATCH 038/128] Use lookup types so TypeScript can infer allowed keys and types --- types/electron-store/index.d.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/types/electron-store/index.d.ts b/types/electron-store/index.d.ts index cde9890c55..2121f7a452 100644 --- a/types/electron-store/index.d.ts +++ b/types/electron-store/index.d.ts @@ -36,27 +36,30 @@ declare module 'electron-store' { /** * Sets an item. */ + set(key: K, value: T[K]): void; set(key: string, value: any): void; /** * Sets multiple items at once. */ - set(object: {}): void; + set(object: Pick | T): void; + set(object: JSONObject): void /** * Retrieves an item. */ + get(key: K, defaultValue?: JSONValue): T[K]; get(key: string, defaultValue?: any): any; /** * Checks if an item exists. */ - has(key: string): boolean; + has(key: K | string): boolean; /** * Deletes an item. */ - delete(key: string): void; + delete(key: K | string): void; /** * Deletes all items. From 992cd81c05f6c926463556b9f1b42322afb1fd54 Mon Sep 17 00:00:00 2001 From: Jakub Synowiec Date: Sat, 17 Feb 2018 16:18:38 +0100 Subject: [PATCH 039/128] Add missing onDidChange --- types/electron-store/index.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/electron-store/index.d.ts b/types/electron-store/index.d.ts index 2121f7a452..30091af75c 100644 --- a/types/electron-store/index.d.ts +++ b/types/electron-store/index.d.ts @@ -71,6 +71,9 @@ declare module 'electron-store' { */ openInEditor(): void; + onDidChange(key: K, callback: (newValue: T[K], oldValue: T[K]) => void): void; + onDidChange(key: string, callback: (newValue: JSONValue, oldValue: JSONValue) => void): void; + /** * Gets the item count. */ From 5ff2de3ce7763d332b3f4b941d87faa9b960f571 Mon Sep 17 00:00:00 2001 From: Jakub Synowiec Date: Sat, 17 Feb 2018 16:19:37 +0100 Subject: [PATCH 040/128] Use generic type for store --- types/electron-store/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/electron-store/index.d.ts b/types/electron-store/index.d.ts index 30091af75c..e15a8aa7e7 100644 --- a/types/electron-store/index.d.ts +++ b/types/electron-store/index.d.ts @@ -82,7 +82,7 @@ declare module 'electron-store' { /** * Gets all the config as an object or replace the current config with an object. */ - store: {}; + store: T; /** * Gets the path to the config file. From 60f12b76412342fd1a62cb34d0373d30dfd9dde8 Mon Sep 17 00:00:00 2001 From: Jakub Synowiec Date: Sat, 17 Feb 2018 16:38:37 +0100 Subject: [PATCH 041/128] Update comments using official package docs --- types/electron-store/index.d.ts | 124 ++++++++++++++++---------------- 1 file changed, 64 insertions(+), 60 deletions(-) diff --git a/types/electron-store/index.d.ts b/types/electron-store/index.d.ts index e15a8aa7e7..6a30daa8fc 100644 --- a/types/electron-store/index.d.ts +++ b/types/electron-store/index.d.ts @@ -14,83 +14,87 @@ declare module 'electron-store' { interface JSONArray extends Array {} interface ElectronStoreOptions { - /** - * Default config. - */ - defaults?: T; + /** + * Default data. + */ + defaults?: T; - /** - * Name of the config file (without extension). - */ - name?: string; + /** + * Name of the storage file (without extension). + */ + name?: string; - /** - * Storage file location. *Don't specify this unless absolutely necessary!* - */ - cwd?: string; + /** + * Storage file location. Don't specify this unless absolutely necessary! + */ + cwd?: string; } class ElectronStore implements Iterable<[keyof T, JSONValue]> { - constructor(options?: ElectronStoreOptions); + constructor(options?: ElectronStoreOptions); - /** - * Sets an item. - */ - set(key: K, value: T[K]): void; - set(key: string, value: any): void; + /** + * Set an item. + */ + set(key: K, value: T[K]): void; + set(key: string, value: any): void; - /** - * Sets multiple items at once. - */ - set(object: Pick | T): void; - set(object: JSONObject): void + /** + * Set multiple items at once. + */ + set(object: Pick | T): void; + set(object: JSONObject): void - /** - * Retrieves an item. - */ - get(key: K, defaultValue?: JSONValue): T[K]; - get(key: string, defaultValue?: any): any; + /** + * Get an item or defaultValue if the item does not exist. + */ + get(key: K, defaultValue?: JSONValue): T[K]; + get(key: string, defaultValue?: any): any; - /** - * Checks if an item exists. - */ - has(key: K | string): boolean; + /** + * Check if an item exists. + */ + has(key: K | string): boolean; - /** - * Deletes an item. - */ - delete(key: K | string): void; + /** + * Delete an item. + */ + delete(key: K | string): void; - /** - * Deletes all items. - */ - clear(): void; + /** + * Delete all items. + */ + clear(): void; - /** - * Open the storage file in the user's editor. - */ - openInEditor(): void; + /** + * Watches the given key, calling callback on any changes. When a key is first set oldValue + * will be undefined, and when a key is deleted newValue will be undefined. + */ + onDidChange(key: K, callback: (newValue: T[K], oldValue: T[K]) => void): void; + onDidChange(key: string, callback: (newValue: JSONValue, oldValue: JSONValue) => void): void; - onDidChange(key: K, callback: (newValue: T[K], oldValue: T[K]) => void): void; - onDidChange(key: string, callback: (newValue: JSONValue, oldValue: JSONValue) => void): void; + /** + * Get the item count. + */ + size: number; - /** - * Gets the item count. - */ - size: number; + /** + * Get all the data as an object or replace the current data with an object. + */ + store: T; - /** - * Gets all the config as an object or replace the current config with an object. - */ - store: T; + /** + * Get the path to the storage file. + */ + path: string; - /** - * Gets the path to the config file. - */ - path: string; + /** + * Open the storage file in the user's editor. + */ + openInEditor(): void; - [Symbol.iterator](): Iterator<[keyof T, JSONValue]>; + [Symbol.iterator](): Iterator<[keyof T, JSONValue]>; } export = ElectronStore; -} + } From 40f344779647caa52e175487c7f69d39b5c5ccfa Mon Sep 17 00:00:00 2001 From: Jakub Synowiec Date: Sat, 17 Feb 2018 16:59:09 +0100 Subject: [PATCH 042/128] Add encryptionKey option --- types/electron-store/index.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/types/electron-store/index.d.ts b/types/electron-store/index.d.ts index 6a30daa8fc..1e687fee0e 100644 --- a/types/electron-store/index.d.ts +++ b/types/electron-store/index.d.ts @@ -4,6 +4,8 @@ // Jakub Synowiec // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + declare module 'electron-store' { type JSONValue = string | number | boolean | JSONObject | JSONArray; @@ -28,6 +30,11 @@ declare module 'electron-store' { * Storage file location. Don't specify this unless absolutely necessary! */ cwd?: string; + + /** + * When specified, the store will be encrypted using the aes-256-cbc encryption algorithm. + */ + encryptionKey?: string | Buffer; } class ElectronStore implements Iterable<[keyof T, JSONValue]> { From bb345b4d8984bbe89dc152b54f69d3765ce55542 Mon Sep 17 00:00:00 2001 From: Jakub Synowiec Date: Sat, 17 Feb 2018 17:02:32 +0100 Subject: [PATCH 043/128] Reformat document according to guidelines --- types/electron-store/index.d.ts | 134 +++++++++++++++++--------------- 1 file changed, 70 insertions(+), 64 deletions(-) diff --git a/types/electron-store/index.d.ts b/types/electron-store/index.d.ts index 1e687fee0e..357ec98460 100644 --- a/types/electron-store/index.d.ts +++ b/types/electron-store/index.d.ts @@ -16,20 +16,20 @@ declare module 'electron-store' { interface JSONArray extends Array {} interface ElectronStoreOptions { - /** - * Default data. - */ - defaults?: T; + /** + * Default data. + */ + defaults?: T; - /** - * Name of the storage file (without extension). - */ - name?: string; + /** + * Name of the storage file (without extension). + */ + name?: string; - /** - * Storage file location. Don't specify this unless absolutely necessary! - */ - cwd?: string; + /** + * Storage file location. Don't specify this unless absolutely necessary! + */ + cwd?: string; /** * When specified, the store will be encrypted using the aes-256-cbc encryption algorithm. @@ -38,70 +38,76 @@ declare module 'electron-store' { } class ElectronStore implements Iterable<[keyof T, JSONValue]> { - constructor(options?: ElectronStoreOptions); + constructor(options?: ElectronStoreOptions); - /** - * Set an item. - */ - set(key: K, value: T[K]): void; - set(key: string, value: any): void; + /** + * Set an item. + */ + set(key: K, value: T[K]): void; + set(key: string, value: any): void; - /** - * Set multiple items at once. - */ - set(object: Pick | T): void; - set(object: JSONObject): void + /** + * Set multiple items at once. + */ + set(object: Pick | T): void; + set(object: JSONObject): void; - /** - * Get an item or defaultValue if the item does not exist. - */ - get(key: K, defaultValue?: JSONValue): T[K]; - get(key: string, defaultValue?: any): any; + /** + * Get an item or defaultValue if the item does not exist. + */ + get(key: K, defaultValue?: JSONValue): T[K]; + get(key: string, defaultValue?: any): any; - /** - * Check if an item exists. - */ - has(key: K | string): boolean; + /** + * Check if an item exists. + */ + has(key: K | string): boolean; - /** - * Delete an item. - */ - delete(key: K | string): void; + /** + * Delete an item. + */ + delete(key: K | string): void; - /** - * Delete all items. - */ - clear(): void; + /** + * Delete all items. + */ + clear(): void; - /** - * Watches the given key, calling callback on any changes. When a key is first set oldValue - * will be undefined, and when a key is deleted newValue will be undefined. - */ - onDidChange(key: K, callback: (newValue: T[K], oldValue: T[K]) => void): void; - onDidChange(key: string, callback: (newValue: JSONValue, oldValue: JSONValue) => void): void; + /** + * Watches the given key, calling callback on any changes. When a key is first set oldValue + * will be undefined, and when a key is deleted newValue will be undefined. + */ + onDidChange( + key: K, + callback: (newValue: T[K], oldValue: T[K]) => void + ): void; + onDidChange( + key: string, + callback: (newValue: JSONValue, oldValue: JSONValue) => void + ): void; - /** - * Get the item count. - */ - size: number; + /** + * Get the item count. + */ + size: number; - /** - * Get all the data as an object or replace the current data with an object. - */ - store: T; + /** + * Get all the data as an object or replace the current data with an object. + */ + store: T; - /** - * Get the path to the storage file. - */ - path: string; + /** + * Get the path to the storage file. + */ + path: string; - /** - * Open the storage file in the user's editor. - */ - openInEditor(): void; + /** + * Open the storage file in the user's editor. + */ + openInEditor(): void; - [Symbol.iterator](): Iterator<[keyof T, JSONValue]>; + [Symbol.iterator](): Iterator<[keyof T, JSONValue]>; } export = ElectronStore; - } +} From afa07abdbbbbc3a0d58342fa9726c6236649f581 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Sat, 17 Feb 2018 00:51:03 -0800 Subject: [PATCH 044/128] Added 'set-value'. --- types/set-value/index.d.ts | 23 +++++++++++++++++++++++ types/set-value/set-value-tests.ts | 12 ++++++++++++ types/set-value/tsconfig.json | 23 +++++++++++++++++++++++ types/set-value/tslint.json | 1 + 4 files changed, 59 insertions(+) create mode 100644 types/set-value/index.d.ts create mode 100644 types/set-value/set-value-tests.ts create mode 100644 types/set-value/tsconfig.json create mode 100644 types/set-value/tslint.json diff --git a/types/set-value/index.d.ts b/types/set-value/index.d.ts new file mode 100644 index 0000000000..be3f2c8b0a --- /dev/null +++ b/types/set-value/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for set-value 2.0 +// Project: https://github.com/jonschlinkert/set-value +// Definitions by: Daniel Rosenwasser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export = set; + +// Technically, everything will fall to the last overload, +// but the first one can be useful for signature help. + +/** + * @param object The object to set `value` on + * @param prop The property to set. + * @param value The value to set on `object[prop]` + */ +declare function set(object: T, prop: K, value: T[K]): void; +/** + * @param object The object to set `value` on + * @param prop The property to set. Dot-notation may be used. + * @param value The value to set on `object[prop]` + */ +declare function set(object: object, prop: string, value: any): void; diff --git a/types/set-value/set-value-tests.ts b/types/set-value/set-value-tests.ts new file mode 100644 index 0000000000..b2b6e78166 --- /dev/null +++ b/types/set-value/set-value-tests.ts @@ -0,0 +1,12 @@ +import set = require("set-value"); + +{ + const obj = {}; + set(obj, "a.b.c", "d"); + set({}, "a\\.b.c", "d"); +} + +{ + const obj = { a: 100 }; + set(obj, "a", 1000); +} diff --git a/types/set-value/tsconfig.json b/types/set-value/tsconfig.json new file mode 100644 index 0000000000..38bec2daa7 --- /dev/null +++ b/types/set-value/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "set-value-tests.ts" + ] +} diff --git a/types/set-value/tslint.json b/types/set-value/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/set-value/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From c448d9b017a9806d5ebf253384bbf027b2bb9072 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Sat, 17 Feb 2018 01:16:48 -0800 Subject: [PATCH 045/128] Added 'get-value'. --- types/get-value/get-value-tests.ts | 22 +++++++++++++ types/get-value/index.d.ts | 53 ++++++++++++++++++++++++++++++ types/get-value/tsconfig.json | 23 +++++++++++++ types/get-value/tslint.json | 1 + 4 files changed, 99 insertions(+) create mode 100644 types/get-value/get-value-tests.ts create mode 100644 types/get-value/index.d.ts create mode 100644 types/get-value/tsconfig.json create mode 100644 types/get-value/tslint.json diff --git a/types/get-value/get-value-tests.ts b/types/get-value/get-value-tests.ts new file mode 100644 index 0000000000..9e7534e000 --- /dev/null +++ b/types/get-value/get-value-tests.ts @@ -0,0 +1,22 @@ +import get = require("get-value"); +const obj = { a: { b: { c: { d: "foo" } } } }; + +get(obj); +get(obj, "a"); +get(obj, "a.b"); +get(obj, "a.b.c"); +get(obj, "a.b.c.d"); + +{ + const isEnumerable = Object.prototype.propertyIsEnumerable; + const options: get.Options = { + isValid: (key, obj) => isEnumerable.call(obj, key) || typeof obj[key] === "string", + }; + + const obj = {}; + Object.defineProperty(obj, 'foo', { value: 'bar', enumerable: false }); + + get(obj, 'foo', options); + get({}, 'hasOwnProperty', options); + get({}, 'constructor', options); +} diff --git a/types/get-value/index.d.ts b/types/get-value/index.d.ts new file mode 100644 index 0000000000..70cf0286e7 --- /dev/null +++ b/types/get-value/index.d.ts @@ -0,0 +1,53 @@ +// Type definitions for get-value 3.0 +// Project: https://github.com/jonschlinkert/get-value +// Definitions by: Daniel Rosenwasser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export = get; + +declare function get(obj: T): T; +declare function get(obj: object, key: string, options?: get.Options): any; + +declare namespace get { + interface Options { + /** + * The default value to return when get-value cannot result a value from the given object. + * + * default: `undefined` + */ + default?: any; + /** + * If defined, this function is called on each resolved value. + * Useful if you want to do `.hasOwnProperty` or `Object.prototype.propertyIsEnumerable`. + */ + isValid?: (key: K, object: Record) => boolean; + /** + * Custom function to use for splitting the string into object path segments. + * + * default: `String.split` + */ + split?: (s: string) => string[]; + /** + * The separator to use for spliting the string. + * (this is probably not needed when `options.split` is used). + * + * default: `"."` + */ + separator?: string | RegExp; + /** + * Customize how the object path is created when iterating over path segments. + * + * default: `Array.join` + */ + join?: (segs: string[]) => string; + /** + * The character to use when re-joining the string to check for keys + * with dots in them (this is probably not needed when `options.join` is used). + * This can be a different value than the separator, since the separator can be a string or regex. + * + * default: `"."` + */ + joinChar?: string; + } +} diff --git a/types/get-value/tsconfig.json b/types/get-value/tsconfig.json new file mode 100644 index 0000000000..33aa3925c5 --- /dev/null +++ b/types/get-value/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "get-value-tests.ts" + ] +} diff --git a/types/get-value/tslint.json b/types/get-value/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/get-value/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ddba7a0d3ad96010611d61e5c81e93da7da03d78 Mon Sep 17 00:00:00 2001 From: Jakub Synowiec Date: Sat, 17 Feb 2018 20:41:59 +0100 Subject: [PATCH 046/128] Fix tslint errors --- types/electron-store/index.d.ts | 207 ++++++++++++++++---------------- 1 file changed, 103 insertions(+), 104 deletions(-) diff --git a/types/electron-store/index.d.ts b/types/electron-store/index.d.ts index 357ec98460..66e579b392 100644 --- a/types/electron-store/index.d.ts +++ b/types/electron-store/index.d.ts @@ -1,113 +1,112 @@ -// Type definitions for electron-store 1.2 +// Type definitions for electron-store 1.3 // Project: https://github.com/sindresorhus/electron-store // Definitions by: Daniel Perez Alvarez // Jakub Synowiec // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + /// -declare module 'electron-store' { - type JSONValue = string | number | boolean | JSONObject | JSONArray; +type JSONValue = string | number | boolean | JSONObject | JSONArray; - interface JSONObject { - [x: string]: JSONValue; - } - - interface JSONArray extends Array {} - - interface ElectronStoreOptions { - /** - * Default data. - */ - defaults?: T; - - /** - * Name of the storage file (without extension). - */ - name?: string; - - /** - * Storage file location. Don't specify this unless absolutely necessary! - */ - cwd?: string; - - /** - * When specified, the store will be encrypted using the aes-256-cbc encryption algorithm. - */ - encryptionKey?: string | Buffer; - } - - class ElectronStore implements Iterable<[keyof T, JSONValue]> { - constructor(options?: ElectronStoreOptions); - - /** - * Set an item. - */ - set(key: K, value: T[K]): void; - set(key: string, value: any): void; - - /** - * Set multiple items at once. - */ - set(object: Pick | T): void; - set(object: JSONObject): void; - - /** - * Get an item or defaultValue if the item does not exist. - */ - get(key: K, defaultValue?: JSONValue): T[K]; - get(key: string, defaultValue?: any): any; - - /** - * Check if an item exists. - */ - has(key: K | string): boolean; - - /** - * Delete an item. - */ - delete(key: K | string): void; - - /** - * Delete all items. - */ - clear(): void; - - /** - * Watches the given key, calling callback on any changes. When a key is first set oldValue - * will be undefined, and when a key is deleted newValue will be undefined. - */ - onDidChange( - key: K, - callback: (newValue: T[K], oldValue: T[K]) => void - ): void; - onDidChange( - key: string, - callback: (newValue: JSONValue, oldValue: JSONValue) => void - ): void; - - /** - * Get the item count. - */ - size: number; - - /** - * Get all the data as an object or replace the current data with an object. - */ - store: T; - - /** - * Get the path to the storage file. - */ - path: string; - - /** - * Open the storage file in the user's editor. - */ - openInEditor(): void; - - [Symbol.iterator](): Iterator<[keyof T, JSONValue]>; - } - - export = ElectronStore; +interface JSONObject { + [x: string]: JSONValue; } + +interface JSONArray extends Array {} + +interface ElectronStoreOptions { + /** + * Default data. + */ + defaults?: T; + + /** + * Name of the storage file (without extension). + */ + name?: string; + + /** + * Storage file location. Don't specify this unless absolutely necessary! + */ + cwd?: string; + + /** + * When specified, the store will be encrypted using the aes-256-cbc encryption algorithm. + */ + encryptionKey?: string | Buffer; +} + +declare class ElectronStore implements Iterable<[string, JSONValue]> { + constructor(options?: ElectronStoreOptions); + + /** + * Set an item. + */ + set(key: K, value: T[K]): void; + set(key: string, value: any): void; + + /** + * Set multiple items at once. + */ + set(object: Pick | T | JSONObject): void; + + /** + * Get an item or defaultValue if the item does not exist. + */ + get(key: K, defaultValue?: JSONValue): T[K]; + get(key: string, defaultValue?: any): any; + + /** + * Check if an item exists. + */ + has(key: keyof T | string): boolean; + + /** + * Delete an item. + */ + delete(key: keyof T | string): void; + + /** + * Delete all items. + */ + clear(): void; + + /** + * Watches the given key, calling callback on any changes. When a key is first set oldValue + * will be undefined, and when a key is deleted newValue will be undefined. + */ + onDidChange( + key: K, + callback: (newValue: T[K], oldValue: T[K]) => void + ): void; + onDidChange( + key: string, + callback: (newValue: JSONValue, oldValue: JSONValue) => void + ): void; + + /** + * Get the item count. + */ + size: number; + + /** + * Get all the data as an object or replace the current data with an object. + */ + store: T; + + /** + * Get the path to the storage file. + */ + path: string; + + /** + * Open the storage file in the user's editor. + */ + openInEditor(): void; + + [Symbol.iterator](): Iterator<[string, JSONValue]>; +} + +export = ElectronStore; From 3437e530d9ed260d2b0a3aab495fe0d91c594ed4 Mon Sep 17 00:00:00 2001 From: Jakub Synowiec Date: Sat, 17 Feb 2018 20:42:17 +0100 Subject: [PATCH 047/128] Add tests for typed store --- types/electron-store/electron-store-tests.ts | 32 ++++++++++++++++---- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/types/electron-store/electron-store-tests.ts b/types/electron-store/electron-store-tests.ts index 61d74d6f18..f27cd6aca3 100644 --- a/types/electron-store/electron-store-tests.ts +++ b/types/electron-store/electron-store-tests.ts @@ -1,20 +1,20 @@ import ElectronStore = require('electron-store'); new ElectronStore({ - defaults: {} + defaults: {} }); new ElectronStore({ - name: 'myConfiguration', - cwd: 'unicorn' + name: 'myConfiguration', + cwd: 'unicorn' }); const electronStore = new ElectronStore(); electronStore.set('foo', 'bar'); electronStore.set({ - foo: 'bar', - foo2: 'bar2' + foo: 'bar', + foo2: 'bar2' }); electronStore.delete('foo'); electronStore.get('foo'); @@ -28,7 +28,27 @@ electronStore.size; electronStore.store; electronStore.store = { - foo: 'bar' + foo: 'bar' }; electronStore.path; + +interface SampleStore { + enabled: boolean; + interval: number; +} + +const typedElectronStore = new ElectronStore({ + defaults: { + enabled: true, + interval: 30000, + }, +}); + +const interval: number = typedElectronStore.get('interval'); +const enabled = false; +typedElectronStore.set('enabled', enabled); +typedElectronStore.set({ + enabled: true, + interval: 10000, +}); From 942e3f71b6a2a72410d971a408095ee235b5b598 Mon Sep 17 00:00:00 2001 From: Edgar Simson Date: Sat, 17 Feb 2018 22:16:28 +0200 Subject: [PATCH 048/128] Use standard lint config, fix lint errors --- types/opentype.js/index.d.ts | 63 ++++++++++----------- types/opentype.js/opentype.js-tests.ts | 76 ++++++++++++------------- types/opentype.js/tslint.json | 78 +------------------------- 3 files changed, 68 insertions(+), 149 deletions(-) diff --git a/types/opentype.js/index.d.ts b/types/opentype.js/index.d.ts index 8dff7e3135..8dc449784d 100644 --- a/types/opentype.js/index.d.ts +++ b/types/opentype.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for opentype.js 0.7.3 +// Type definitions for opentype.js 0.7 // Project: https://github.com/nodebox/opentype.js // Definitions by: Dan Marshall // Edgar Simson @@ -60,15 +60,13 @@ export class Font { y: number | undefined, fontSize: number | undefined, options: RenderOptions | undefined, - callback: { - ( - glyph: Glyph, - x: number, - y: number, - fontSize: number, - options?: RenderOptions - ): void; - } + callback: ( + glyph: Glyph, + x: number, + y: number, + fontSize: number, + options?: RenderOptions + ) => void ): number; getAdvanceWidth( text: string, @@ -115,7 +113,7 @@ export type FontConstructorOptions = FontConstructorOptionsBase & glyphs: Glyph[]; }; -interface FontOptions { +export interface FontOptions { empty?: boolean; familyName: string; styleName: string; @@ -140,7 +138,7 @@ interface FontOptions { fsSelection?: string; } -interface FontConstructorOptionsBase { +export interface FontConstructorOptionsBase { familyName: string; styleName: string; unitsPerEm: number; @@ -148,7 +146,7 @@ interface FontConstructorOptionsBase { descender: number; } -interface FontNames { +export interface FontNames { copyright: LocalizedName; description: LocalizedName; designer: LocalizedName; @@ -165,7 +163,7 @@ interface FontNames { version: LocalizedName; } -interface Table { +export interface Table { [propName: string]: any; encode(): number[]; fields: Field[]; @@ -174,15 +172,15 @@ interface Table { tableName: string; } -interface KerningPairs { +export interface KerningPairs { [pair: string]: number; } -interface LocalizedName { +export interface LocalizedName { [lang: string]: string; } -interface Field { +export interface Field { name: string; type: string; value: any; @@ -201,7 +199,7 @@ export class Glyph { private points; name: string; - path: Path | { (): Path }; + path: Path | (() => Path); unicode: number; unicodes: number[]; advanceWidth: number; @@ -242,7 +240,7 @@ export class Glyph { font?: Font ): Path; } -interface GlyphOptions { +export interface GlyphOptions { advanceWidth?: number; index?: number; font?: Font; @@ -266,13 +264,13 @@ export class GlyphNames { export class GlyphSet { private font; private glyphs; - constructor(font: Font, glyphs: Glyph[] | { (): Glyph }[]); + constructor(font: Font, glyphs: Glyph[] | Array<(() => Glyph)>); get(index: number): Glyph; length: number; - push(index: number, loader: { (): Glyph }): void; + push(index: number, loader: () => Glyph): void; } -interface Post { +export interface Post { glyphNameIndex?: number[]; isFixedPitch: number; italicAngle: number; @@ -288,7 +286,7 @@ interface Post { version: number; } -interface RenderOptions { +export interface RenderOptions { script?: string; language?: string; kerning?: boolean; @@ -310,7 +308,7 @@ export interface Metrics { export interface Contour extends Array {} -interface Point { +export interface Point { lastPointOfContour?: boolean; } @@ -355,7 +353,7 @@ export class Path { unitsPerEm: number; } -interface PathCommand { +export interface PathCommand { type: string; x?: number; y?: number; @@ -369,20 +367,17 @@ interface PathCommand { * UTIL CLASSES ******************************************/ -export class BoundingBox { - // TODO add methods -} +export type BoundingBox = () => any; +// TODO add methods -export class Encoding { +export interface Encoding { charset: string; charToGlyphIndex(c: string): number; font: Font; } -export class Substitution { - constructor(font: Font); - // TODO add methods -} +export type Substitution = (font: Font) => any; +// TODO add methods /****************************************** * STATIC @@ -390,7 +385,7 @@ export class Substitution { export function load( url: string, - callback: { (error: any, font?: Font): void } + callback: (error: any, font?: Font) => void ): void; export function loadSync(url: string): Font; diff --git a/types/opentype.js/opentype.js-tests.ts b/types/opentype.js/opentype.js-tests.ts index 6e1639a1b0..04781d5415 100644 --- a/types/opentype.js/opentype.js-tests.ts +++ b/types/opentype.js/opentype.js-tests.ts @@ -1,60 +1,60 @@ -var x = 0; -var y = 0; -var fontSize = 72; -var ctx: CanvasRenderingContext2D; +const x = 0; +const y = 0; +const fontSize = 72; +let ctx: CanvasRenderingContext2D; -opentype.load('fonts/Roboto-Black.ttf', function(err, font) { +opentype.load('fonts/Roboto-Black.ttf', (err, font) => { if (err) { alert('Font could not be loaded: ' + err); } else { - var path = font.getPath('Hello, World!', 0, 150, 72); + const path = font.getPath('Hello, World!', 0, 150, 72); // If you just want to draw the text you can also use font.draw(ctx, text, x, y, fontSize). path.draw(ctx); } }); -var myBuffer: ArrayBuffer; -var font = opentype.parse(myBuffer); +let myBuffer: ArrayBuffer; +let font = opentype.parse(myBuffer); font = opentype.loadSync('fonts/Roboto-Black.ttf'); -var notdefGlyph = new opentype.Glyph({ +const notdefGlyph = new opentype.Glyph({ name: '.notdef', unicode: 0, advanceWidth: 650, path: new opentype.Path() }); -var aPath = new opentype.Path(); +const aPath = new opentype.Path(); // more drawing instructions... -var aGlyph = new opentype.Glyph({ +const aGlyph = new opentype.Glyph({ name: 'A', unicode: 65, advanceWidth: 650, path: aPath }); -var glyphs = [notdefGlyph, aGlyph]; -var font = new opentype.Font({ +const glyphs = [notdefGlyph, aGlyph]; +const fontGenerated = new opentype.Font({ familyName: 'OpenTypeSans', styleName: 'Medium', unitsPerEm: 1000, ascender: 800, descender: -200, - glyphs: glyphs + glyphs }); font.download(); -var hasChar: boolean = font.hasChar('a'); -var charIndex: number = font.charToGlyphIndex('a'); -var charGlyph: opentype.Glyph = font.charToGlyph('a'); -var charGlyphs: opentype.Glyph[] = font.stringToGlyphs('abc'); -var nameIndex: number = font.nameToGlyphIndex('a'); -var nameGlyph: opentype.Glyph = font.nameToGlyph('a'); -var indexName: string = font.glyphIndexToName(1); -var kerning: number = font.getKerningValue(notdefGlyph, aGlyph); +const hasChar: boolean = font.hasChar('a'); +const charIndex: number = font.charToGlyphIndex('a'); +const charGlyph: opentype.Glyph = font.charToGlyph('a'); +const charGlyphs: opentype.Glyph[] = font.stringToGlyphs('abc'); +const nameIndex: number = font.nameToGlyphIndex('a'); +const nameGlyph: opentype.Glyph = font.nameToGlyph('a'); +const indexName: string = font.glyphIndexToName(1); +const kerning: number = font.getKerningValue(notdefGlyph, aGlyph); font.defaultRenderOptions.kerning = false; -var forEachWidth: number = font.forEachGlyph( +const forEachWidth: number = font.forEachGlyph( 'text', x, y, @@ -71,32 +71,32 @@ var forEachWidth: number = font.forEachGlyph( }); } ); -var fontPath: opentype.Path = font.getPath('text', x, y, fontSize, {}); -var fontPaths: opentype.Path[] = font.getPaths('text', x, y, fontSize, {}); -var fontWidth: number = font.getAdvanceWidth('text', fontSize, { yScale: 0.5 }); +const fontPath: opentype.Path = font.getPath('text', x, y, fontSize, {}); +const fontPaths: opentype.Path[] = font.getPaths('text', x, y, fontSize, {}); +const fontWidth: number = font.getAdvanceWidth('text', fontSize, { yScale: 0.5 }); font.draw(ctx, 'text'); font.drawPoints(ctx, 'text', x, y, fontSize, { yScale: 0.5 }); font.drawMetrics(ctx, 'text', x, y, fontSize, { xScale: 1.1, yScale: 0.5 }); -var engName: string = font.getEnglishName('a'); +const engName: string = font.getEnglishName('a'); font.validate(); -var tables: opentype.Table = font.toTables(); -var ab: ArrayBuffer = font.toArrayBuffer(); +const tables: opentype.Table = font.toTables(); +const ab: ArrayBuffer = font.toArrayBuffer(); font.download(); font.download('fileName.ttf'); aGlyph.bindConstructorValues({ advanceWidth: 1 }); aGlyph.addUnicode(42); -var glyphBBox: opentype.BoundingBox = aGlyph.getBoundingBox(); -var glyphPathBasic: opentype.Path = aGlyph.getPath(); -var glyphPathFull: opentype.Path = aGlyph.getPath( +const glyphBBox: opentype.BoundingBox = aGlyph.getBoundingBox(); +const glyphPathBasic: opentype.Path = aGlyph.getPath(); +const glyphPathFull: opentype.Path = aGlyph.getPath( x, y, fontSize, { xScale: 1, yScale: 2 }, font ); -var glyphContours: opentype.Contour = aGlyph.getContours(); -var glyphMetrics: opentype.Metrics = aGlyph.getMetrics(); +const glyphContours: opentype.Contour = aGlyph.getContours(); +const glyphMetrics: opentype.Metrics = aGlyph.getMetrics(); aGlyph.draw(ctx, x, y, fontSize, {}); aGlyph.drawPoints(ctx, x, y, fontSize); aGlyph.drawMetrics(ctx, x, y, fontSize); @@ -112,8 +112,8 @@ aPath.closePath(); aPath.extend(aPath); aPath.extend(aPath.commands); aPath.extend(aPath.getBoundingBox()); -var pathBBox: opentype.BoundingBox = aPath.getBoundingBox(); +const pathBBox: opentype.BoundingBox = aPath.getBoundingBox(); aPath.draw(ctx); -var pathData: string = aPath.toPathData(7); -var pathSvg: string = aPath.toSVG(7); -var pathDom: SVGPathElement = aPath.toDOMElement(7); +const pathData: string = aPath.toPathData(7); +const pathSvg: string = aPath.toSVG(7); +const pathDom: SVGPathElement = aPath.toDOMElement(7); diff --git a/types/opentype.js/tslint.json b/types/opentype.js/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/opentype.js/tslint.json +++ b/types/opentype.js/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } From 699778708558e79438071272958c572480b97693 Mon Sep 17 00:00:00 2001 From: Umoxfo Date: Sun, 18 Feb 2018 12:05:04 -0800 Subject: [PATCH 049/128] Add support for vnu-jar --- types/vnu-jar/index.d.ts | 8 ++++++++ types/vnu-jar/tsconfig.json | 24 ++++++++++++++++++++++++ types/vnu-jar/tslint.json | 1 + types/vnu-jar/vnu-jar-tests.ts | 15 +++++++++++++++ 4 files changed, 48 insertions(+) create mode 100644 types/vnu-jar/index.d.ts create mode 100644 types/vnu-jar/tsconfig.json create mode 100644 types/vnu-jar/tslint.json create mode 100644 types/vnu-jar/vnu-jar-tests.ts diff --git a/types/vnu-jar/index.d.ts b/types/vnu-jar/index.d.ts new file mode 100644 index 0000000000..2e2e2a1ac9 --- /dev/null +++ b/types/vnu-jar/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for vnu-jar 17.11 +// Project: https://github.com/validator/validator#readme +// Definitions by: Umoxfo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = vnu_jar; + +declare const vnu_jar: string; diff --git a/types/vnu-jar/tsconfig.json b/types/vnu-jar/tsconfig.json new file mode 100644 index 0000000000..8468e98846 --- /dev/null +++ b/types/vnu-jar/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "vnu-jar-tests.ts" + ] +} diff --git a/types/vnu-jar/tslint.json b/types/vnu-jar/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/vnu-jar/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/vnu-jar/vnu-jar-tests.ts b/types/vnu-jar/vnu-jar-tests.ts new file mode 100644 index 0000000000..776ccd9d4a --- /dev/null +++ b/types/vnu-jar/vnu-jar-tests.ts @@ -0,0 +1,15 @@ +// Imported from: https://github.com/soywiz/typescript-node-definitions/d.ts + +/// + +import { exec } from "child_process"; +import vnu = require("vnu-jar"); + +exec(`java -jar ${vnu} --version`, (error, stdout) => { + if (error) { + console.error(`exec error: ${error}`); + return; + } + + console.log(stdout); +}); From 953de5068d34098f137ee05a65ec038cfdab8d4d Mon Sep 17 00:00:00 2001 From: Jonathan Siebern Date: Mon, 19 Feb 2018 16:07:17 +0100 Subject: [PATCH 050/128] Revert Version --- types/luxon/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 2275e331f0..0d66b9750c 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for luxon 0.4.0 +// Type definitions for luxon 0.2 // Project: https://github.com/moment/luxon#readme // Definitions by: Colby DeHart // Hyeonseok Yang From 3e54d1924efd893231ab7db8362a69d40eafa069 Mon Sep 17 00:00:00 2001 From: Derek Wickern Date: Mon, 19 Feb 2018 10:39:28 -0800 Subject: [PATCH 051/128] ember-data: improve snapshot typings and add test --- types/ember-data/index.d.ts | 64 +++++++++++++++++------------ types/ember-data/test/serializer.ts | 56 +++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 27 deletions(-) diff --git a/types/ember-data/index.d.ts b/types/ember-data/index.d.ts index e3917b1a8b..2a2fdab7bd 100644 --- a/types/ember-data/index.d.ts +++ b/types/ember-data/index.d.ts @@ -13,6 +13,32 @@ declare module 'ember-data' { export interface ModelRegistry {} export interface AdapterRegistry {} export interface SerializerRegistry {} + export interface TransformRegistry { + 'string': string; + 'boolean': boolean; + 'number': number; + 'date': Date; + } + + type AttributesFor = keyof Model; // TODO: filter to attr properties only (TS 2.8) + type RelationshipsFor = keyof Model; // TODO: filter to hasMany/belongsTo properties only (TS 2.8) + + interface AttributeMeta { + type: keyof TransformRegistry; + options: object; + name: AttributesFor; + parentType: Model; + isAttribute: true; + } + interface RelationshipMeta { + key: RelationshipsFor; + kind: 'belongsTo' | 'hasMany'; + type: keyof ModelRegistry; + options: object; + name: string; + parentType: Model; + isRelationship: true; + } namespace DS { /** @@ -82,27 +108,11 @@ declare module 'ember-data' { * `boolean` and `date`. You can define your own transforms by subclassing * [DS.Transform](/api/data/classes/DS.Transform.html). */ - function attr( - type: 'string', - options?: AttrOptions - ): Ember.ComputedProperty; - function attr( - type: 'boolean', - options?: AttrOptions - ): Ember.ComputedProperty; - function attr( - type: 'number', - options?: AttrOptions - ): Ember.ComputedProperty; - function attr( - type: 'date', - options?: AttrOptions - ): Ember.ComputedProperty; - function attr( - type: string, - options?: AttrOptions - ): Ember.ComputedProperty; - function attr(options?: AttrOptions): Ember.ComputedProperty; + function attr( + type: K, + options?: AttrOptions + ): Ember.ComputedProperty; + function attr(options?: AttrOptions): Ember.ComputedProperty; /** * WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 * ## Using BuildURLMixin @@ -942,7 +952,7 @@ declare module 'ember-data' { /** * Returns the value of an attribute. */ - attr(keyName: L): ModelRegistry[K][L]; + attr>(keyName: L): ModelRegistry[K][L]; /** * Returns all attributes and their corresponding values. */ @@ -954,18 +964,18 @@ declare module 'ember-data' { /** * Returns the current value of a belongsTo relationship. */ - belongsTo( + belongsTo>( keyName: L, options?: {} ): Snapshot['record'][L] | string | null | undefined; /** * Returns the current value of a hasMany relationship. */ - hasMany( + hasMany>( keyName: L, options?: { ids: false } ): Array['record'][L]> | undefined; - hasMany( + hasMany>( keyName: L, options: { ids: true } ): string[] | undefined; @@ -973,12 +983,12 @@ declare module 'ember-data' { * Iterates through all the attributes of the model, calling the passed * function on each attribute. */ - eachAttribute(callback: Function, binding: {}): any; + eachAttribute(callback: (key: keyof M, meta: AttributeMeta) => void, binding?: {}): any; /** * Iterates through all the relationships of the model, calling the passed * function on each relationship. */ - eachRelationship(callback: Function, binding: {}): any; + eachRelationship(callback: (key: keyof M, meta: RelationshipMeta) => void, binding?: {}): any; /** * Serializes the snapshot using the serializer for the model. */ diff --git a/types/ember-data/test/serializer.ts b/types/ember-data/test/serializer.ts index baaa65ae9e..b694b38b89 100644 --- a/types/ember-data/test/serializer.ts +++ b/types/ember-data/test/serializer.ts @@ -37,3 +37,59 @@ const EmbeddedRecordMixin = DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, { } } }); + +class Message extends DS.Model.extend({ + title: DS.attr(), + body: DS.attr(), + + author: DS.belongsTo('user'), + comments: DS.belongsTo('comment') +}) {} + +declare module 'ember-data' { + interface ModelRegistry { + 'message-for-serializer': Message; + } +} + +interface CustomSerializerOptions { + includeId: boolean; +} + +const SerializerUsingSnapshots = DS.RESTSerializer.extend({ + serialize(snapshot: DS.Snapshot<'message-for-serializer'>, options: CustomSerializerOptions) { + let json: any = { + POST_TTL: snapshot.attr('title'), + POST_BDY: snapshot.attr('body'), + POST_CMS: snapshot.hasMany('comments', { ids: true }) + }; + + if (options.includeId) { + json.POST_ID_ = snapshot.id; + } + + return json; + } +}); + +DS.Serializer.extend({ + serialize(snapshot: DS.Snapshot<'message-for-serializer'>, options: {}) { + let json: any = { + id: snapshot.id + }; + + snapshot.eachAttribute((key, attribute) => { + json[key] = snapshot.attr(key); + }); + + snapshot.eachRelationship((key, relationship) => { + if (relationship.kind === 'belongsTo') { + json[key] = snapshot.belongsTo(key, { id: true }); + } else if (relationship.kind === 'hasMany') { + json[key] = snapshot.hasMany(key, { ids: true }); + } + }); + + return json; + }, +}); From 38a16c7ac7a23708e5bcb0b40239ccf08ac136bb Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 20 Feb 2018 08:34:40 -0800 Subject: [PATCH 052/128] bull: Remove duplicate getWaiting definition (#23715) --- types/bull/index.d.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index 8a12db0fd7..a7a9ea350b 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -456,11 +456,6 @@ declare namespace Bull { */ getFailed(start?: number, end?: number): Promise; - /** - * Returns a promise that will return an array with the waiting jobs between start and end. - */ - getWaiting(start?: number, end?: number): Promise; - /** * Returns JobInformation of repeatable jobs (ordered descending). Provide a start and/or an end * index to limit the number of results. Start defaults to 0, end to -1 and asc to false. From 38c8148560c717b8270b65de8d5d49f79b4a15df Mon Sep 17 00:00:00 2001 From: Andrew Goodale Date: Tue, 20 Feb 2018 13:19:34 -0500 Subject: [PATCH 053/128] Add `onScrollToIndexFailed` prop for `VirtualizedList` --- types/react-native/index.d.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 656b1c2e0d..395ce9af45 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -3909,6 +3909,17 @@ export interface VirtualizedListProperties extends ScrollViewProperties { */ onRefresh?: (() => void) | null; + /** + * Used to handle failures when scrolling to an index that has not been measured yet. + * Recommended action is to either compute your own offset and `scrollTo` it, or scroll as far + * as possible and then try again after more items have been rendered. + */ + onScrollToIndexFailed?: (info: { + index: number, + highestMeasuredFrameIndex: number, + averageItemLength: number + }) => void; + /** * Called when the viewability of rows changes, as defined by the * `viewabilityConfig` prop. From 39d94c080d6c3002fa78313a9ca55bbe42246010 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 20 Feb 2018 12:39:00 -0800 Subject: [PATCH 054/128] Make `import { fabric } from "fabric";` work (2) (#23787) --- types/fabric/fabric-impl.d.ts | 4428 +++++++++++++++++ types/fabric/index.d.ts | 4427 +--------------- types/fabric/test/import.ts | 2 + .../fabric/{fabric-tests.ts => test/index.ts} | 0 types/fabric/tsconfig.json | 3 +- 5 files changed, 4433 insertions(+), 4427 deletions(-) create mode 100644 types/fabric/fabric-impl.d.ts create mode 100644 types/fabric/test/import.ts rename types/fabric/{fabric-tests.ts => test/index.ts} (100%) diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts new file mode 100644 index 0000000000..f2570b9542 --- /dev/null +++ b/types/fabric/fabric-impl.d.ts @@ -0,0 +1,4428 @@ +// This module does not really exist. +// This is just to get `export as namespace fabric;` to work and to be re-exportable from `index.d.ts`. + +export as namespace fabric; + +export const isLikelyNode: boolean; +export const isTouchSupported: boolean; + +///////////////////////////////////////////////////////////// +// farbic Functions +///////////////////////////////////////////////////////////// + +export function createCanvasForNode(width: number, height: number): Canvas; + +// Parse +// ---------------------------------------------------------- +/** + * Creates markup containing SVG referenced elements like patterns, gradients etc. + * @param canvas instance of fabric.Canvas + */ +export function createSVGRefElementsMarkup(canvas: StaticCanvas): string; +/** + * Creates markup containing SVG font faces + * @param objects Array of fabric objects + */ +export function createSVGFontFacesMarkup(objects: Object[]): string; +/** + * Takes string corresponding to an SVG document, and parses it into a set of fabric objects + * @param [reviver] Method for further parsing of SVG elements, called after each fabric object created. + */ +export function loadSVGFromString(string: string, callback: (results: Object[], options: any) => void, reviver?: Function): void; +/** + * Takes url corresponding to an SVG document, and parses it into a set of fabric objects. + * Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy) + * @param [reviver] Method for further parsing of SVG elements, called after each fabric object created. + */ +export function loadSVGFromURL(url: string, callback: (results: Object[], options: any) => void, reviver?: Function): void; +/** + * Returns CSS rules for a given SVG document + * @param doc SVG document to parse + */ +export function getCSSRules(doc: SVGElement): any; + +export function parseElements(elements: any[], callback: Function, options: any, reviver?: Function): void; +/** + * Parses "points" attribute, returning an array of values + * @param points points attribute string + */ +export function parsePointsAttribute(points: string): any[]; +/** + * Parses "style" attribute, retuning an object with values + * @param element Element to parse + */ +export function parseStyleAttribute(element: SVGElement): any; +/** + * Transforms an array of svg elements to corresponding fabric.* instances + * @param elements Array of elements to parse + * @param callback Being passed an array of fabric instances (transformed from SVG elements) + * @param [options] Options object + * @param [reviver] Method for further parsing of SVG elements, called after each fabric object created. + */ +export function parseElements(elements: SVGElement[], callback: Function, options?: any, reviver?: Function): void; +/** + * Returns an object of attributes' name/value, given element and an array of attribute names; + * Parses parent "g" nodes recursively upwards. + * @param element Element to parse + * @param attributes Array of attributes to parse + */ +export function parseAttributes(element: HTMLElement, attributes: string[], svgUid?: string): { [key: string]: string }; +/** + * Parses an SVG document, returning all of the gradient declarations found in it + * @param doc SVG document to parse + */ +export function getGradientDefs(doc: SVGElement): { [key: string]: any }; +/** + * Parses a short font declaration, building adding its properties to a style object + * @param value font declaration + * @param oStyle definition + */ +export function parseFontDeclaration(value: string, oStyle: any): void; +/** + * Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback + * @param doc SVG document to parse + * @param callback Callback to call when parsing is finished; It's being passed an array of elements (parsed from a document). + * @param [reviver] Method for further parsing of SVG elements, called after each fabric object created. + */ +export function parseSVGDocument(doc: SVGElement, callback: (results: Object[], options: any) => void, reviver?: Function): void; +/** + * Parses "transform" attribute, returning an array of values + * @param attributeValue String containing attribute value + */ +export function parseTransformAttribute(attributeValue: string): number[]; + +// fabric Log +// --------------- +/** + * Wrapper around `console.log` (when available) + */ +export function log(...values: any[]): void; +/** + * Wrapper around `console.warn` (when available) + */ +export function warn(...values: any[]): void; + +/////////////////////////////////////////////////////////////////////////////// +// Data Object Interfaces - These intrface are not specific part of fabric, +// They are just helpful for for defining function paramters +////////////////////////////////////////////////////////////////////////////// +interface IDataURLOptions { + /** + * The format of the output image. Either "jpeg" or "png" + */ + format?: string; + /** + * Quality level (0..1). Only used for jpeg + */ + quality?: number; + /** + * Multiplier to scale by + */ + multiplier?: number; + /** + * Cropping left offset. Introduced in v1.2.14 + */ + left?: number; + /** + * Cropping top offset. Introduced in v1.2.14 + */ + top?: number; + /** + * Cropping width. Introduced in v1.2.14 + */ + width?: number; + /** + * Cropping height. Introduced in v1.2.14 + */ + height?: number; +} + +interface IEvent { + e: Event; + target?: Object; +} + +interface IFillOptions { + /** + * options.source Pattern source + */ + source: string | HTMLImageElement; + /** + * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat) + */ + repeat?: string; + /** + * Pattern horizontal offset from object's left/top corner + */ + offsetX?: number; + /** + * Pattern vertical offset from object's left/top corner + */ + offsetY?: number; +} + +interface IToSVGOptions { + /** + * If true xml tag is not included + */ + suppressPreamble: boolean; + /** + * SVG viewbox object + */ + viewBox: IViewBox; + /** + * Encoding of SVG output + */ + encoding: string; +} + +interface IViewBox { + /** + * x-cooridnate of viewbox + */ + x: number; + /** + * y-coordinate of viewbox + */ + y: number; + /** + * Width of viewbox + */ + width: number; + /** + * Height of viewbox + */ + height: number; +} + +/////////////////////////////////////////////////////////////////////////////// +// Mixins Interfaces +////////////////////////////////////////////////////////////////////////////// +interface ICollection { + /** + * Adds objects to collection, then renders canvas (if `renderOnAddRemove` is not `false`) + * Objects should be instances of (or inherit from) fabric.Object + * @param object Zero or more fabric instances + */ + add(...object: Object[]): T; + + /** + * Inserts an object into collection at specified index, then renders canvas (if `renderOnAddRemove` is not `false`) + * An object should be an instance of (or inherit from) fabric.Object + * @param object Object to insert + * @param index Index to insert object at + * @param nonSplicing When `true`, no splicing (shifting) of objects occurs + * @return thisArg + * @chainable + */ + insertAt(object: Object, index: number, nonSplicing: boolean): T; + + /** + * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`) + * @param object Zero or more fabric instances + * @return thisArg + * @chainable + */ + remove(...object: Object[]): T; + + /** + * Executes given function for each object in this group + * @param context Context (aka thisObject) + * @return thisArg + */ + forEachObject(callback: (element: Object, index: number, array: Object[]) => void, context?: any): T; + + /** + * Returns an array of children objects of this instance + * Type parameter introduced in 1.3.10 + * @param [type] When specified, only objects of this type are returned + */ + getObjects(type?: string): Object[]; + + /** + * Returns object at specified index + * @return thisArg + */ + item(index: number): T; + + /** + * Returns true if collection contains no objects + * @return true if collection is empty + */ + isEmpty(): boolean; + + /** + * Returns a size of a collection (i.e: length of an array containing its objects) + * @return Collection size + */ + size(): number; + + /** + * Returns true if collection contains an object + * @param object Object to check against + * @return `true` if collection contains an object + */ + contains(object: Object): boolean; + + /** + * Returns number representation of a collection complexity + * @return complexity + */ + complexity(): number; +} + +interface IObservable { + /** + * Observes specified event + * @param eventName Event name (eg. 'after:render') + * @param handler Function that receives a notification when an event of the specified type occurs + */ + on(eventName: string, handler: (e: IEvent) => void): T; + + /** + * Observes specified event + * @param eventName Object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) + */ + on(events: {[eventName: string]: (e: IEvent) => void}): T; + /** + * Fires event with an optional options object + * @param eventName Event name to fire + * @param [options] Options object + */ + trigger(eventName: string, options?: any): T; + /** + * Stops event observing for a particular event handler. Calling this method + * without arguments removes all handlers for all events + * @param eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) + * @param handler Function to be deleted from EventListeners + */ + off(eventName?: string|any, handler?: (e: IEvent) => void): T; +} + +interface Callbacks { + /** Invoked on completion */ + onComplete?: Function; + /** Invoked on every step of animation */ + onChange?: Function; +} + +// animation mixin +// ---------------------------------------------------- +interface ICanvasAnimation { + FX_DURATION: number; + /** + * Centers object horizontally with animation. + * @param object Object to center + */ + fxCenterObjectH(object: Object, callbacks?: Callbacks): T; + + /** + * Centers object vertically with animation. + * @param object Object to center + */ + fxCenterObjectV(object: Object, callbacks?: Callbacks): T; + + /** + * Same as `fabric.Canvas#remove` but animated + * @param object Object to remove + * @chainable + */ + fxRemove(object: Object): T; +} +interface IObjectAnimation { + /** + * Animates object's properties + * object.animate('left', ..., {duration: ...}); + * @param property Property to animate + * @param value Value to animate property + * @param options The animation options + */ + animate(property: string, value: number|string, options?: IAnimationOptions): Object; + /** + * Animates object's properties + * object.animate({ left: ..., top: ... }, { duration: ... }); + * @param properties Properties to animate + * @param value Options object + */ + animate(properties: any, options?: IAnimationOptions): Object; +} +interface IAnimationOptions { + /** + * Allows to specify starting value of animatable property (if we don't want current value to be used). + */ + from?: string|number; + /** + * Defaults to 500 (ms). Can be used to change duration of an animation. + */ + duration?: number; + /** + * Callback; invoked on every value change + */ + onChange?: Function; + /** + * Callback; invoked when value change is completed + */ + onComplete?: Function; + + /** + * Easing function. Default: fabric.util.ease.easeInSine + */ + easing?: Function; + /** + * Value to modify the property by, default: end - start + */ + by?: number; +} + +/////////////////////////////////////////////////////////////////////////////// +// General Fabric Interfaces +////////////////////////////////////////////////////////////////////////////// +export class Color { + /** + * Color class + * The purpose of Color is to abstract and encapsulate common color operations; + * @param color optional in hex or rgb(a) format + */ + constructor(color?: string); + + /** + * Returns source of this color (where source is an array representation; ex: [200, 200, 100, 1]) + */ + getSource(): number[]; + + /** + * Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1]) + */ + setSource(source: number[]): void; + + /** + * Returns color represenation in RGB format ex: rgb(0-255,0-255,0-255) + */ + toRgb(): string; + + /** + * Returns color represenation in RGBA format ex: rgba(0-255,0-255,0-255,0-1) + */ + toRgba(): string; + + /** + * Returns color represenation in HSL format ex: hsl(0-360,0%-100%,0%-100%) + */ + toHsl(): string; + + /** + * Returns color represenation in HSLA format ex: hsla(0-360,0%-100%,0%-100%,0-1) + */ + toHsla(): string; + + /** + * Returns color represenation in HEX format ex: FF5555 + */ + toHex(): string; + + /** + * Gets value of alpha channel for this color + */ + getAlpha(): number; + + /** + * Sets value of alpha channel for this color + * @param alpha Alpha value 0-1 + */ + setAlpha(alpha: number): void; + + /** + * Transforms color to its grayscale representation + */ + toGrayscale(): Color; + + /** + * Transforms color to its black and white representation + */ + toBlackWhite(threshold: number): Color; + /** + * Overlays color with another color + */ + overlayWith(otherColor: string|Color): Color; + + /** + * Returns new color object, when given a color in RGB format + * @param color Color value ex: rgb(0-255,0-255,0-255) + */ + static fromRgb(color: string): Color; + /** + * Returns new color object, when given a color in RGBA format + * @param color Color value ex: rgb(0-255,0-255,0-255) + */ + static fromRgba(color: string): Color; + /** + * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in RGB or RGBA format + * @param color Color value ex: rgb(0-255,0-255,0-255), rgb(0%-100%,0%-100%,0%-100%) + */ + static sourceFromRgb(color: string): number[]; + /** + * Returns new color object, when given a color in HSL format + * @param color Color value ex: hsl(0-260,0%-100%,0%-100%) + */ + static fromHsl(color: string): Color; + /** + * Returns new color object, when given a color in HSLA format + * @param color Color value ex: hsl(0-260,0%-100%,0%-100%) + */ + static fromHsla(color: string): Color; + /** + * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HSL or HSLA format. + * @param color Color value ex: hsl(0-360,0%-100%,0%-100%) or hsla(0-360,0%-100%,0%-100%, 0-1) + */ + static sourceFromHsl(color: string): number[]; + /** + * Returns new color object, when given a color in HEX format + * @param color Color value ex: FF5555 + */ + static fromHex(color: string): Color; + + /** + * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HEX format + * @param color ex: FF5555 + */ + static sourceFromHex(color: string): number[]; + /** + * Returns new color object, when given color in array representation (ex: [200, 100, 100, 0.5]) + */ + static fromSource(source: number[]): Color; +} + +interface IGradientOptions { + /** + * @param [options.type] Type of gradient 'radial' or 'linear' + */ + type?: string; + /** + * x-coordinate of start point + */ + x1?: number; + /** + * y-coordinate of start point + */ + y1?: number; + /** + * x-coordinate of end point + */ + x2?: number; + /** + * y-coordinate of end point + */ + y2?: number; + /** + * Radius of start point (only for radial gradients) + */ + r1?: number; + /** + * Radius of end point (only for radial gradients) + */ + r2?: number; + /** + * Color stops object eg. {0:string; 1:string; + */ + colorStops?: any; +} +interface IGradient extends IGradientOptions { + /** + * Adds another colorStop + * @param colorStop Object with offset and color + */ + addColorStop(colorStop: any): IGradient; + /** + * Returns object representation of a gradient + */ + toObject(): any; + /** + * Returns SVG representation of an gradient + * @param object Object to create a gradient for + * @param normalize Whether coords should be normalized + * @return SVG representation of an gradient (linear/radial) + */ + toSVG(object: Object, normalize?: boolean): string; + + /** + * Returns an instance of CanvasGradient + * @param ctx Context to render on + */ + toLive(ctx: CanvasRenderingContext2D, object?: PathGroup): CanvasGradient; +} +interface IGrandientStatic { + new (options?: IGradientOptions): IGradient; + /** + * Returns instance from an SVG element + * @param el SVG gradient element + */ + fromElement(el: SVGGradientElement, instance: Object): IGradient; + /** + * Returns instance from its object representation + * @param [options] Options object + */ + fromObject(obj: any, options: any[]): IGradient; +} + +export class Intersection { + constructor(status?: string); + + /** + * Appends a point to intersection + */ + appendPoint(point: Point): void; + /** + * Appends points to intersection + */ + appendPoints(points: Point[]): void; + + /** + * Checks if polygon intersects another polygon + */ + static intersectPolygonPolygon(points1: Point[], points2: Point[]): Intersection; + /** + * Checks if line intersects polygon + */ + static intersectLinePolygon(a1: Point, a2: Point, points: Point[]): Intersection; + /** + * Checks if one line intersects another + */ + static intersectLineLine(a1: Point, a2: Point, b1: Point, b2: Point): Intersection; + /** + * Checks if polygon intersects rectangle + */ + static intersectPolygonRectangle(points: Point[], r1: number, r2: number): Intersection; +} + +interface IPatternOptions { + /** + * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat) + */ + repeat: string; + + /** + * Pattern horizontal offset from object's left/top corner + */ + offsetX: number; + + /** + * Pattern vertical offset from object's left/top corner + */ + offsetY: number; + /** + * The source for the pattern + */ + source: string|HTMLImageElement; +} +export interface Pattern extends IPatternOptions {} +export class Pattern { + constructor(options?: IPatternOptions); + + initialise(options?: IPatternOptions): Pattern; + /** + * Returns an instance of CanvasPattern + */ + toLive(ctx: CanvasRenderingContext2D): Pattern; + + /** + * Returns object representation of a pattern + */ + toObject(): any; + /** + * Returns SVG representation of a pattern + */ + toSVG(object: Object): string; +} + +export class Point { + x: number; + y: number; + + constructor(x: number, y: number); + + /** + * Adds another point to this one and returns another one + */ + add(that: Point): Point; + + /** + * Adds another point to this one + */ + addEquals(that: Point): Point; + + /** + * Adds value to this point and returns a new one + */ + scalarAdd(scalar: number): Point; + + /** + * Adds value to this point + */ + scalarAddEquals(scalar: number): Point; + + /** + * Subtracts another point from this point and returns a new one + */ + subtract(that: Point): Point; + + /** + * Subtracts another point from this point + */ + subtractEquals(that: Point): Point; + + /** + * Subtracts value from this point and returns a new one + */ + scalarSubtract(scalar: number): Point; + + /** + * Subtracts value from this point + */ + scalarSubtractEquals(scalar: number): Point; + + /** + * Miltiplies this point by a value and returns a new one + */ + multiply(scalar: number): Point; + + /** + * Miltiplies this point by a value + */ + multiplyEquals(scalar: number): Point; + + /** + * Divides this point by a value and returns a new one + */ + divide(scalar: number): Point; + + /** + * Divides this point by a value + */ + divideEquals(scalar: number): Point; + + /** + * Returns true if this point is equal to another one + */ + eq(that: Point): Point; + + /** + * Returns true if this point is less than another one + */ + lt(that: Point): Point; + + /** + * Returns true if this point is less than or equal to another one + */ + lte(that: Point): Point; + + /** + * Returns true if this point is greater another one + */ + gt(that: Point): Point; + + /** + * Returns true if this point is greater than or equal to another one + */ + gte(that: Point): Point; + + /** + * Returns new point which is the result of linear interpolation with this one and another one + */ + lerp(that: Point, t: number): Point; + + /** + * Returns distance from this point and another one + */ + distanceFrom(that: Point): number; + + /** + * Returns the point between this point and another one + */ + midPointFrom(that: Point): Point; + + /** + * Returns a new point which is the min of this and another one + */ + min(that: Point): Point; + + /** + * Returns a new point which is the max of this and another one + */ + max(that: Point): Point; + + /** + * Returns string representation of this point + */ + toString(): string; + + /** + * Sets x/y of this point + */ + setXY(x: number, y: number): Point; + + /** + * Sets x/y of this point from another point + */ + setFromPoint(that: Point): Point; + + /** + * Swaps x/y of this point and another point + */ + swap(that: Point): Point; +} + +interface IShadowOptions { + /** + * Whether the shadow should affect stroke operations + */ + affectStrike: boolean; + /** + * Shadow blur + */ + blur: number; + /** + * Shadow color + */ + color: string; + /** + * Indicates whether toObject should include default values + */ + includeDefaultValues: boolean; + /** + * Shadow horizontal offset + */ + offsetX: number; + /** + * Shadow vertical offset + */ + offsetY: number; +} +export interface Shadow extends IShadowOptions {} +export class Shadow { + constructor(options?: IShadowOptions); + initialize(options?: IShadowOptions|string): Shadow; + /** + * Returns object representation of a shadow + */ + toObject(): any; + /** + * Returns a string representation of an instance, CSS3 text-shadow declaration + */ + toString(): string; + /** + * Returns SVG representation of a shadow + */ + toSVG(object: Object): string; + + /** + * Regex matching shadow offsetX, offsetY and blur, Static + */ + reOffsetsAndBlur: RegExp; + + static reOffsetsAndBlur: RegExp; +} + +/////////////////////////////////////////////////////////////////////////////// +// Canvas Interfaces +////////////////////////////////////////////////////////////////////////////// +interface ICanvasDimensions { + /** + * Width of canvas element + */ + width: number; + /** + * Height of canvas element + */ + height: number; +} +interface ICanvasDimensionsOptions { + /** + * Set the given dimensions only as canvas backstore dimensions + */ + backstoreOnly?: boolean; + /** + * Set the given dimensions only as css dimensions + */ + cssOnly?: boolean; +} + +interface IStaticCanvasOptions { + /** + * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas + */ + allowTouchScrolling?: boolean; + /** + * Indicates whether this canvas will use image smoothing, this is on by default in browsers + */ + imageSmoothingEnabled?: boolean; + + /** + * Indicates whether objects should remain in current stack position when selected. + * When false objects are brought to top and rendered as part of the selection group + */ + preserveObjectStacking?: boolean; + + /** + * The transformation (in the format of Canvas transform) which focuses the viewport + */ + viewportTransform?: number[]; + + freeDrawingColor?: string; + freeDrawingLineWidth?: number; + + /** + * Background color of canvas instance. + * Should be set via setBackgroundColor + */ + backgroundColor?: string|Pattern; + /** + * Background image of canvas instance. + * Should be set via setBackgroundImage + * Backwards incompatibility note: The "backgroundImageOpacity" and "backgroundImageStretch" properties are deprecated since 1.3.9. + */ + backgroundImage?: Image | string; + backgroundImageOpacity?: number; + backgroundImageStretch?: number; + /** + * Function that determines clipping of entire canvas area + * Being passed context as first argument. See clipping canvas area + */ + clipTo?(context: CanvasRenderingContext2D): void; + + /** + * Indicates whether object controls (borders/controls) are rendered above overlay image + */ + controlsAboveOverlay?: boolean; + + /** + * Indicates whether toObject/toDatalessObject should include default values + */ + includeDefaultValues?: boolean; + /** + * Overlay color of canvas instance. + * Should be set via setOverlayColor + */ + overlayColor?: string|Pattern; + /** + * Overlay image of canvas instance. + * Should be set via setOverlayImage + * Backwards incompatibility note: The "overlayImageLeft" and "overlayImageTop" properties are deprecated since 1.3.9. + */ + overlayImage?: Image; + overlayImageLeft?: number; + overlayImageTop?: number; + /** + * Indicates whether add, insertAt and remove should also re-render canvas. + * Disabling this option could give a great performance boost when adding/removing a lot of objects to/from canvas at once + * (followed by a manual rendering after addition/deletion) + */ + renderOnAddRemove?: boolean; + /** + * Indicates whether objects' state should be saved + */ + stateful?: boolean; +} +export interface StaticCanvas extends IObservable, IStaticCanvasOptions, ICollection, ICanvasAnimation {} +export class StaticCanvas { + /** + * Constructor + * @param element element to initialize instance on + * @param [options] Options object + */ + constructor(element: HTMLCanvasElement|string, options?: ICanvasOptions); + + /** + * Calculates canvas element offset relative to the document + * This method is also attached as "resize" event handler of window + */ + calcOffset(): this; + + /** + * Sets {@link fabric.StaticCanvas#overlayImage|overlay image} for this canvas + * @param image fabric.Image instance or URL of an image to set overlay to + * @param callback callback to invoke when image is loaded and set as an overlay + * @param [options] Optional options to set for the {@link fabric.Image|overlay image}. + */ + setOverlayImage(image: Image|string, callback: (img: HTMLImageElement) => void, options?: IImageOptions): this; + + /** + * Sets {@link fabric.StaticCanvas#backgroundImage|background image} for this canvas + * @param image fabric.Image instance or URL of an image to set background to + * @param callback Callback to invoke when image is loaded and set as background + * @param [options] Optional options to set for the {@link fabric.Image|background image}. + */ + setBackgroundImage(image: Image|string, callback?: (img: HTMLImageElement) => void, options?: IImageOptions): this; + + /** + * Sets {@link fabric.StaticCanvas#overlayColor|background color} for this canvas + * @param overlayColor Color or pattern to set background color to + * @param callback Callback to invoke when background color is set + */ + setOverlayColor(overlayColor: string|Pattern, callback: (pattern: Pattern | undefined) => void): this; + + /** + * Sets {@link fabric.StaticCanvas#backgroundColor|background color} for this canvas + * @param backgroundColor Color or pattern to set background color to + * @param callback Callback to invoke when background color is set + */ + setBackgroundColor(backgroundColor: string|Pattern, callback: (pattern: Pattern | undefined) => void): StaticCanvas; + + /** + * Returns canvas width (in px) + */ + getWidth(): number; + + /** + * Returns canvas height (in px) + */ + getHeight(): number; + + /** + * Sets width of this canvas instance + * @param value Value to set width to + * @param [options] Options object + */ + setWidth(value: number|string, options?: ICanvasDimensionsOptions): this; + + /** + * Sets height of this canvas instance + * @param value Value to set height to + * @param [options] Options object + */ + setHeight(value: number|string, options?: ICanvasDimensionsOptions): this; + + /** + * Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em) + * @param dimensions Object with width/height properties + * @param [options] Options object + */ + setDimensions(dimensions: ICanvasDimensions, options?: ICanvasDimensionsOptions): this; + + /** + * Returns canvas zoom level + */ + getZoom(): number; + + /** + * Sets viewport transform of this canvas instance + * @param vpt the transform in the form of context.transform + */ + setViewportTransform(vpt: number[]): this; + + /** + * Sets zoom level of this canvas instance, zoom centered around point + * @param point to zoom with respect to + * @param value to set zoom to, less than 1 zooms out + */ + zoomToPoint(point: Point, value: number): this; + + /** + * Sets zoom level of this canvas instance + * @param value to set zoom to, less than 1 zooms out + */ + setZoom(value: number): this; + + /** + * Pan viewport so as to place point at top left corner of canvas + * @param point to move to + */ + absolutePan(point: Point): this; + + /** + * Pans viewpoint relatively + * @param point (position vector) to move by + */ + relativePan(point: Point): this; + + /** + * Returns element corresponding to this instance + */ + getElement(): HTMLCanvasElement; + + /** + * Returns currently selected object, if any + */ + getActiveObject(): Object; + + /** + * Returns currently selected group of object, if any + */ + getActiveGroup(): Group; + + /** + * Clears specified context of canvas element + * @param ctx Context to clear + * @chainable + */ + clearContext(ctx: CanvasRenderingContext2D): this; + + /** + * Returns context of canvas where objects are drawn + */ + getContext(): CanvasRenderingContext2D; + + /** + * Clears all contexts (background, main, top) of an instance + */ + clear(): this; + + /** + * Renders both the top canvas and the secondary container canvas. + * @param [allOnTop] Whether we want to force all images to be rendered on the top canvas + * @chainable + */ + renderAll(allOnTop?: boolean): this; + + /** + * Method to render only the top canvas. + * Also used to render the group selection box. + * @chainable + */ + renderTop(): StaticCanvas; + + /** + * Returns coordinates of a center of canvas. + * Returned value is an object with top and left properties + */ + getCenter(): { top: number; left: number; }; + /** + * Centers object horizontally. + * You might need to call `setCoords` on an object after centering, to update controls area. + * @param object Object to center horizontally + */ + centerObjectH(object: Object): this; + + /** + * Centers object vertically. + * You might need to call `setCoords` on an object after centering, to update controls area. + * @param object Object to center vertically + */ + centerObjectV(object: Object): this; + + /** + * Centers object vertically and horizontally. + * You might need to call `setCoords` on an object after centering, to update controls area. + * @param object Object to center vertically and horizontally + */ + centerObject(object: Object): this; + + /** + * Returs dataless JSON representation of canvas + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toDatalessJSON(propertiesToInclude?: string[]): string; + + /** + * Returns object representation of canvas + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toObject(propertiesToInclude?: string[]): any; + + /** + * Returns dataless object representation of canvas + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toDatalessObject(propertiesToInclude?: string[]): any; + + /** + * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true, + * a zoomed canvas will then produce zoomed SVG output. + */ + svgViewportTransformation: boolean; + + /** + * Returns SVG representation of canvas + * @param [options] Options object for SVG output + * @param [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation. + */ + toSVG(options: IToSVGOptions, reviver?: Function): string; + + /** + * Moves an object to the bottom of the stack of drawn objects + * @param object Object to send to back + * @chainable + */ + sendToBack(object: Object): this; + + /** + * Moves an object to the top of the stack of drawn objects + * @param object Object to send + * @chainable + */ + bringToFront(object: Object): this; + + /** + * Moves an object down in stack of drawn objects + * @param object Object to send + * @param [intersecting] If `true`, send object behind next lower intersecting object + * @chainable + */ + sendBackwards(object: Object): this; + + /** + * Moves an object up in stack of drawn objects + * @param object Object to send + * @param [intersecting] If `true`, send object in front of next upper intersecting object + * @chainable + */ + bringForward(object: Object): this; + /** + * Moves an object to specified level in stack of drawn objects + * @param object Object to send + * @param index Position to move to + * @chainable + */ + moveTo(object: Object, index: number): this; + + /** + * Clears a canvas element and removes all event listeners + */ + dispose(): this; + + /** + * Returns a string representation of an instance + */ + toString(): string; + + /** + * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately + * @param [options] Options object + */ + toDataURL(options?: IDataURLOptions): string; + + /** + * Provides a way to check support of some of the canvas methods + * (either those of HTMLCanvasElement itself, or rendering context) + * @param methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" + * @return `true` if method is supported (or at least exists), null` if canvas element or context can not be initialized + */ + supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; + + /** + * Populates canvas with data from the specified JSON. + * JSON format must conform to the one of toJSON formats + * @param json JSON string or object + * @param callback Callback, invoked when json is parsed + * and corresponding objects (e.g: {@link fabric.Image}) + * are initialized + * @param [reviver] Method for further parsing of JSON elements, called after each fabric object created. + */ + loadFromJSON(json: string|any, callback: () => void, reviver?: Function): this; + /** + * Clones canvas instance + * @param [callback] Receives cloned instance as a first argument + * @param [properties] Array of properties to include in the cloned canvas and children + */ + clone(callback: (canvas: StaticCanvas) => void, properties?: string[]): void; + + /** + * Clones canvas instance without cloning existing data. + * This essentially copies canvas dimensions, clipping properties, etc. + * but leaves data empty (so that you can populate it with your own) + * @param [callback] Receives cloned instance as a first argument + */ + cloneWithoutData(callback: (canvas: StaticCanvas) => void): void; + + /** + * Callback; invoked right before object is about to be scaled/rotated + */ + onBeforeScaleRotate(target: Object): void; + + // Functions from object straighten mixin + // -------------------------------------------------------------------------------------------------------------------------------- + + /** + * Straightens object, then rerenders canvas + * @param object Object to straighten + */ + straightenObject(object: Object): this; + + /** + * Same as straightenObject, but animated + * @param object Object to straighten + */ + fxStraightenObject(object: Object): this; + + static EMPTY_JSON: string; + /** + * Provides a way to check support of some of the canvas methods + * (either those of HTMLCanvasElement itself, or rendering context) + * @param methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" + */ + static supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; + /** + * Returns JSON representation of canvas + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + static toJSON(propertiesToInclude?: string[]): string; +} + +interface ICanvasOptions extends IStaticCanvasOptions { + /** + * When true, objects can be transformed by one side (unproportionally) + */ + uniScaleTransform?: boolean; + + /** + * When true, objects use center point as the origin of scale transformation. + * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). + */ + centeredScaling?: boolean; + + /** + * When true, objects use center point as the origin of rotate transformation. + * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). + */ + centeredRotation?: boolean; + + /** + * Indicates that canvas is interactive. This property should not be changed. + */ + interactive?: boolean; + + /** + * Indicates whether group selection should be enabled + */ + selection?: boolean; + + /** + * Color of selection + */ + selectionColor?: string; + + /** + * Default dash array pattern + * If not empty the selection border is dashed + */ + selectionDashArray?: any[]; + + /** + * Color of the border of selection (usually slightly darker than color of selection itself) + */ + selectionBorderColor?: string; + + /** + * Width of a line used in object/group selection + */ + selectionLineWidth?: number; + + /** + * Default cursor value used when hovering over an object on canvas + */ + hoverCursor?: string; + + /** + * Default cursor value used when moving an object on canvas + */ + moveCursor?: string; + + /** + * Default cursor value used for the entire canvas + */ + defaultCursor?: string; + + /** + * Cursor value used during free drawing + */ + freeDrawingCursor?: string; + + /** + * Cursor value used for rotation point + */ + rotationCursor?: string; + + /** + * Default element class that's given to wrapper (div) element of canvas + */ + containerClass?: string; + + /** + * When true, object detection happens on per-pixel basis rather than on per-bounding-box + */ + perPixelTargetFind?: boolean; + + /** + * Number of pixels around target pixel to tolerate (consider active) during object detection + */ + targetFindTolerance?: number; + + /** + * When true, target detection is skipped when hovering over canvas. This can be used to improve performance. + */ + skipTargetFind?: boolean; + + /** + * When true, mouse events on canvas (mousedown/mousemove/mouseup) result in free drawing. + * After mousedown, mousemove creates a shape, + * and then mouseup finalizes it and adds an instance of `fabric.Path` onto canvas. + */ + isDrawingMode?: boolean; +} +export interface Canvas extends StaticCanvas {} +export interface Canvas extends ICanvasOptions {} +export class Canvas { + /** + * Constructor + * @param element element to initialize instance on + * @param [options] Options object + */ + constructor(element: HTMLCanvasElement | string, options?: ICanvasOptions); + + _objects: Object[]; + + /** + * Checks if point is contained within an area of given object + * @param e Event object + * @param target Object to test against + */ + containsPoint(e: Event, target: Object): boolean; + /** + * Deactivates all objects on canvas, removing any active group or object + * @return thisArg + */ + deactivateAll(): Canvas; + /** + * Deactivates all objects and dispatches appropriate events + * @param [e] Event (passed along when firing) + * @return thisArg + */ + deactivateAllWithDispatch(e?: Event): Canvas; + /** + * Discards currently active group + * @param [e] Event (passed along when firing) + * @return thisArg + */ + discardActiveGroup(e?: Event): Canvas; + /** + * Discards currently active object + * @param [e] Event (passed along when firing) + * @return thisArg + * @chainable + */ + discardActiveObject(e?: Event): Canvas; + /** + * Draws objects' controls (borders/controls) + * @param ctx Context to render controls on + */ + drawControls(ctx: CanvasRenderingContext2D): void; + /** + * Method that determines what object we are clicking on + * @param e mouse event + * @param skipGroup when true, group is skipped and only objects are traversed through + */ + findTarget(e: MouseEvent, skipGroup: boolean): Canvas; + /** + * Returns currently active group + * @return Current group + */ + getActiveGroup(): Group; + /** + * Returns currently active object + * @return active object + */ + getActiveObject(): Object; + /** + * Returns pointer coordinates relative to canvas. + * @return object with "x" and "y" number values + */ + getPointer(e: Event, ignoreZoom?: boolean, upperCanvasEl?: CanvasRenderingContext2D): { x: number; y: number; }; + /** + * Returns context of canvas where object selection is drawn + */ + getSelectionContext(): CanvasRenderingContext2D; + /** + * Returns element on which object selection is drawn + */ + getSelectionElement(): HTMLCanvasElement; + /** + * Returns true if object is transparent at a certain location + * @param target Object to check + * @param x Left coordinate + * @param y Top coordinate + */ + isTargetTransparent(target: Object, x: number, y: number): boolean; + /** + * Sets active group to a speicified one + * @param group Group to set as a current one + * @param [e] Event (passed along when firing) + */ + setActiveGroup(group: Group, e?: Event): Canvas; + /** + * Sets given object as the only active object on canvas + * @param object Object to set as an active one + * @param [e] Event (passed along when firing "object:selected") + */ + setActiveObject(object: Object, e?: Event): Canvas; + /** + * Set the cursor type of the canvas element + * @param value Cursor type of the canvas element. + * @see http://www.w3.org/TR/css3-ui/#cursor + */ + setCursor(value: string): void; + + /** + * Removes all event listeners + */ + removeListeners(): void; + + static EMPTY_JSON: string; + /** + * Provides a way to check support of some of the canvas methods + * (either those of HTMLCanvasElement itself, or rendering context) + * @param methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" + */ + static supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; + /** + * Returns JSON representation of canvas + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + static toJSON(propertiesToInclude?: string[]): string; +} + +/////////////////////////////////////////////////////////////////////////////// +// Shape Interfaces +////////////////////////////////////////////////////////////////////////////// + +interface ICircleOptions extends IObjectOptions { + /** + * Radius of this circle + */ + radius?: number; + /** + * Start angle of the circle, moving clockwise + */ + startAngle?: number; + + /** + * End angle of the circle + */ + endAngle?: number; +} +export interface Circle extends Object, ICircleOptions {} +export class Circle { + constructor(options?: ICircleOptions); + + /** + * Returns complexity of an instance + * @return complexity of this instance + */ + complexity(): number; + /** + * Returns horizontal radius of an object (according to how an object is scaled) + */ + getRadiusX(): number; + /** + * Returns vertical radius of an object (according to how an object is scaled) + */ + getRadiusY(): number; + /** + * Sets radius of an object (and updates width accordingly) + */ + setRadius(value: number): number; + + /** + * Returns object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return object representation of an instance + */ + toObject(propertiesToInclude?: string[]): any; + /** + * Returns svg representation of an instance + * @param [reviver] Method for further parsing of svg representation. + * @return svg representation of an instance + */ + toSVG(reviver?: Function): string; + + /** + * List of attribute names to account for when parsing SVG element (used by {@link fabric.Circle.fromElement}) + */ + static ATTRIBUTE_NAMES: string[]; + /** + * Returns Circle instance from an SVG element + * @param element Element to parse + * @param [options] Options object + */ + static fromElement(element: SVGElement, options: ICircleOptions): Circle; + /** + * Returns Circle instance from an object representation + * @param object Object to create an instance from + */ + static fromObject(object: any): Circle; +} + +interface IEllipseOptions extends IObjectOptions { + /** + * Horizontal radius + */ + rx?: number; + /** + * Vertical radius + */ + ry?: number; +} +export interface Ellipse extends Object, IEllipseOptions {} +export class Ellipse { + constructor(options?: IEllipseOptions); + + /** + * Returns horizontal radius of an object (according to how an object is scaled) + */ + getRx(): number; + + /** + * Returns Vertical radius of an object (according to how an object is scaled) + */ + getRy(): number; + /** + * Returns object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return object representation of an instance + */ + toObject(propertiesToInclude?: string[]): any; + /** + * Returns svg representation of an instance + * @param [reviver] Method for further parsing of svg representation. + * @return svg representation of an instance + */ + toSVG(reviver?: Function): string; + /** + * Returns complexity of an instance + * @return complexity + */ + complexity(): number; + + /** + * List of attribute names to account for when parsing SVG element (used by {@link fabric.Ellipse.fromElement}) + */ + static ATTRIBUTE_NAMES: string[]; + + /** + * Returns Ellipse instance from an SVG element + * @param element Element to parse + * @param [options] Options object + */ + static fromElement(element: SVGElement, options?: IEllipseOptions): Ellipse; + + /** + * Returns Ellipse instance from an object representation + * @param object Object to create an instance from + */ + static fromObject(object: any): Ellipse; +} + +export interface Group extends Object, ICollection {} +export class Group { + /** + * Constructor + * @param objects Group objects + * @param [options] Options object + */ + constructor(items?: any[], options?: IObjectOptions); + + activateAllObjects(): Group; + /** + * Adds an object to a group; Then recalculates group's dimension, position. + * @return thisArg + * @chainable + */ + addWithUpdate(object: Object): Group; + containsPoint(point: Point): boolean; + /** + * Destroys a group (restoring state of its objects) + * @return thisArg + * @chainable + */ + destroy(): Group; + /** + * Returns requested property + * @param prop Property to get + */ + get(prop: string): any; + /** + * Checks whether this group was moved (since `saveCoords` was called last) + * @return true if an object was moved (since fabric.Group#saveCoords was called) + */ + hasMoved(): boolean; + /** + * Removes an object from a group; Then recalculates group's dimension, position. + * @return thisArg + * @chainable + */ + removeWithUpdate(object: Object): Group; + /** + * Renders instance on a given context + * @param ctx context to render instance on + */ + render(ctx: CanvasRenderingContext2D): void; + /** + * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`) + * @param object Zero or more fabric instances + * @return thisArg + * @chainable + */ + remove(...object: Object[]): Group; + /** + * Saves coordinates of this instance (to be used together with `hasMoved`) + * @saveCoords + * @return thisArg + * @chainable + */ + saveCoords(): Group; + /** + * Sets coordinates of all group objects + * @return thisArg + * @chainable + */ + setObjectsCoords(): Group; + /** + * Returns object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return object representation of an instance + */ + toObject(propertiesToInclude?: string[]): any; + /** + * Returns string represenation of a group + */ + toString(): string; + /** + * Returns svg representation of an instance + * @param [reviver] Method for further parsing of svg representation. + * @return svg representation of an instance + */ + toSVG(reviver?: Function): string; + + /** + * Returns {@link fabric.Group} instance from an object representation + * @param object Object to create a group from + * @param [callback] Callback to invoke when an group instance is created + */ + static fromObject(object: any, callback: (group: Group) => any): void; +} + +interface IImageOptions extends IObjectOptions { + /** + * crossOrigin value (one of "", "anonymous", "allow-credentials") + */ + crossOrigin?: string; + + /** + * AlignX value, part of preserveAspectRatio (one of "none", "mid", "min", "max") + * This parameter defines how the picture is aligned to its viewport when image element width differs from image width. + */ + alignX?: string; + + /** + * AlignY value, part of preserveAspectRatio (one of "none", "mid", "min", "max") + * This parameter defines how the picture is aligned to its viewport when image element height differs from image height. + */ + alignY?: string; + + /** + * meetOrSlice value, part of preserveAspectRatio (one of "meet", "slice"). + * if meet the image is always fully visibile, if slice the viewport is always filled with image. + * @see http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute + */ + meetOrSlice?: string; + + /** + * Image filter array + */ + filters?: IBaseFilter[]; +} +interface Image extends Object, IImageOptions {} +export class Image { + /** + * Constructor + * @param element Image element + * @param [options] Options object + */ + constructor(element: HTMLImageElement, objObjects: IObjectOptions); + + initialize(element?: string|HTMLImageElement, options?: IImageOptions): void; + /** + * Applies filters assigned to this image (from "filters" array) + * @param callback Callback is invoked when all filters have been applied and new image is generated + */ + applyFilters(callback: Function): void; + /** + * Returns a clone of an instance + * @param callback Callback is invoked with a clone as a first argument + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + clone(callback?: Function, propertiesToInclude?: string[]): void; + /** + * Returns complexity of an instance + * @return complexity of this instance + */ + complexity(): number; + /** + * Returns image element which this instance if based on + * @return Image element + */ + getElement(): HTMLImageElement; + /** + * Returns original size of an image + * @return Object with "width" and "height" properties + */ + getOriginalSize(): { width: number; height: number; }; + /** + * Returns source of an image + * @return Source of an image + */ + getSrc(): string; + render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; + + /** + * Sets image element for this instance to a specified one. + * If filters defined they are applied to new image. + * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area. + * @param [callback] Callback is invoked when all filters have been applied and new image is generated + * @param [options] Options object + */ + setElement(element: HTMLImageElement, callback: Function, options: IImageOptions): Image; + /** + * Sets crossOrigin value (on an instance and corresponding image element) + */ + setCrossOrigin(value: string): Image; + /** + * Returns object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return Object representation of an instance + */ + toObject(propertiesToInclude?: string[]): any; + /** + * Returns string representation of an instance + * @return String representation of an instance + */ + toString(): string; + /** + * Returns SVG representation of an instance + * @param [reviver] Method for further parsing of svg representation. + * @return svg representation of an instance + */ + toSVG(reviver?: Function): string; + /** + * Sets source of an image + * @param src Source string (URL) + * @param [callback] Callback is invoked when image has been loaded (and all filters have been applied) + * @param [options] Options object + */ + setSrc(src: string, callback?: Function, options?: IImageOptions): Image; + + /** + * Creates an instance of fabric.Image from an URL string + * @param url URL to create an image from + * @param [callback] Callback to invoke when image is created (newly created image is passed as a first argument) + * @param [imgOptions] Options object + */ + static fromURL(url: string, callback?: (image: Image) => void, objObjects?: IObjectOptions): Image; + /** + * Creates an instance of fabric.Image from its object representation + * @param object Object to create an instance from + * @param [callback] Callback to invoke when an image instance is created + */ + static fromObject(object: any, callback: (image: Image) => void): void; + /** + * Returns Image instance from an SVG element + * @param element Element to parse + * @param callback Callback to execute when fabric.Image object is created + * @param [options] Options object + */ + static fromElement(element: SVGElement, callback: (image: Image) => void, options?: IImageOptions): void; + /** + * Default CSS class name for canvas + */ + static CSS_CANVAS: string; + + static filters: IAllFilters; +} + +interface ILineOptions extends IObjectOptions { + /** + * x value or first line edge + */ + x1: number; + /** + * x value or second line edge + */ + x2: number; + /** + * y value or first line edge + */ + y1: number; + /** + * y value or second line edge + */ + y2: number; +} +export interface Line extends Object, ILineOptions {} +export class Line { + /** + * Constructor + * @param [points] Array of points + * @param [options] Options object + */ + constructor(points?: number[], objObjects?: IObjectOptions); + /** + * Returns complexity of an instance + * @return complexity + */ + complexity(): number; + initialize(points?: number[], options?: ILineOptions): Line; + /** + * Returns object representation of an instance + * @methd toObject + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return object representation of an instance + */ + toObject(propertiesToInclude: string[]): any; + /** + * Returns SVG representation of an instance + * @param [reviver] Method for further parsing of svg representation. + * @return svg representation of an instance + */ + toSVG(reviver?: Function): string; + + static ATTRIBUTE_NAMES: string[]; + /** + * Returns fabric.Line instance from an SVG element + * @param element Element to parse + * @param [options] Options object + */ + static fromElement(element: SVGElement, options?: ILineOptions): Line; + /** + * Returns fabric.Line instance from an object representation + * @param object Object to create an instance from + */ + static fromObject(object: any): Line; +} + +interface IObjectOptions { + /** + * Type of an object (rect, circle, path, etc.). + * Note that this property is meant to be read-only and not meant to be modified. + * If you modify, certain parts of Fabric (such as JSON loading) won't work correctly. + */ + type?: string; + + /** + * Horizontal origin of transformation of an object (one of "left", "right", "center") + */ + originX?: string; + + /** + * Vertical origin of transformation of an object (one of "top", "bottom", "center") + */ + originY?: string; + + /** + * Top position of an object. Note that by default it's relative to object center. You can change this by setting originY={top/center/bottom} + */ + top?: number; + + /** + * Left position of an object. Note that by default it's relative to object center. You can change this by setting originX={left/center/right} + */ + left?: number; + + /** + * Object width + */ + width?: number; + + /** + * Object height + */ + height?: number; + + /** + * Object scale factor (horizontal) + */ + scaleX?: number; + + /** + * Object scale factor (vertical) + */ + scaleY?: number; + + /** + * When true, an object is rendered as flipped horizontally + */ + flipX?: boolean; + + /** + * When true, an object is rendered as flipped vertically + */ + flipY?: boolean; + + /** + * Opacity of an object + */ + opacity?: number; + + /** + * Angle of rotation of an object (in degrees) + */ + angle?: number; + + /** + * When true, object's controlling corners are rendered as transparent inside (i.e. stroke instead of fill) + */ + transparentCorners?: boolean; + + /** + * Default cursor value used when hovering over this object on canvas + */ + hoverCursor?: string; + + /** + * Padding between object and its controlling borders (in pixels) + */ + padding?: number; + + /** + * Color of controlling borders of an object (when it's active) + */ + borderColor?: string; + + /** + * Color of controlling corners of an object (when it's active) + */ + cornerColor?: string; + + /** + * Array specifying dash pattern of an object's control (hasBorder must be true) + */ + cornerDashArray?: number[]; + + /** + * Size of object's controlling corners (in pixels) + */ + cornerSize?: number; + + /** + * Color of controlling corners of an object (when it's active and transparentCorners false) + */ + cornerStrokeColor?: string; + + /** + * Specify style of control, 'rect' or 'circle' + */ + cornerStyle?: "rect" | "circle"; + + /** + * When true, this object will use center point as the origin of transformation + * when being scaled via the controls. + * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). + */ + centeredScaling?: boolean; + + /** + * When true, this object will use center point as the origin of transformation + * when being rotated via the controls. + * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). + */ + centeredRotation?: boolean; + + /** + * Color of object's fill + */ + fill?: string; + + /** + * Fill rule used to fill an object + * accepted values are nonzero, evenodd + * Backwards incompatibility note: This property was used for setting globalCompositeOperation until v1.4.12, use `globalCompositeOperation` instead + */ + fillRule?: string; + + /** + * Composite rule used for canvas globalCompositeOperation + */ + globalCompositeOperation?: string; + + /** + * Background color of an object. Only works with text objects at the moment. + */ + backgroundColor?: string; + + /** + * When defined, an object is rendered via stroke and this property specifies its color + */ + stroke?: string; + + /** + * Width of a stroke used to render this object + */ + strokeWidth?: number; + + /** + * Array specifying dash pattern of an object's stroke (stroke must be defined) + */ + strokeDashArray?: any[]; + + /** + * Line endings style of an object's stroke (one of "butt", "round", "square") + */ + strokeLineCap?: string; + + /** + * Corner style of an object's stroke (one of "bevil", "round", "miter") + */ + strokeLineJoin?: string; + + /** + * Maximum miter length (used for strokeLineJoin = "miter") of an object's stroke + */ + strokeMiterLimit?: number; + + /** + * Shadow object representing shadow of this shape + */ + shadow?: Shadow|string; + + /** + * Opacity of object's controlling borders when object is active and moving + */ + borderOpacityWhenMoving?: number; + + /** + * Scale factor of object's controlling borders + */ + borderScaleFactor?: number; + + /** + * Transform matrix (similar to SVG's transform matrix) + */ + transformMatrix?: any[]; + + /** + * Minimum allowed scale value of an object + */ + minScaleLimit?: number; + + /** + * When set to `false`, an object can not be selected for modification (using either point-click-based or group-based selection). + * But events still fire on it. + */ + selectable?: boolean; + + /** + * When set to `false`, an object can not be a target of events. All events propagate through it. Introduced in v1.3.4 + */ + evented?: boolean; + + /** + * When set to `false`, an object is not rendered on canvas + */ + visible?: boolean; + + /** + * When set to `false`, object's controls are not displayed and can not be used to manipulate object + */ + hasControls?: boolean; + + /** + * When set to `false`, object's controlling borders are not rendered + */ + hasBorders?: boolean; + + /** + * When set to `false`, object's controlling rotating point will not be visible or selectable + */ + hasRotatingPoint?: boolean; + + /** + * Offset for object's controlling rotating point (when enabled via `hasRotatingPoint`) + */ + rotatingPointOffset?: number; + + /** + * When set to `true`, objects are "found" on canvas on per-pixel basis rather than according to bounding box + */ + perPixelTargetFind?: boolean; + + /** + * When `false`, default object's values are not included in its serialization + */ + includeDefaultValues?: boolean; + + /** + * Function that determines clipping of an object (context is passed as a first argument) + * Note that context origin is at the object's center point (not left/top corner) + */ + clipTo?: Function; + + /** + * When `true`, object horizontal movement is locked + */ + lockMovementX?: boolean; + + /** + * When `true`, object vertical movement is locked + */ + lockMovementY?: boolean; + + /** + * When `true`, object rotation is locked + */ + lockRotation?: boolean; + + /** + * When `true`, object horizontal scaling is locked + */ + lockScalingX?: boolean; + + /** + * When `true`, object vertical scaling is locked + */ + lockScalingY?: boolean; + + /** + * When `true`, object non-uniform scaling is locked + */ + lockUniScaling?: boolean; + + /** + * When `true`, object cannot be flipped by scaling into negative values + */ + lockScalingFlip?: boolean; + + /** + * Not used by fabric, just for convenience + */ + name?: string; + + /** + * Not used by fabric, just for convenience + */ + data?: any; +} +export interface Object extends IObservable, IObjectOptions, IObjectAnimation {} +export class Object { + getCurrentWidth(): number; + getCurrentHeight(): number; + + getAngle(): number; + setAngle(value: number): Object; + + getBorderColor(): string; + setBorderColor(value: string): Object; + + getBorderScaleFactor(): number; + + getCornersize(): number; + setCornersize(value: number): Object; + + getFill(): string; + setFill(value: string): Object; + + getFillRule(): string; + setFillRule(value: string): Object; + + getFlipX(): boolean; + setFlipX(value: boolean): Object; + + getFlipY(): boolean; + setFlipY(value: boolean): Object; + + getHeight(): number; + setHeight(value: number): Object; + + getLeft(): number; + setLeft(value: number): Object; + + getOpacity(): number; + setOpacity(value: number): Object; + + overlayFill: string; + getOverlayFill(): string; + setOverlayFill(value: string): Object; + + getScaleX(): number; + setScaleX(value: number): Object; + + getScaleY(): number; + setScaleY(value: number): Object; + + setShadow(options: any): Object; + getShadow(): Object; + + stateProperties: any[]; + getTop(): number; + setTop(value: number): Object; + + getWidth(): number; + setWidth(value: number): Object; + + /* * Sets object's properties from options + * @param {Object} [options] Options object + */ + setOptions(options: IObjectOptions): void; + + /** + * Transforms context when rendering an object + * @param ctx Context + * @param fromLeft When true, context is transformed to object's top/left corner. This is used when rendering text on Node + */ + transform(ctx: CanvasRenderingContext2D, fromLeft: boolean): void; + + /** + * Returns an object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toObject(propertiesToInclude?: string[]): any; + + /** + * Returns (dataless) object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toDatalessObject(propertiesToInclude?: string[]): any; + + /** + * Returns a string representation of an instance + */ + toString(): string; + + /** + * Basic getter + * @param property Property name + */ + get(property: K): this[K]; + + /** + * Sets property to a given value. + * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. + * If you need to update those, call `setCoords()`. + * @param key Property name + * @param value Property value (if function, the value is passed into it and its return value is used as a new one) + */ + set(key: K, value: this[K] | ((value: this[K]) => this[K])): this; + /** + * Sets property to a given value. + * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. + * If you need to update those, call `setCoords()`. + * @param options Property object, iterate over the object properties + */ + set(options: Partial): this; + + /** + * Toggles specified property from `true` to `false` or from `false` to `true` + * @param property Property to toggle + */ + toggle(property: keyof this): this; + + /** + * Sets sourcePath of an object + * @param value Value to set sourcePath to + */ + setSourcePath(value: string): this; + + /** + * Retrieves viewportTransform from Object's canvas if possible + */ + getViewportTransform(): boolean; + + /** + * Renders an object on a specified context + * @param ctx Context to render on + * @param [noTransform] When true, context is not transformed + */ + render(ctx: CanvasRenderingContext2D, noTransform?: boolean): void; + + /** + * Clones an instance, using a callback method will work for every object. + * @param callback Callback is invoked with a clone as a first argument + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + clone(callback: (clone: Object) => void, propertiesToInclude?: string[]): void; + + /** + * Creates an instance of fabric.Image out of an object + * @param callback callback, invoked with an instance as a first argument + */ + cloneAsImage(callback: (image: Image) => void): this; + + /** + * Converts an object into a data-url-like string + * @param options Options object + */ + toDataURL(options: IDataURLOptions): string; + + /** + * Returns true if specified type is identical to the type of an instance + * @param type Type to check against + */ + isType(type: string): boolean; + + /** + * Returns complexity of an instance + */ + complexity(): number; + + /** + * Returns a JSON representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toJSON(propertiesToInclude?: string[]): any; + + /** + * Sets gradient (fill or stroke) of an object + * **Backwards incompatibility note:** This method was named "setGradientFill" until v1.1.0 + * @param property Property name 'stroke' or 'fill' + * @param [options] Options object + */ + setGradient(property: "stroke" | "fill", options: IGradientOptions): this; + /** + * Sets pattern fill of an object + * @param options Options object + */ + setPatternFill(options: IFillOptions): this; + + /** + * Sets shadow of an object + * @param [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)") + */ + setShadow(options?: string | Shadow): this; + + /** + * Sets "color" of an instance (alias of `set('fill', …)`) + * @param color Color value + */ + setColor(color: string): this; + + /** + * Sets "angle" of an instance + * @param angle Angle value + */ + setAngle(angle: number): this; + + /** + * Sets "angle" of an instance + * @param angle Angle value + */ + rotate(angle: number): this; + + /** + * Centers object horizontally on canvas to which it was added last. + * You might need to call `setCoords` on an object after centering, to update controls area. + */ + centerH(): this; + + /** + * Centers object vertically on canvas to which it was added last. + * You might need to call `setCoords` on an object after centering, to update controls area. + */ + centerV(): this; + + /** + * Centers object vertically and horizontally on canvas to which is was added last + * You might need to call `setCoords` on an object after centering, to update controls area. + */ + center(): this; + + /** + * Removes object from canvas to which it was added last + */ + remove(): Object; + + /** + * Returns coordinates of a pointer relative to an object + * @param e Event to operate upon + * @param [pointer] Pointer to operate upon (instead of event) + */ + getLocalPointer(e: Event, pointer?: { x: number, y: number }): { x: number, y: number }; + + /** + * Sets object's properties from options + * @param [options] Options object + */ + setOptions(options: any): void; + /** + * Sets sourcePath of an object + * @param value Value to set sourcePath to + */ + setSourcePath(value: string): Object; + // functions from object svg export mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Returns styles-string for svg-export + */ + getSvgStyles(): string; + /** + * Returns transform-string for svg-export + */ + getSvgTransform(): string; + /** + * Returns transform-string for svg-export from the transform matrix of single elements + */ + getSvgTransformMatrix(): string; + + // functions from stateful mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Returns true if object state (one of its state properties) was changed + */ + hasStateChanged(): boolean; + /** + * Saves state of an object + * @param [options] Object with additional `stateProperties` array to include when saving state + * @return thisArg + */ + saveState(options?: { stateProperties: any[] }): this; + /** + * Setups state of an object + */ + setupState(): this; + // functions from object straightening mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Straightens an object (rotating it from current angle to one of 0, 90, 180, 270, etc. depending on which is closer) + */ + straighten(): this; + /** + * Same as straighten but with animation + */ + fxStraighten(callbacks: Callbacks): this; + + // functions from object stacking mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Moves an object up in stack of drawn objects + * @param [intersecting] If `true`, send object in front of next upper intersecting object + */ + bringForward(intersecting?: boolean): this; + /** + * Moves an object to the top of the stack of drawn objects + */ + bringToFront(): this; + /** + * Moves an object down in stack of drawn objects + * @param [intersecting] If `true`, send object behind next lower intersecting object + */ + sendBackwards(intersecting?: boolean): this; + /** + * Moves an object to the bottom of the stack of drawn objects + */ + sendToBack(): this; + /** + * Moves an object to specified level in stack of drawn objects + * @param index New position of object + */ + moveTo(index: number): this; + + // functions from object origin mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Translates the coordinates from origin to center coordinates (based on the object's dimensions) + * @param point The point which corresponds to the originX and originY params + * @param originX Horizontal origin: 'left', 'center' or 'right' + * @param originY Vertical origin: 'top', 'center' or 'bottom' + */ + translateToCenterPoint(point: Point, originX: string, originY: string): Point; + + /** + * Translates the coordinates from center to origin coordinates (based on the object's dimensions) + * @param center The point which corresponds to center of the object + * @param originX Horizontal origin: 'left', 'center' or 'right' + * @param originY Vertical origin: 'top', 'center' or 'bottom' + */ + translateToOriginPoint(center: Point, originX: string, originY: string): Point; + /** + * Returns the real center coordinates of the object + */ + getCenterPoint(): Point; + + /** + * Returns the coordinates of the object as if it has a different origin + * @param originX Horizontal origin: 'left', 'center' or 'right' + * @param originY Vertical origin: 'top', 'center' or 'bottom' + */ + getPointByOrigin(): Point; + + /** + * Returns the point in local coordinates + * @param point The point relative to the global coordinate system + * @param originX Horizontal origin: 'left', 'center' or 'right' + * @param originY Vertical origin: 'top', 'center' or 'bottom' + */ + toLocalPoint(point: Point, originX: string, originY: string): Point; + + /** + * Sets the position of the object taking into consideration the object's origin + * @param pos The new position of the object + * @param originX Horizontal origin: 'left', 'center' or 'right' + * @param originY Vertical origin: 'top', 'center' or 'bottom' + */ + setPositionByOrigin(pos: Point, originX: string, originY: string): void; + + /** + * @param to One of 'left', 'center', 'right' + */ + adjustPosition(to: string): void; + + // functions from interactivity mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Draws borders of an object's bounding box. + * Requires public properties: width, height + * Requires public options: padding, borderColor + * @param ctx Context to draw on + */ + drawBorders(context: CanvasRenderingContext2D): this; + + /** + * Draws corners of an object's bounding box. + * Requires public properties: width, height + * Requires public options: cornerSize, padding + * @param ctx Context to draw on + */ + drawCorners(context: CanvasRenderingContext2D): Object; + + /** + * Returns true if the specified control is visible, false otherwise. + * @param controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'. + */ + isControlVisible(controlName: string): boolean; + /** + * Sets the visibility of the specified control. + * @param controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'. + * @param visible true to set the specified control visible, false otherwise + */ + setControlVisible(controlName: string, visible: boolean): this; + + /** + * Sets the visibility state of object controls. + * @param [options] Options object + */ + setControlsVisibility(options?: { + bl?: boolean; + br?: boolean; + mb?: boolean; + ml?: boolean; + mr?: boolean; + mt?: boolean; + tl?: boolean; + tr?: boolean; + mtr?: boolean; }): this; + + // functions from geometry mixin + // ------------------------------------------------------------------------------------------------------------------------------- + /** + * Sets corner position coordinates based on current angle, width and height + * See https://github.com/kangax/fabric.js/wiki/When-to-call-setCoords + */ + setCoords(): this; + /** + * Returns coordinates of object's bounding rectangle (left, top, width, height) + * @return Object with left, top, width, height properties + */ + getBoundingRect(): { left: number; top: number; width: number; height: number }; + /** + * Checks if object is fully contained within area of another object + * @param other Object to test + */ + isContainedWithinObject(other: Object): boolean; + /** + * Checks if object is fully contained within area formed by 2 points + * @param pointTL top-left point of area + * @param pointBR bottom-right point of area + */ + isContainedWithinRect(pointTL: any, pointBR: any): boolean; + /** + * Checks if point is inside the object + * @param point Point to check against + */ + containsPoint(point: Point): boolean; + /** + * Scales an object (equally by x and y) + * @param value Scale factor + * @return thisArg + */ + scale(value: number): this; + /** + * Scales an object to a given height, with respect to bounding box (scaling by x/y equally) + * @param value New height value + */ + scaleToHeight(value: number): this; + /** + * Scales an object to a given width, with respect to bounding box (scaling by x/y equally) + * @param value New width value + */ + scaleToWidth(value: number): this; + /** + * Checks if object intersects with another object + * @param other Object to test + */ + intersectsWithObject(other: Object): boolean; + /** + * Checks if object intersects with an area formed by 2 points + * @param pointTL top-left point of area + * @param pointBR bottom-right point of area + */ + intersectsWithRect(pointTL: any, pointBR: any): boolean; +} + +interface IPathOptions extends IObjectOptions { + /** + * Array of path points + */ + path?: any[]; + + /** + * Minimum X from points values, necessary to offset points + */ + minX?: number; + + /** + * Minimum Y from points values, necessary to offset points + */ + minY?: number; +} +export interface Path extends Object, IPathOptions {} +export class Path { + /** + * Constructor + * @param path Path data (sequence of coordinates and corresponding "command" tokens) + * @param [options] Options object + */ + constructor(path?: string|any[], options?: IPathOptions); + + initialize(path?: any[], options?: IPathOptions): Path; + + /** + * Returns number representation of an instance complexity + * @return complexity of this instance + */ + complexity(): number; + + /** + * Renders path on a specified context + * @param ctx context to render path on + * @param [noTransform] When true, context is not transformed + */ + render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; + /** + * Returns dataless object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return object representation of an instance + */ + toDatalessObject(propertiesToInclude?: string[]): any; + /** + * Returns object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return object representation of an instance + */ + toObject(propertiesToInclude?: string[]): any; + /** + * Returns string representation of an instance + * @return string representation of an instance + */ + toString(): string; + /** + * Returns svg representation of an instance + * @param [reviver] Method for further parsing of svg representation. + * @return svg representation of an instance + */ + toSVG(reviver?: Function): string; + + /** + * Creates an instance of fabric.Path from an SVG element + * @param element to parse + * @param callback Callback to invoke when an fabric.Path instance is created + * @param [options] Options object + */ + static fromElement(element: SVGElement, callback: (path: Path) => any, options?: IPathOptions): void; + /** + * Creates an instance of fabric.Path from an object + * @param callback Callback to invoke when an fabric.Path instance is created + */ + static fromObject(object: any, callback: (path: Path) => any): void; +} + +export class PathGroup extends Object { + /** + * Constructor + * @param [options] Options object + */ + constructor(paths: Path[], options?: IObjectOptions); + + initialize(paths: Path[], options?: IObjectOptions): void; + /** + * Returns number representation of object's complexity + * @return complexity + */ + complexity(): number; + /** + * Returns true if all paths in this group are of same color + * @return true if all paths are of the same color (`fill`) + */ + isSameColor(): boolean; + /** + * Renders this group on a specified context + * @param ctx Context to render this instance on + */ + render(ctx: CanvasRenderingContext2D): void; + /** + * Returns dataless object representation of this path group + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return dataless object representation of an instance + */ + toDatalessObject(propertiesToInclude?: string[]): any; + /** + * Returns object representation of this path group + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return object representation of an instance + */ + toObject(propertiesToInclude?: string[]): any; + /** + * Returns a string representation of this path group + * @return string representation of an object + */ + toString(): string; + /** + * Returns svg representation of an instance + * @param [reviver] Method for further parsing of svg representation. + * @return svg representation of an instance + */ + toSVG(reviver?: Function): string; + /** + * Returns all paths in this path group + * @return array of path objects included in this path group + */ + getObjects(): Path[]; + + static fromObject(object: any): PathGroup; + /** + * Creates fabric.PathGroup instance from an object representation + * @param object Object to create an instance from + * @param callback Callback to invoke when an fabric.PathGroup instance is created + */ + static fromObject(object: any, callback: (group: PathGroup) => any): void; +} + +interface IPolygonOptions extends IObjectOptions { + /** + * Points array + */ + points?: Point[]; + + /** + * Minimum X from points values, necessary to offset points + */ + minX?: number; + + /** + * Minimum Y from points values, necessary to offset points + */ + minY?: number; +} +export interface Polygon extends IPolygonOptions {} +export class Polygon extends Object { + /** + * Constructor + * @param points Array of points + * @param [options] Options object + */ + constructor(points: Array<{ x: number; y: number }>, options?: IObjectOptions, skipOffset?: boolean); + + /** + * Returns complexity of an instance + * @return complexity of this instance + */ + complexity(): number; + + /** + * Returns object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return object representation of an instance + */ + toObject(propertiesToInclude?: string[]): any; + /** + * Returns svg representation of an instance + * @param [reviver] Method for further parsing of svg representation. + * @return svg representation of an instance + */ + toSVG(reviver?: Function): string; + + /** + * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) + */ + static ATTRIBUTE_NAMES: string[]; + + /** + * Returns Polygon instance from an SVG element + * @param element Element to parse + * @param [options] Options object + */ + static fromElement(element: SVGElement, options?: IPolygonOptions): Polygon; + /** + * Returns fabric.Polygon instance from an object representation + * @param object Object to create an instance from + */ + static fromObject(object: any): Polygon; +} + +interface IPolylineOptions extends IObjectOptions { + /** + * Points array + */ + points?: Point[]; + + /** + * Minimum X from points values, necessary to offset points + */ + minX?: number; + + /** + * Minimum Y from points values, necessary to offset points + */ + minY?: number; +} +export interface Polyline extends IPolylineOptions {} +export class Polyline extends Object { + /** + * Constructor + * @param points Array of points (where each point is an object with x and y) + * @param [options] Options object + * @param [skipOffset] Whether points offsetting should be skipped + */ + constructor(points: Array<{ x: number; y: number }>, options?: IPolylineOptions); + initialize(points: Point[], options?: IPolylineOptions): void; + /** + * Returns complexity of an instance + * @return complexity of this instance + */ + complexity(): number; + /** + * Returns object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return Object representation of an instance + */ + toObject(propertiesToInclude?: string[]): any; + /** + * Returns SVG representation of an instance + * @param [reviver] Method for further parsing of svg representation. + * @return svg representation of an instance + */ + toSVG(reviver?: Function): string; + + /** + * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) + */ + static ATTRIBUTE_NAMES: string[]; + + /** + * Returns Polyline instance from an SVG element + * @param element Element to parse + * @param [options] Options object + */ + static fromElement(element: SVGElement, options?: IPolylineOptions): Polyline; + /** + * Returns fabric.Polyline instance from an object representation + * @param object Object to create an instance from + */ + static fromObject(object: any): Polyline; +} + +interface IRectOptions extends IObjectOptions { + x?: number; + y?: number; + /** + * Horizontal border radius + */ + rx?: number; + + /** + * Vertical border radius + */ + ry?: number; +} + +export interface Rect extends IRectOptions {} +export class Rect extends Object { + /** + * Constructor + * @param [options] Options object + */ + constructor(options?: IRectOptions); + initialize(points?: number[], options?: any): Rect; + /** + * Returns complexity of an instance + * @return complexity + */ + complexity(): number; + /** + * Returns object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return object representation of an instance + */ + toObject(propertiesToInclude: any[]): any; + /** + * Returns svg representation of an instance + * @param [reviver] Method for further parsing of svg representation. + * @return svg representation of an instance + */ + toSVG(reviver?: Function): string; + + /** + * List of attribute names to account for when parsing SVG element (used by `fabric.Rect.fromElement`) + */ + static ATTRIBUTE_NAMES: string[]; + /** + * Returns Rect instance from an SVG element + * @param element Element to parse + * @param [options] Options object + */ + static fromElement(element: SVGElement, options?: IRectOptions): Rect; + /** + * Returns Rect instance from an object representation + * @param object Object to create an instance from + */ + static fromObject(object: any): Rect; +} + +interface ITextOptions extends IObjectOptions { + /** + * Font size (in pixels) + */ + fontSize?: number; + /** + * Font weight (e.g. bold, normal, 400, 600, 800) + */ + fontWeight?: number|string; + /** + * Font family + */ + fontFamily?: string; + /** + * Text decoration Possible values?: "", "underline", "overline" or "line-through". + */ + textDecoration?: string; + /** + * Text alignment. Possible values?: "left", "center", or "right". + */ + textAlign?: string; + /** + * Font style . Possible values?: "", "normal", "italic" or "oblique". + */ + fontStyle?: string; + /** + * Line height + */ + lineHeight?: number; + /** + * When defined, an object is rendered via stroke and this property specifies its color. + * Backwards incompatibility note?: This property was named "strokeStyle" until v1.1.6 + */ + stroke?: string; + /** + * Shadow object representing shadow of this shape. + * Backwards incompatibility note?: This property was named "textShadow" (String) until v1.2.11 + */ + shadow?: Shadow|string; + /** + * Background color of text lines + */ + textBackgroundColor?: string; + + path?: string; + useNative?: boolean; + text?: string; +} +export interface Text extends ITextOptions {} +export class Text extends Object { + /** + * Constructor + * @param text Text string + * @param [options] Options object + */ + constructor(text: string, options?: ITextOptions); + /** + * Returns complexity of an instance + */ + complexity(): number; + /** + * Returns string representation of an instance + */ + toString(): string; + /** + * Renders text instance on a specified context + * @param ctx Context to render on + */ + render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; + /** + * Returns object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toObject(propertiesToInclude?: string[]): any; + /** + * Returns SVG representation of an instance + * @param [reviver] Method for further parsing of svg representation. + */ + toSVG(reviver?: Function): string; + /** + * Retrieves object's fontSize + */ + getFontSize(): number; + /** + * Sets object's fontSize + * @param fontSize Font size (in pixels) + */ + setFontSize(fontSize: number): Text; + /** + * Retrieves object's fontWeight + */ + getFontWeight(): number|string; + /** + * Sets object's fontWeight + * @param fontWeight Font weight + */ + setFontWeight(fontWeight: string|number): Text; + /** + * Retrieves object's fontFamily + */ + getFontFamily(): string; + /** + * Sets object's fontFamily + * @param fontFamily Font family + */ + setFontFamily(fontFamily: string): Text; + /** + * Retrieves object's text + */ + getText(): string; + /** + * Sets object's text + * @param text Text + */ + setText(text: string): Text; + /** + * Retrieves object's textDecoration + */ + getTextDecoration(): string; + /** + * Sets object's textDecoration + * @param textDecoration Text decoration + */ + setTextDecoration(textDecoration: string): Text; + /** + * Retrieves object's fontStyle + */ + getFontStyle(): string; + /** + * Sets object's fontStyle + * @param fontStyle Font style + */ + setFontStyle(fontStyle: string): Text; + /** + * Retrieves object's lineHeight + */ + getLineHeight(): number; + /** + * Sets object's lineHeight + * @param lineHeight Line height + */ + setLineHeight(lineHeight: number): Text; + /** + * Retrieves object's textAlign + */ + getTextAlign(): string; + /** + * Sets object's textAlign + * @param textAlign Text alignment + */ + setTextAlign(textAlign: string): Text; + /** + * Retrieves object's textBackgroundColor + */ + getTextBackgroundColor(): string; + /** + * Sets object's textBackgroundColor + * @param textBackgroundColor Text background color + */ + setTextBackgroundColor(textBackgroundColor: string): Text; + + /** + * List of attribute names to account for when parsing SVG element (used by `fabric.Text.fromElement`) + */ + static ATTRIBUTE_NAMES: string[]; + /** + * Default SVG font size + */ + static DEFAULT_SVG_FONT_SIZE: number; + + /** + * Returns fabric.Text instance from an SVG element (not yet implemented) + * @param element Element to parse + * @param [options] Options object + */ + static fromElement(element: SVGElement, options?: ITextOptions): Text; + /** + * Returns fabric.Text instance from an object representation + * @param object Object to create an instance from + */ + static fromObject(object: any): Text; +} + +interface IITextOptions extends IObjectOptions, ITextOptions { + /** + * Index where text selection starts (or where cursor is when there is no selection) + */ + selectionStart?: number; + + /** + * Index where text selection ends + */ + selectionEnd?: number; + + /** + * Color of text selection + */ + selectionColor?: string; + + /** + * Indicates whether text is in editing mode + */ + isEditing?: boolean; + + /** + * Indicates whether a text can be edited + */ + editable?: boolean; + + /** + * Border color of text object while it's in editing mode + */ + editingBorderColor?: string; + + /** + * Width of cursor (in px) + */ + cursorWidth?: number; + + /** + * Color of default cursor (when not overwritten by character style) + */ + cursorColor?: string; + + /** + * Delay between cursor blink (in ms) + */ + cursorDelay?: number; + + /** + * Duration of cursor fadein (in ms) + */ + cursorDuration?: number; + + /** + * Object containing character styles + * (where top-level properties corresponds to line number and 2nd-level properties -- to char number in a line) + */ + styles?: any; + + /** + * Indicates whether internal text char widths can be cached + */ + caching?: boolean; +} +export interface IText extends Text, IITextOptions {} +export class IText extends Object { + /** + * Constructor + * @param text Text string + * @param [options] Options object + */ + constructor(text: string, options?: IITextOptions); + /** + * Returns true if object has no styling + */ + isEmptyStyles(): boolean; + render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; + /** + * Returns object representation of an instance + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return object representation of an instance + */ + toObject(propertiesToInclude?: string[]): any; + + setText(value: string): Text; + /** + * Sets selection start (left boundary of a selection) + * @param index Index to set selection start to + */ + setSelectionStart(index: number): void; + /** + * Sets selection end (right boundary of a selection) + * @param index Index to set selection end to + */ + setSelectionEnd(index: number): void; + /** + * Gets style of a current selection/cursor (at the start position) + * @param [startIndex] Start index to get styles at + * @param [endIndex] End index to get styles at + * @return styles Style object at a specified (or current) index + */ + getSelectionStyles(startIndex: number, endIndex: number): any; + /** + * Sets style of a current selection + * @param [styles] Styles object + * @return thisArg + * @chainable + */ + setSelectionStyles(styles: any): Text; + + /** + * Renders cursor or selection (depending on what exists) + */ + renderCursorOrSelection(): void; + + /** + * Returns 2d representation (lineIndex and charIndex) of cursor (or selection start) + * @param [selectionStart] Optional index. When not given, current selectionStart is used. + */ + get2DCursorLocation(selectionStart?: number): void; + /** + * Returns complete style of char at the current cursor + * @param lineIndex Line index + * @param charIndex Char index + * @return Character style + */ + getCurrentCharStyle(lineIndex: number, charIndex: number): any; + + /** + * Returns fontSize of char at the current cursor + * @param lineIndex Line index + * @param charIndex Char index + * @return Character font size + */ + getCurrentCharFontSize(lineIndex: number, charIndex: number): number; + + /** + * Returns color (fill) of char at the current cursor + * @param lineIndex Line index + * @param charIndex Char index + * @return Character color (fill) + */ + getCurrentCharColor(lineIndex: number, charIndex: number): string; + /** + * Renders cursor + */ + renderCursor(boundaries: any): void; + + /** + * Renders text selection + * @param chars Array of characters + * @param boundaries Object with left/top/leftOffset/topOffset + */ + renderSelection(chars: string[], boundaries: any): void; + + // functions from itext behavior mixin + // ------------------------------------------------------------------------------------------------------------------------ + /** + * Initializes all the interactive behavior of IText + */ + initBehavior(): void; + + /** + * Initializes "selected" event handler + */ + initSelectedHandler(): void; + + /** + * Initializes "added" event handler + */ + initAddedHandler(): void; + + initRemovedHandler(): void; + + /** + * Initializes delayed cursor + */ + initDelayedCursor(restart: boolean): void; + + /** + * Aborts cursor animation and clears all timeouts + */ + abortCursorAnimation(): void; + + /** + * Selects entire text + */ + selectAll(): void; + + /** + * Returns selected text + */ + getSelectedText(): string; + + /** + * Find new selection index representing start of current word according to current selection index + * @param startFrom Surrent selection index + * @return New selection index + */ + findWordBoundaryLeft(startFrom: number): number; + + /** + * Find new selection index representing end of current word according to current selection index + * @param startFrom Current selection index + * @return New selection index + */ + findWordBoundaryRight(startFrom: number): number; + + /** + * Find new selection index representing start of current line according to current selection index + * @param startFrom Current selection index + */ + findLineBoundaryLeft(startFrom: number): number; + + /** + * Find new selection index representing end of current line according to current selection index + * @param startFrom Current selection index + */ + findLineBoundaryRight(startFrom: number): number; + + /** + * Returns number of newlines in selected text + */ + getNumNewLinesInSelectedText(): number; + + /** + * Finds index corresponding to beginning or end of a word + * @param selectionStart Index of a character + * @param direction: 1 or -1 + */ + searchWordBoundary(selectionStart: number, direction: number): number; + + /** + * Selects a word based on the index + * @param selectionStart Index of a character + */ + selectWord(selectionStart: number): void; + /** + * Selects a line based on the index + * @param selectionStart Index of a character + */ + selectLine(selectionStart: number): void; + + /** + * Enters editing state + */ + enterEditing(): IText; + + /** + * Initializes "mousemove" event handler + */ + initMouseMoveHandler(): void; + /** + * Exits from editing state + * @return thisArg + * @chainable + */ + exitEditing(): IText; + + /** + * Inserts a character where cursor is (replacing selection if one exists) + * @param _chars Characters to insert + */ + insertChars(_chars: string, useCopiedStyle?: boolean): void; + /** + * Inserts new style object + * @param lineIndex Index of a line + * @param charIndex Index of a char + * @param isEndOfLine True if it's end of line + */ + insertNewlineStyleObject(lineIndex: number, charIndex: number, isEndOfLine: boolean): void; + + /** + * Inserts style object for a given line/char index + * @param lineIndex Index of a line + * @param charIndex Index of a char + * @param [style] Style object to insert, if given + */ + insertCharStyleObject(lineIndex: number, charIndex: number, isEndOfLine: boolean): void; + + /** + * Inserts style object(s) + * @param _chars Characters at the location where style is inserted + * @param isEndOfLine True if it's end of line + * @param [useCopiedStyle] Style to insert + */ + insertStyleObjects(_chars: string, isEndOfLine: boolean, useCopiedStyle?: boolean): void; + + /** + * Shifts line styles up or down + * @param lineIndex Index of a line + * @param offset Can be -1 or +1 + */ + shiftLineStyles(lineIndex: number, offset: number): void; + + /** + * Removes style object + * @param isBeginningOfLine True if cursor is at the beginning of line + * @param [index] Optional index. When not given, current selectionStart is used. + */ + removeStyleObject(isBeginningOfLine: boolean, index?: number): void; + /** + * Inserts new line + */ + insertNewline(): void; + + /** + * Returns fabric.IText instance from an object representation + * @param object Object to create an instance from + */ + static fromObject(object: any): IText; +} + +interface ITriangleOptions extends IObjectOptions { } +export class Triangle extends Object { + /** + * Constructor + * @param [options] Options object + */ + constructor(options?: ITriangleOptions); + + /** + * Returns complexity of an instance + * @return complexity of this instance + */ + complexity(): number; + /** + * Returns SVG representation of an instance + * @param [reviver] Method for further parsing of svg representation. + * @return svg representation of an instance + */ + toSVG(reviver?: Function): string; + + /** + * Returns Triangle instance from an object representation + * @param object Object to create an instance from + */ + static fromObject(object: any): Triangle; +} + +//////////////////////////////////////////////////////////// +// Filters +//////////////////////////////////////////////////////////// +interface IAllFilters { + BaseFilter: { + /** + * Constructor + * @param [options] Options object + */ + new (options?: any): IBaseFilter; + }; + Blend: { + /** + * Constructor + * @param [options] Options object + */ + new (options?: { color?: string; mode?: string; alpha?: number; image?: Image }): IBlendFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IBlendFilter + }; + Brightness: { + new (options?: { + /** + * Value to brighten the image up (0..255) + * @default 0 + */ + brightness: number + }): IBrightnessFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IBrightnessFilter + }; + Convolute: { + new (options?: { + opaque?: boolean, + /** Filter matrix */ + matrix?: number[], + }): IConvoluteFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IConvoluteFilter + }; + GradientTransparency: { + new (options?: { + /** @default 100 */ + threshold?: number; + }): IGradientTransparencyFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IGradientTransparencyFilter + }; + Grayscale: { + new (options?: any): IGrayscaleFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IGrayscaleFilter + }; + Invert: { + /** + * Constructor + * @param [options] Options object + */ + new (options?: any): IInvertFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IInvertFilter + }; + Mask: { + new (options?: { + /** Mask image object */ + mask?: Image, + /** + * Rgb channel (0, 1, 2 or 3) + * @default 0 + */ + channel: number, + }): IMaskFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IMaskFilter + }; + Multiply: { + new (options?: { + /** + * Color to multiply the image pixels with + * @default #000000 + */ + color: string; + }): IMultiplyFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IMultiplyFilter + }; + Noise: { + new (options?: { + /** @default 0 */ + noise: number, + }): INoiseFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): INoiseFilter + }; + Pixelate: { + new (options?: { + /** + * Blocksize for pixelate + * @default 4 + */ + blocksize?: number, + }): IPixelateFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IPixelateFilter + }; + RemoveWhite: { + new (options?: { + /** @default 30 */ + threshold?: number, + /** @default 20 */ + distance?: number, + }): IRemoveWhiteFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IRemoveWhiteFilter + }; + Resize: { + new (options?: any): IResizeFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IResizeFilter + }; + Sepia2: { + new (options?: any): ISepia2Filter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): ISepia2Filter + }; + Sepia: { + new (options?: any): ISepiaFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): ISepiaFilter + }; + Tint: { + new (options?: { + /** + * Color to tint the image with + * @default #000000 + */ + color?: string; + /** Opacity value that controls the tint effect's transparency (0..1) */ + opacity?: number; + }): ITintFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): ITintFilter + }; +} +interface IBaseFilter { + /** + * Sets filter's properties from options + * @param [options] Options object + */ + setOptions(options?: any): void; + /** + * Returns object representation of an instance + */ + toObject(): any; + /** + * Returns a JSON representation of an instance + */ + toJSON(): string; +} +interface IBlendFilter extends IBaseFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface IBrightnessFilter extends IBaseFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface IConvoluteFilter extends IBaseFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface IGradientTransparencyFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface IGrayscaleFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface IInvertFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface IMaskFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface IMultiplyFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface INoiseFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface IPixelateFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface IRemoveWhiteFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface IResizeFilter { + /** + * Resize type + */ + resizeType: string; + + /** + * Scale factor for resizing, x axis + */ + scaleX: number; + + /** + * Scale factor for resizing, y axis + */ + scaleY: number; + + /** + * LanczosLobes parameter for lanczos filter + */ + lanczosLobes: number; + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface ISepiaFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface ISepia2Filter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface ITintFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} + +//////////////////////////////////////////////////////////// +// Brushes +//////////////////////////////////////////////////////////// +export class BaseBrush { + /** + * Color of a brush + */ + color: string; + + /** + * Width of a brush + */ + width: number; + + /** + * Shadow object representing shadow of this shape. + * Backwards incompatibility note: This property replaces "shadowColor" (String), "shadowOffsetX" (Number), + * "shadowOffsetY" (Number) and "shadowBlur" (Number) since v1.2.12 + */ + shadow: Shadow|string; + /** + * Line endings style of a brush (one of "butt", "round", "square") + */ + strokeLineCap: string; + + /** + * Corner style of a brush (one of "bevil", "round", "miter") + */ + strokeLineJoin: string; + + /** + * Stroke Dash Array. + */ + strokeDashArray: any[]; + + /** + * Sets shadow of an object + * @param [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)") + */ + setShadow(options: string|any): BaseBrush; +} + +export class CircleBrush extends BaseBrush { + /** + * Width of a brush + */ + width: number; + /** + * Invoked inside on mouse down and mouse move + */ + drawDot(pointer: any): void; + + /** + * @return Just added pointer point + */ + addPoint(pointer: any): Point; +} + +export class SprayBrush extends BaseBrush { + /** + * Width of a brush + */ + width: number; + /** + * Density of a spray (number of dots per chunk) + */ + density: number; + + /** + * Width of spray dots + */ + dotWidth: number; + /** + * Width variance of spray dots + */ + dotWidthVariance: number; + + /** + * Whether opacity of a dot should be random + */ + randomOpacity: boolean; + /** + * Whether overlapping dots (rectangles) should be removed (for performance reasons) + */ + optimizeOverlapping: boolean; + + addSprayChunk(pointer: any): void; +} +export class PatternBrush extends PencilBrush { + getPatternSrc(): HTMLCanvasElement; + + getPatternSrcFunction(): string; + + /** + * Creates "pattern" instance property + */ + getPattern(): any; + /** + * Creates path + */ + createPath(pathData: string): Path; +} +export class PencilBrush extends BaseBrush { + /** + * Converts points to SVG path + * @param points Array of points + */ + convertPointsToSVGPath(points: Array<{ x: number; y: number }>, minX?: number, minY?: number): string[]; + + /** + * Creates fabric.Path object to add on canvas + * @param pathData Path data + */ + createPath(pathData: string): Path; +} + +/////////////////////////////////////////////////////////////////////////////// +// Fabric util Interface +////////////////////////////////////////////////////////////////////////////// +interface IUtilAnimationOptions { + /** + * Starting value + */ + startValue?: number; + /** + * Ending value + */ + endValue?: number; + /** + * Value to modify the property by + */ + byValue: number; + /** + * Duration of change (in ms) + */ + duration?: number; + /** + * Callback; invoked on every value change + */ + onChange?: Function; + /** + * Callback; invoked when value change is completed + */ + onComplete?: Function; + /** + * Easing function + */ + easing?: Function; +} +interface IUtilAnimation { + /** + * Changes value from one to another within certain period of time, invoking callbacks as value is being changed. + * @param [options] Animation options + */ + animate(options?: IUtilAnimationOptions): void; + /** + * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/ + * In order to get a precise start time, `requestAnimFrame` should be called as an entry into the method + * @param callback Callback to invoke + */ + requestAnimFrame(callback: Function): void; +} + +type IUtilAminEaseFunction = (t: number, b: number, c: number, d: number) => number; + +interface IUtilAnimEase { + easeInBack: IUtilAminEaseFunction; + easeInBounce: IUtilAminEaseFunction; + easeInCirc: IUtilAminEaseFunction; + easeInCubic: IUtilAminEaseFunction; + easeInElastic: IUtilAminEaseFunction; + easeInExpo: IUtilAminEaseFunction; + easeInOutBack: IUtilAminEaseFunction; + easeInOutBounce: IUtilAminEaseFunction; + easeInOutCirc: IUtilAminEaseFunction; + easeInOutCubic: IUtilAminEaseFunction; + easeInOutElastic: IUtilAminEaseFunction; + easeInOutExpo: IUtilAminEaseFunction; + easeInOutQuad: IUtilAminEaseFunction; + easeInOutQuart: IUtilAminEaseFunction; + easeInOutQuint: IUtilAminEaseFunction; + easeInOutSine: IUtilAminEaseFunction; + easeInQuad: IUtilAminEaseFunction; + easeInQuart: IUtilAminEaseFunction; + easeInQuint: IUtilAminEaseFunction; + easeInSine: IUtilAminEaseFunction; + easeOutBack: IUtilAminEaseFunction; + easeOutBounce: IUtilAminEaseFunction; + easeOutCirc: IUtilAminEaseFunction; + easeOutCubic: IUtilAminEaseFunction; + easeOutElastic: IUtilAminEaseFunction; + easeOutExpo: IUtilAminEaseFunction; + easeOutQuad: IUtilAminEaseFunction; + easeOutQuart: IUtilAminEaseFunction; + easeOutQuint: IUtilAminEaseFunction; + easeOutSine: IUtilAminEaseFunction; +} + +interface IUtilArc { + /** + * Draws arc + */ + drawArc(ctx: CanvasRenderingContext2D, fx: number, fy: number, coords: number[]): void; + /** + * Calculate bounding box of a elliptic-arc + * @param fx start point of arc + * @param rx horizontal radius + * @param ry vertical radius + * @param rot angle of horizontal axe + * @param large 1 or 0, whatever the arc is the big or the small on the 2 points + * @param sweep 1 or 0, 1 clockwise or counterclockwise direction + * @param tx end point of arc + */ + getBoundsOfArc(fx: number, fy: number, rx: number, ry: number, rot: number, large: number, sweep: number, tx: number, ty: number): Point[]; + /** + * Calculate bounding box of a beziercurve + * @param x0 starting point + * @param x1 first control point + * @param x2 secondo control point + * @param x3 end of beizer + */ + getBoundsOfCurve(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): Point[]; +} + +interface IUtilDomEvent { + /** + * Cross-browser wrapper for getting event's coordinates + * @param event Event object + * @param upperCanvasEl <canvas> element on which object selection is drawn + */ + getPointer(event: Event, upperCanvasEl: HTMLCanvasElement): Point; + + /** + * Adds an event listener to an element + */ + addListener(element: HTMLElement, eventName: string, handler: Function): void; + + /** + * Removes an event listener from an element + */ + removeListener(element: HTMLElement, eventName: string, handler: Function): void; +} + +interface IUtilDomMisc { + /** + * Takes id and returns an element with that id (if one exists in a document) + */ + getById(id: string|HTMLElement): HTMLElement; + /** + * Converts an array-like object (e.g. arguments or NodeList) to an array + */ + toArray(arrayLike: any): any[]; + /** + * Creates specified element with specified attributes + * @param tagName Type of an element to create + * @param [attributes] Attributes to set on an element + * @return Newly created element + */ + makeElement(tagName: string, attributes?: any): HTMLElement; + /** + * Adds class to an element + * @param element Element to add class to + * @param className Class to add to an element + */ + addClass(element: HTMLElement, classname: string): void; + /** + * Wraps element with another element + * @param element Element to wrap + * @param wrapper Element to wrap with + * @param [attributes] Attributes to set on a wrapper + */ + wrapElement(element: HTMLElement, wrapper: HTMLElement|string, attributes?: any): HTMLElement; + /** + * Returns element scroll offsets + * @param element Element to operate on + * @param upperCanvasEl Upper canvas element + */ + getScrollLeftTop(element: HTMLElement, upperCanvasEl: HTMLElement): { left: number; right: number; }; + /** + * Returns offset for a given element + * @param element Element to get offset for + */ + getElementOffset(element: HTMLElement): { left: number; right: number; }; + /** + * Returns style attribute value of a given element + * @param element Element to get style attribute for + * @param attr Style attribute to get for element + */ + getElementStyle(elment: HTMLElement, attr: string): string; + /** + * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading + * @param url URL of a script to load + * @param callback Callback to execute when script is finished loading + */ + getScript(url: string, callback: Function): void; + /** + * Makes element unselectable + * @param element Element to make unselectable + */ + makeElementUnselectable(element: HTMLElement): HTMLElement; + /** + * Makes element selectable + * @param element Element to make selectable + */ + makeElementSelectable(element: HTMLElement): HTMLElement; +} + +interface IUtilDomRequest { + /** + * Cross-browser abstraction for sending XMLHttpRequest + * @param url URL to send XMLHttpRequest to + */ + request(url: string, options?: { + /** @default "GET" */ + method?: string, + /** Callback to invoke when request is completed */ + onComplete: Function, + }): XMLHttpRequest; +} + +interface IUtilDomStyle { + /** + * Cross-browser wrapper for setting element's style + */ + setStyle(element: HTMLElement, styles: any): HTMLElement; +} + +interface IUtilArray { + /** + * Invokes method on all items in a given array + * @param array Array to iterate over + * @param method Name of a method to invoke + */ + invoke(array: any[], method: string): any[]; + /** + * Finds minimum value in array (not necessarily "first" one) + * @param array Array to iterate over + */ + min(array: any[], byProperty: string): any; + /** + * Finds maximum value in array (not necessarily "first" one) + * @param array Array to iterate over + */ + max(array: any[], byProperty: string): any; +} + +interface IUtilClass { + /** + * Helper for creation of "classes". + * @param [parent] optional "Class" to inherit from + * @param [properties] Properties shared by all instances of this class + * (be careful modifying objects defined here as this would affect all instances) + */ + createClass(parent: Function, properties?: any): void; + /** + * Helper for creation of "classes". + * @param [properties] Properties shared by all instances of this class + * (be careful modifying objects defined here as this would affect all instances) + */ + createClass(properties?: any): void; +} + +interface IUtilObject { + /** + * Copies all enumerable properties of one object to another + * @param destination Where to copy to + * @param source Where to copy from + */ + extend(destination: any, source: any): any; + + /** + * Creates an empty object and copies all enumerable properties of another object to it + * @param object Object to clone + */ + clone(object: any): any; +} + +interface IUtilString { + /** + * Camelizes a string + * @param string String to camelize + */ + camelize(string: string): string; + + /** + * Capitalizes a string + * @param string String to capitalize + * @param [firstLetterOnly] If true only first letter is capitalized + * and other letters stay untouched, if false first letter is capitalized + * and other letters are converted to lowercase. + */ + capitalize(string: string, firstLetterOnly: boolean): string; + + /** + * Escapes XML in a string + * @param string String to escape + */ + escapeXml(string: string): string; +} + +interface IUtilMisc { + /** + * Removes value from an array. + * Presence of value (and its position in an array) is determined via `Array.prototype.indexOf` + */ + removeFromArray(array: any[], value: any): any[]; + + /** + * Returns random number between 2 specified ones. + * @param min lower limit + * @param max upper limit + */ + getRandomInt(min: number, max: number): number; + + /** + * Transforms degrees to radians. + * @param degrees value in degrees + */ + degreesToRadians(degrees: number): number; + + /** + * Transforms radians to degrees. + * @param radians value in radians + */ + radiansToDegrees(radians: number): number; + + /** + * Rotates `point` around `origin` with `radians` + * @param point The point to rotate + * @param origin The origin of the rotation + * @param radians The radians of the angle for the rotation + */ + rotatePoint(point: Point, origin: Point, radians: number): Point; + + /** + * Rotates `vector` with `radians` + * @param vector The vector to rotate (x and y) + * @param radians The radians of the angle for the rotation + */ + rotateVector(vector: { x: number, y: number }, radians: number): { x: number, y: number }; + + /** + * Apply transform t to point p + * @param p The point to transform + * @param t The transform + * @param [ignoreOffset] Indicates that the offset should not be applied + */ + transformPoint(p: Point, t: any[], ignoreOffset?: boolean): Point; + + /** + * Invert transformation t + * @param t The transform + */ + invertTransform(t: any[]): any[]; + + /** + * A wrapper around Number#toFixed, which contrary to native method returns number, not string. + * @param number number to operate on + * @param fractionDigits number of fraction digits to "leave" + */ + toFixed(number: number, fractionDigits: number): number; + + /** + * Converts from attribute value to pixel value if applicable. + * Returns converted pixels or original value not converted. + * @param value number to operate on + */ + parseUnit(value: number|string, fontSize?: number): number|string; + + /** + * Function which always returns `false`. + */ + falseFunction(): boolean; + + /** + * Returns klass "Class" object of given namespace + * @param type Type of object (eg. 'circle') + * @param namespace Namespace to get klass "Class" object from + */ + getKlass(type: string, namespace: string): any; + + /** + * Returns object of given namespace + * @param namespace Namespace string e.g. 'fabric.Image.filter' or 'fabric' + */ + resolveNamespace(namespace: string): any; + + /** + * Loads image element from given url and passes it to a callback + * @param url URL representing an image + * @param callback Callback; invoked with loaded image + * @param [context] Context to invoke callback in + * @param [crossOrigin] crossOrigin value to set image element to + */ + loadImage(url: string, callback: (image: HTMLImageElement) => {}, context?: any, crossOrigin?: boolean): void; + + /** + * Creates corresponding fabric instances from their object representations + * @param objects Objects to enliven + * @param callback Callback to invoke when all objects are created + * @param namespace Namespace to get klass "Class" object from + * @param reviver Method for further parsing of object elements, called after each fabric object created. + */ + enlivenObjects(objects: any[], callback: Function, namespace: string, reviver?: Function): void; + + /** + * Groups SVG elements (usually those retrieved from SVG document) + * @param elements SVG elements to group + * @param [options] Options object + */ + groupSVGElements(elements: any[], options?: any, path?: any): PathGroup; + + /** + * Populates an object with properties of another object + * @param source Source object + * @param destination Destination object + * @param properties Propertie names to include + */ + populateWithProperties(source: any, destination: any, properties: any): void; + + /** + * Draws a dashed line between two points + * This method is used to draw dashed line around selection area. + * @param ctx context + * @param x start x coordinate + * @param y start y coordinate + * @param x2 end x coordinate + * @param y2 end y coordinate + * @param da dash array pattern + */ + drawDashedLine(ctx: CanvasRenderingContext2D, x: number, y: number, x2: number, y2: number, da: any[]): void; + + /** + * Creates canvas element and initializes it via excanvas if necessary + * @param [canvasEl] optional canvas element to initialize; + * when not given, element is created implicitly + */ + createCanvasElement(canvasEl?: HTMLCanvasElement): HTMLCanvasElement; + + /** + * Creates image element (works on client and node) + */ + createImage(): HTMLImageElement; + + /** + * Creates accessors (getXXX, setXXX) for a "class", based on "stateProperties" array + * @param klass "Class" to create accessors for + */ + createAccessors(klass: any): any; + + /** + * @param receiver Object implementing `clipTo` method + * @param ctx Context to clip + */ + clipContext(receiver: Object, ctx: CanvasRenderingContext2D): void; + + /** + * Multiply matrix A by matrix B to nest transformations + * @param a First transformMatrix + * @param b Second transformMatrix + */ + multiplyTransformMatrices(a: number[], b: number[]): number[]; + + /** + * Decomposes standard 2x2 matrix into transform componentes + * @param a transformMatrix + */ + qrDecompose(a: number[]): { angle: number, scaleX: number, scaleY: number, skewX: number, skewY: number, translateX: number, translateY: number }; + + /** + * Returns string representation of function body + * @param fn Function to get body of + */ + getFunctionBody(fn: Function): string; + + /** + * Returns true if context has transparent pixel + * at specified location (taking tolerance into account) + * @param ctx context + * @param x x coordinate + * @param y y coordinate + * @param tolerance Tolerance + */ + isTransparent(ctx: CanvasRenderingContext2D, x: number, y: number, tolerance: number): boolean; +} + +export const util: IUtil; +interface IUtil extends IUtilAnimation, IUtilArc, IObservable, IUtilDomEvent, IUtilDomMisc, + IUtilDomRequest, IUtilDomStyle, IUtilClass, IUtilMisc { + ease: IUtilAnimEase; + array: IUtilArray; + object: IUtilObject; + string: IUtilString; +} diff --git a/types/fabric/index.d.ts b/types/fabric/index.d.ts index 8b7c007cd7..a0fa06629e 100644 --- a/types/fabric/index.d.ts +++ b/types/fabric/index.d.ts @@ -6,4429 +6,4 @@ // Tiger Oakes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 - -export as namespace fabric; - -export const isLikelyNode: boolean; -export const isTouchSupported: boolean; - -///////////////////////////////////////////////////////////// -// farbic Functions -///////////////////////////////////////////////////////////// - -export function createCanvasForNode(width: number, height: number): Canvas; - -// Parse -// ---------------------------------------------------------- -/** - * Creates markup containing SVG referenced elements like patterns, gradients etc. - * @param canvas instance of fabric.Canvas - */ -export function createSVGRefElementsMarkup(canvas: StaticCanvas): string; -/** - * Creates markup containing SVG font faces - * @param objects Array of fabric objects - */ -export function createSVGFontFacesMarkup(objects: Object[]): string; -/** - * Takes string corresponding to an SVG document, and parses it into a set of fabric objects - * @param [reviver] Method for further parsing of SVG elements, called after each fabric object created. - */ -export function loadSVGFromString(string: string, callback: (results: Object[], options: any) => void, reviver?: Function): void; -/** - * Takes url corresponding to an SVG document, and parses it into a set of fabric objects. - * Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy) - * @param [reviver] Method for further parsing of SVG elements, called after each fabric object created. - */ -export function loadSVGFromURL(url: string, callback: (results: Object[], options: any) => void, reviver?: Function): void; -/** - * Returns CSS rules for a given SVG document - * @param doc SVG document to parse - */ -export function getCSSRules(doc: SVGElement): any; - -export function parseElements(elements: any[], callback: Function, options: any, reviver?: Function): void; -/** - * Parses "points" attribute, returning an array of values - * @param points points attribute string - */ -export function parsePointsAttribute(points: string): any[]; -/** - * Parses "style" attribute, retuning an object with values - * @param element Element to parse - */ -export function parseStyleAttribute(element: SVGElement): any; -/** - * Transforms an array of svg elements to corresponding fabric.* instances - * @param elements Array of elements to parse - * @param callback Being passed an array of fabric instances (transformed from SVG elements) - * @param [options] Options object - * @param [reviver] Method for further parsing of SVG elements, called after each fabric object created. - */ -export function parseElements(elements: SVGElement[], callback: Function, options?: any, reviver?: Function): void; -/** - * Returns an object of attributes' name/value, given element and an array of attribute names; - * Parses parent "g" nodes recursively upwards. - * @param element Element to parse - * @param attributes Array of attributes to parse - */ -export function parseAttributes(element: HTMLElement, attributes: string[], svgUid?: string): { [key: string]: string }; -/** - * Parses an SVG document, returning all of the gradient declarations found in it - * @param doc SVG document to parse - */ -export function getGradientDefs(doc: SVGElement): { [key: string]: any }; -/** - * Parses a short font declaration, building adding its properties to a style object - * @param value font declaration - * @param oStyle definition - */ -export function parseFontDeclaration(value: string, oStyle: any): void; -/** - * Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback - * @param doc SVG document to parse - * @param callback Callback to call when parsing is finished; It's being passed an array of elements (parsed from a document). - * @param [reviver] Method for further parsing of SVG elements, called after each fabric object created. - */ -export function parseSVGDocument(doc: SVGElement, callback: (results: Object[], options: any) => void, reviver?: Function): void; -/** - * Parses "transform" attribute, returning an array of values - * @param attributeValue String containing attribute value - */ -export function parseTransformAttribute(attributeValue: string): number[]; - -// fabric Log -// --------------- -/** - * Wrapper around `console.log` (when available) - */ -export function log(...values: any[]): void; -/** - * Wrapper around `console.warn` (when available) - */ -export function warn(...values: any[]): void; - -/////////////////////////////////////////////////////////////////////////////// -// Data Object Interfaces - These intrface are not specific part of fabric, -// They are just helpful for for defining function paramters -////////////////////////////////////////////////////////////////////////////// -interface IDataURLOptions { - /** - * The format of the output image. Either "jpeg" or "png" - */ - format?: string; - /** - * Quality level (0..1). Only used for jpeg - */ - quality?: number; - /** - * Multiplier to scale by - */ - multiplier?: number; - /** - * Cropping left offset. Introduced in v1.2.14 - */ - left?: number; - /** - * Cropping top offset. Introduced in v1.2.14 - */ - top?: number; - /** - * Cropping width. Introduced in v1.2.14 - */ - width?: number; - /** - * Cropping height. Introduced in v1.2.14 - */ - height?: number; -} - -interface IEvent { - e: Event; - target?: Object; -} - -interface IFillOptions { - /** - * options.source Pattern source - */ - source: string | HTMLImageElement; - /** - * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat) - */ - repeat?: string; - /** - * Pattern horizontal offset from object's left/top corner - */ - offsetX?: number; - /** - * Pattern vertical offset from object's left/top corner - */ - offsetY?: number; -} - -interface IToSVGOptions { - /** - * If true xml tag is not included - */ - suppressPreamble: boolean; - /** - * SVG viewbox object - */ - viewBox: IViewBox; - /** - * Encoding of SVG output - */ - encoding: string; -} - -interface IViewBox { - /** - * x-cooridnate of viewbox - */ - x: number; - /** - * y-coordinate of viewbox - */ - y: number; - /** - * Width of viewbox - */ - width: number; - /** - * Height of viewbox - */ - height: number; -} - -/////////////////////////////////////////////////////////////////////////////// -// Mixins Interfaces -////////////////////////////////////////////////////////////////////////////// -interface ICollection { - /** - * Adds objects to collection, then renders canvas (if `renderOnAddRemove` is not `false`) - * Objects should be instances of (or inherit from) fabric.Object - * @param object Zero or more fabric instances - */ - add(...object: Object[]): T; - - /** - * Inserts an object into collection at specified index, then renders canvas (if `renderOnAddRemove` is not `false`) - * An object should be an instance of (or inherit from) fabric.Object - * @param object Object to insert - * @param index Index to insert object at - * @param nonSplicing When `true`, no splicing (shifting) of objects occurs - * @return thisArg - * @chainable - */ - insertAt(object: Object, index: number, nonSplicing: boolean): T; - - /** - * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`) - * @param object Zero or more fabric instances - * @return thisArg - * @chainable - */ - remove(...object: Object[]): T; - - /** - * Executes given function for each object in this group - * @param context Context (aka thisObject) - * @return thisArg - */ - forEachObject(callback: (element: Object, index: number, array: Object[]) => void, context?: any): T; - - /** - * Returns an array of children objects of this instance - * Type parameter introduced in 1.3.10 - * @param [type] When specified, only objects of this type are returned - */ - getObjects(type?: string): Object[]; - - /** - * Returns object at specified index - * @return thisArg - */ - item(index: number): T; - - /** - * Returns true if collection contains no objects - * @return true if collection is empty - */ - isEmpty(): boolean; - - /** - * Returns a size of a collection (i.e: length of an array containing its objects) - * @return Collection size - */ - size(): number; - - /** - * Returns true if collection contains an object - * @param object Object to check against - * @return `true` if collection contains an object - */ - contains(object: Object): boolean; - - /** - * Returns number representation of a collection complexity - * @return complexity - */ - complexity(): number; -} - -interface IObservable { - /** - * Observes specified event - * @param eventName Event name (eg. 'after:render') - * @param handler Function that receives a notification when an event of the specified type occurs - */ - on(eventName: string, handler: (e: IEvent) => void): T; - - /** - * Observes specified event - * @param eventName Object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) - */ - on(events: {[eventName: string]: (e: IEvent) => void}): T; - /** - * Fires event with an optional options object - * @param eventName Event name to fire - * @param [options] Options object - */ - trigger(eventName: string, options?: any): T; - /** - * Stops event observing for a particular event handler. Calling this method - * without arguments removes all handlers for all events - * @param eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) - * @param handler Function to be deleted from EventListeners - */ - off(eventName?: string|any, handler?: (e: IEvent) => void): T; -} - -interface Callbacks { - /** Invoked on completion */ - onComplete?: Function; - /** Invoked on every step of animation */ - onChange?: Function; -} - -// animation mixin -// ---------------------------------------------------- -interface ICanvasAnimation { - FX_DURATION: number; - /** - * Centers object horizontally with animation. - * @param object Object to center - */ - fxCenterObjectH(object: Object, callbacks?: Callbacks): T; - - /** - * Centers object vertically with animation. - * @param object Object to center - */ - fxCenterObjectV(object: Object, callbacks?: Callbacks): T; - - /** - * Same as `fabric.Canvas#remove` but animated - * @param object Object to remove - * @chainable - */ - fxRemove(object: Object): T; -} -interface IObjectAnimation { - /** - * Animates object's properties - * object.animate('left', ..., {duration: ...}); - * @param property Property to animate - * @param value Value to animate property - * @param options The animation options - */ - animate(property: string, value: number|string, options?: IAnimationOptions): Object; - /** - * Animates object's properties - * object.animate({ left: ..., top: ... }, { duration: ... }); - * @param properties Properties to animate - * @param value Options object - */ - animate(properties: any, options?: IAnimationOptions): Object; -} -interface IAnimationOptions { - /** - * Allows to specify starting value of animatable property (if we don't want current value to be used). - */ - from?: string|number; - /** - * Defaults to 500 (ms). Can be used to change duration of an animation. - */ - duration?: number; - /** - * Callback; invoked on every value change - */ - onChange?: Function; - /** - * Callback; invoked when value change is completed - */ - onComplete?: Function; - - /** - * Easing function. Default: fabric.util.ease.easeInSine - */ - easing?: Function; - /** - * Value to modify the property by, default: end - start - */ - by?: number; -} - -/////////////////////////////////////////////////////////////////////////////// -// General Fabric Interfaces -////////////////////////////////////////////////////////////////////////////// -export class Color { - /** - * Color class - * The purpose of Color is to abstract and encapsulate common color operations; - * @param color optional in hex or rgb(a) format - */ - constructor(color?: string); - - /** - * Returns source of this color (where source is an array representation; ex: [200, 200, 100, 1]) - */ - getSource(): number[]; - - /** - * Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1]) - */ - setSource(source: number[]): void; - - /** - * Returns color represenation in RGB format ex: rgb(0-255,0-255,0-255) - */ - toRgb(): string; - - /** - * Returns color represenation in RGBA format ex: rgba(0-255,0-255,0-255,0-1) - */ - toRgba(): string; - - /** - * Returns color represenation in HSL format ex: hsl(0-360,0%-100%,0%-100%) - */ - toHsl(): string; - - /** - * Returns color represenation in HSLA format ex: hsla(0-360,0%-100%,0%-100%,0-1) - */ - toHsla(): string; - - /** - * Returns color represenation in HEX format ex: FF5555 - */ - toHex(): string; - - /** - * Gets value of alpha channel for this color - */ - getAlpha(): number; - - /** - * Sets value of alpha channel for this color - * @param alpha Alpha value 0-1 - */ - setAlpha(alpha: number): void; - - /** - * Transforms color to its grayscale representation - */ - toGrayscale(): Color; - - /** - * Transforms color to its black and white representation - */ - toBlackWhite(threshold: number): Color; - /** - * Overlays color with another color - */ - overlayWith(otherColor: string|Color): Color; - - /** - * Returns new color object, when given a color in RGB format - * @param color Color value ex: rgb(0-255,0-255,0-255) - */ - static fromRgb(color: string): Color; - /** - * Returns new color object, when given a color in RGBA format - * @param color Color value ex: rgb(0-255,0-255,0-255) - */ - static fromRgba(color: string): Color; - /** - * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in RGB or RGBA format - * @param color Color value ex: rgb(0-255,0-255,0-255), rgb(0%-100%,0%-100%,0%-100%) - */ - static sourceFromRgb(color: string): number[]; - /** - * Returns new color object, when given a color in HSL format - * @param color Color value ex: hsl(0-260,0%-100%,0%-100%) - */ - static fromHsl(color: string): Color; - /** - * Returns new color object, when given a color in HSLA format - * @param color Color value ex: hsl(0-260,0%-100%,0%-100%) - */ - static fromHsla(color: string): Color; - /** - * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HSL or HSLA format. - * @param color Color value ex: hsl(0-360,0%-100%,0%-100%) or hsla(0-360,0%-100%,0%-100%, 0-1) - */ - static sourceFromHsl(color: string): number[]; - /** - * Returns new color object, when given a color in HEX format - * @param color Color value ex: FF5555 - */ - static fromHex(color: string): Color; - - /** - * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HEX format - * @param color ex: FF5555 - */ - static sourceFromHex(color: string): number[]; - /** - * Returns new color object, when given color in array representation (ex: [200, 100, 100, 0.5]) - */ - static fromSource(source: number[]): Color; -} - -interface IGradientOptions { - /** - * @param [options.type] Type of gradient 'radial' or 'linear' - */ - type?: string; - /** - * x-coordinate of start point - */ - x1?: number; - /** - * y-coordinate of start point - */ - y1?: number; - /** - * x-coordinate of end point - */ - x2?: number; - /** - * y-coordinate of end point - */ - y2?: number; - /** - * Radius of start point (only for radial gradients) - */ - r1?: number; - /** - * Radius of end point (only for radial gradients) - */ - r2?: number; - /** - * Color stops object eg. {0:string; 1:string; - */ - colorStops?: any; -} -interface IGradient extends IGradientOptions { - /** - * Adds another colorStop - * @param colorStop Object with offset and color - */ - addColorStop(colorStop: any): IGradient; - /** - * Returns object representation of a gradient - */ - toObject(): any; - /** - * Returns SVG representation of an gradient - * @param object Object to create a gradient for - * @param normalize Whether coords should be normalized - * @return SVG representation of an gradient (linear/radial) - */ - toSVG(object: Object, normalize?: boolean): string; - - /** - * Returns an instance of CanvasGradient - * @param ctx Context to render on - */ - toLive(ctx: CanvasRenderingContext2D, object?: PathGroup): CanvasGradient; -} -interface IGrandientStatic { - new (options?: IGradientOptions): IGradient; - /** - * Returns instance from an SVG element - * @param el SVG gradient element - */ - fromElement(el: SVGGradientElement, instance: Object): IGradient; - /** - * Returns instance from its object representation - * @param [options] Options object - */ - fromObject(obj: any, options: any[]): IGradient; -} - -export class Intersection { - constructor(status?: string); - - /** - * Appends a point to intersection - */ - appendPoint(point: Point): void; - /** - * Appends points to intersection - */ - appendPoints(points: Point[]): void; - - /** - * Checks if polygon intersects another polygon - */ - static intersectPolygonPolygon(points1: Point[], points2: Point[]): Intersection; - /** - * Checks if line intersects polygon - */ - static intersectLinePolygon(a1: Point, a2: Point, points: Point[]): Intersection; - /** - * Checks if one line intersects another - */ - static intersectLineLine(a1: Point, a2: Point, b1: Point, b2: Point): Intersection; - /** - * Checks if polygon intersects rectangle - */ - static intersectPolygonRectangle(points: Point[], r1: number, r2: number): Intersection; -} - -interface IPatternOptions { - /** - * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat) - */ - repeat: string; - - /** - * Pattern horizontal offset from object's left/top corner - */ - offsetX: number; - - /** - * Pattern vertical offset from object's left/top corner - */ - offsetY: number; - /** - * The source for the pattern - */ - source: string|HTMLImageElement; -} -export interface Pattern extends IPatternOptions {} -export class Pattern { - constructor(options?: IPatternOptions); - - initialise(options?: IPatternOptions): Pattern; - /** - * Returns an instance of CanvasPattern - */ - toLive(ctx: CanvasRenderingContext2D): Pattern; - - /** - * Returns object representation of a pattern - */ - toObject(): any; - /** - * Returns SVG representation of a pattern - */ - toSVG(object: Object): string; -} - -export class Point { - x: number; - y: number; - - constructor(x: number, y: number); - - /** - * Adds another point to this one and returns another one - */ - add(that: Point): Point; - - /** - * Adds another point to this one - */ - addEquals(that: Point): Point; - - /** - * Adds value to this point and returns a new one - */ - scalarAdd(scalar: number): Point; - - /** - * Adds value to this point - */ - scalarAddEquals(scalar: number): Point; - - /** - * Subtracts another point from this point and returns a new one - */ - subtract(that: Point): Point; - - /** - * Subtracts another point from this point - */ - subtractEquals(that: Point): Point; - - /** - * Subtracts value from this point and returns a new one - */ - scalarSubtract(scalar: number): Point; - - /** - * Subtracts value from this point - */ - scalarSubtractEquals(scalar: number): Point; - - /** - * Miltiplies this point by a value and returns a new one - */ - multiply(scalar: number): Point; - - /** - * Miltiplies this point by a value - */ - multiplyEquals(scalar: number): Point; - - /** - * Divides this point by a value and returns a new one - */ - divide(scalar: number): Point; - - /** - * Divides this point by a value - */ - divideEquals(scalar: number): Point; - - /** - * Returns true if this point is equal to another one - */ - eq(that: Point): Point; - - /** - * Returns true if this point is less than another one - */ - lt(that: Point): Point; - - /** - * Returns true if this point is less than or equal to another one - */ - lte(that: Point): Point; - - /** - * Returns true if this point is greater another one - */ - gt(that: Point): Point; - - /** - * Returns true if this point is greater than or equal to another one - */ - gte(that: Point): Point; - - /** - * Returns new point which is the result of linear interpolation with this one and another one - */ - lerp(that: Point, t: number): Point; - - /** - * Returns distance from this point and another one - */ - distanceFrom(that: Point): number; - - /** - * Returns the point between this point and another one - */ - midPointFrom(that: Point): Point; - - /** - * Returns a new point which is the min of this and another one - */ - min(that: Point): Point; - - /** - * Returns a new point which is the max of this and another one - */ - max(that: Point): Point; - - /** - * Returns string representation of this point - */ - toString(): string; - - /** - * Sets x/y of this point - */ - setXY(x: number, y: number): Point; - - /** - * Sets x/y of this point from another point - */ - setFromPoint(that: Point): Point; - - /** - * Swaps x/y of this point and another point - */ - swap(that: Point): Point; -} - -interface IShadowOptions { - /** - * Whether the shadow should affect stroke operations - */ - affectStrike: boolean; - /** - * Shadow blur - */ - blur: number; - /** - * Shadow color - */ - color: string; - /** - * Indicates whether toObject should include default values - */ - includeDefaultValues: boolean; - /** - * Shadow horizontal offset - */ - offsetX: number; - /** - * Shadow vertical offset - */ - offsetY: number; -} -export interface Shadow extends IShadowOptions {} -export class Shadow { - constructor(options?: IShadowOptions); - initialize(options?: IShadowOptions|string): Shadow; - /** - * Returns object representation of a shadow - */ - toObject(): any; - /** - * Returns a string representation of an instance, CSS3 text-shadow declaration - */ - toString(): string; - /** - * Returns SVG representation of a shadow - */ - toSVG(object: Object): string; - - /** - * Regex matching shadow offsetX, offsetY and blur, Static - */ - reOffsetsAndBlur: RegExp; - - static reOffsetsAndBlur: RegExp; -} - -/////////////////////////////////////////////////////////////////////////////// -// Canvas Interfaces -////////////////////////////////////////////////////////////////////////////// -interface ICanvasDimensions { - /** - * Width of canvas element - */ - width: number; - /** - * Height of canvas element - */ - height: number; -} -interface ICanvasDimensionsOptions { - /** - * Set the given dimensions only as canvas backstore dimensions - */ - backstoreOnly?: boolean; - /** - * Set the given dimensions only as css dimensions - */ - cssOnly?: boolean; -} - -interface IStaticCanvasOptions { - /** - * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas - */ - allowTouchScrolling?: boolean; - /** - * Indicates whether this canvas will use image smoothing, this is on by default in browsers - */ - imageSmoothingEnabled?: boolean; - - /** - * Indicates whether objects should remain in current stack position when selected. - * When false objects are brought to top and rendered as part of the selection group - */ - preserveObjectStacking?: boolean; - - /** - * The transformation (in the format of Canvas transform) which focuses the viewport - */ - viewportTransform?: number[]; - - freeDrawingColor?: string; - freeDrawingLineWidth?: number; - - /** - * Background color of canvas instance. - * Should be set via setBackgroundColor - */ - backgroundColor?: string|Pattern; - /** - * Background image of canvas instance. - * Should be set via setBackgroundImage - * Backwards incompatibility note: The "backgroundImageOpacity" and "backgroundImageStretch" properties are deprecated since 1.3.9. - */ - backgroundImage?: Image | string; - backgroundImageOpacity?: number; - backgroundImageStretch?: number; - /** - * Function that determines clipping of entire canvas area - * Being passed context as first argument. See clipping canvas area - */ - clipTo?(context: CanvasRenderingContext2D): void; - - /** - * Indicates whether object controls (borders/controls) are rendered above overlay image - */ - controlsAboveOverlay?: boolean; - - /** - * Indicates whether toObject/toDatalessObject should include default values - */ - includeDefaultValues?: boolean; - /** - * Overlay color of canvas instance. - * Should be set via setOverlayColor - */ - overlayColor?: string|Pattern; - /** - * Overlay image of canvas instance. - * Should be set via setOverlayImage - * Backwards incompatibility note: The "overlayImageLeft" and "overlayImageTop" properties are deprecated since 1.3.9. - */ - overlayImage?: Image; - overlayImageLeft?: number; - overlayImageTop?: number; - /** - * Indicates whether add, insertAt and remove should also re-render canvas. - * Disabling this option could give a great performance boost when adding/removing a lot of objects to/from canvas at once - * (followed by a manual rendering after addition/deletion) - */ - renderOnAddRemove?: boolean; - /** - * Indicates whether objects' state should be saved - */ - stateful?: boolean; -} -export interface StaticCanvas extends IObservable, IStaticCanvasOptions, ICollection, ICanvasAnimation {} -export class StaticCanvas { - /** - * Constructor - * @param element element to initialize instance on - * @param [options] Options object - */ - constructor(element: HTMLCanvasElement|string, options?: ICanvasOptions); - - /** - * Calculates canvas element offset relative to the document - * This method is also attached as "resize" event handler of window - */ - calcOffset(): this; - - /** - * Sets {@link fabric.StaticCanvas#overlayImage|overlay image} for this canvas - * @param image fabric.Image instance or URL of an image to set overlay to - * @param callback callback to invoke when image is loaded and set as an overlay - * @param [options] Optional options to set for the {@link fabric.Image|overlay image}. - */ - setOverlayImage(image: Image|string, callback: (img: HTMLImageElement) => void, options?: IImageOptions): this; - - /** - * Sets {@link fabric.StaticCanvas#backgroundImage|background image} for this canvas - * @param image fabric.Image instance or URL of an image to set background to - * @param callback Callback to invoke when image is loaded and set as background - * @param [options] Optional options to set for the {@link fabric.Image|background image}. - */ - setBackgroundImage(image: Image|string, callback?: (img: HTMLImageElement) => void, options?: IImageOptions): this; - - /** - * Sets {@link fabric.StaticCanvas#overlayColor|background color} for this canvas - * @param overlayColor Color or pattern to set background color to - * @param callback Callback to invoke when background color is set - */ - setOverlayColor(overlayColor: string|Pattern, callback: (pattern: Pattern | undefined) => void): this; - - /** - * Sets {@link fabric.StaticCanvas#backgroundColor|background color} for this canvas - * @param backgroundColor Color or pattern to set background color to - * @param callback Callback to invoke when background color is set - */ - setBackgroundColor(backgroundColor: string|Pattern, callback: (pattern: Pattern | undefined) => void): StaticCanvas; - - /** - * Returns canvas width (in px) - */ - getWidth(): number; - - /** - * Returns canvas height (in px) - */ - getHeight(): number; - - /** - * Sets width of this canvas instance - * @param value Value to set width to - * @param [options] Options object - */ - setWidth(value: number|string, options?: ICanvasDimensionsOptions): this; - - /** - * Sets height of this canvas instance - * @param value Value to set height to - * @param [options] Options object - */ - setHeight(value: number|string, options?: ICanvasDimensionsOptions): this; - - /** - * Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em) - * @param dimensions Object with width/height properties - * @param [options] Options object - */ - setDimensions(dimensions: ICanvasDimensions, options?: ICanvasDimensionsOptions): this; - - /** - * Returns canvas zoom level - */ - getZoom(): number; - - /** - * Sets viewport transform of this canvas instance - * @param vpt the transform in the form of context.transform - */ - setViewportTransform(vpt: number[]): this; - - /** - * Sets zoom level of this canvas instance, zoom centered around point - * @param point to zoom with respect to - * @param value to set zoom to, less than 1 zooms out - */ - zoomToPoint(point: Point, value: number): this; - - /** - * Sets zoom level of this canvas instance - * @param value to set zoom to, less than 1 zooms out - */ - setZoom(value: number): this; - - /** - * Pan viewport so as to place point at top left corner of canvas - * @param point to move to - */ - absolutePan(point: Point): this; - - /** - * Pans viewpoint relatively - * @param point (position vector) to move by - */ - relativePan(point: Point): this; - - /** - * Returns element corresponding to this instance - */ - getElement(): HTMLCanvasElement; - - /** - * Returns currently selected object, if any - */ - getActiveObject(): Object; - - /** - * Returns currently selected group of object, if any - */ - getActiveGroup(): Group; - - /** - * Clears specified context of canvas element - * @param ctx Context to clear - * @chainable - */ - clearContext(ctx: CanvasRenderingContext2D): this; - - /** - * Returns context of canvas where objects are drawn - */ - getContext(): CanvasRenderingContext2D; - - /** - * Clears all contexts (background, main, top) of an instance - */ - clear(): this; - - /** - * Renders both the top canvas and the secondary container canvas. - * @param [allOnTop] Whether we want to force all images to be rendered on the top canvas - * @chainable - */ - renderAll(allOnTop?: boolean): this; - - /** - * Method to render only the top canvas. - * Also used to render the group selection box. - * @chainable - */ - renderTop(): StaticCanvas; - - /** - * Returns coordinates of a center of canvas. - * Returned value is an object with top and left properties - */ - getCenter(): { top: number; left: number; }; - /** - * Centers object horizontally. - * You might need to call `setCoords` on an object after centering, to update controls area. - * @param object Object to center horizontally - */ - centerObjectH(object: Object): this; - - /** - * Centers object vertically. - * You might need to call `setCoords` on an object after centering, to update controls area. - * @param object Object to center vertically - */ - centerObjectV(object: Object): this; - - /** - * Centers object vertically and horizontally. - * You might need to call `setCoords` on an object after centering, to update controls area. - * @param object Object to center vertically and horizontally - */ - centerObject(object: Object): this; - - /** - * Returs dataless JSON representation of canvas - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - toDatalessJSON(propertiesToInclude?: string[]): string; - - /** - * Returns object representation of canvas - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - toObject(propertiesToInclude?: string[]): any; - - /** - * Returns dataless object representation of canvas - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - toDatalessObject(propertiesToInclude?: string[]): any; - - /** - * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true, - * a zoomed canvas will then produce zoomed SVG output. - */ - svgViewportTransformation: boolean; - - /** - * Returns SVG representation of canvas - * @param [options] Options object for SVG output - * @param [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation. - */ - toSVG(options: IToSVGOptions, reviver?: Function): string; - - /** - * Moves an object to the bottom of the stack of drawn objects - * @param object Object to send to back - * @chainable - */ - sendToBack(object: Object): this; - - /** - * Moves an object to the top of the stack of drawn objects - * @param object Object to send - * @chainable - */ - bringToFront(object: Object): this; - - /** - * Moves an object down in stack of drawn objects - * @param object Object to send - * @param [intersecting] If `true`, send object behind next lower intersecting object - * @chainable - */ - sendBackwards(object: Object): this; - - /** - * Moves an object up in stack of drawn objects - * @param object Object to send - * @param [intersecting] If `true`, send object in front of next upper intersecting object - * @chainable - */ - bringForward(object: Object): this; - /** - * Moves an object to specified level in stack of drawn objects - * @param object Object to send - * @param index Position to move to - * @chainable - */ - moveTo(object: Object, index: number): this; - - /** - * Clears a canvas element and removes all event listeners - */ - dispose(): this; - - /** - * Returns a string representation of an instance - */ - toString(): string; - - /** - * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately - * @param [options] Options object - */ - toDataURL(options?: IDataURLOptions): string; - - /** - * Provides a way to check support of some of the canvas methods - * (either those of HTMLCanvasElement itself, or rendering context) - * @param methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" - * @return `true` if method is supported (or at least exists), null` if canvas element or context can not be initialized - */ - supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; - - /** - * Populates canvas with data from the specified JSON. - * JSON format must conform to the one of toJSON formats - * @param json JSON string or object - * @param callback Callback, invoked when json is parsed - * and corresponding objects (e.g: {@link fabric.Image}) - * are initialized - * @param [reviver] Method for further parsing of JSON elements, called after each fabric object created. - */ - loadFromJSON(json: string|any, callback: () => void, reviver?: Function): this; - /** - * Clones canvas instance - * @param [callback] Receives cloned instance as a first argument - * @param [properties] Array of properties to include in the cloned canvas and children - */ - clone(callback: (canvas: StaticCanvas) => void, properties?: string[]): void; - - /** - * Clones canvas instance without cloning existing data. - * This essentially copies canvas dimensions, clipping properties, etc. - * but leaves data empty (so that you can populate it with your own) - * @param [callback] Receives cloned instance as a first argument - */ - cloneWithoutData(callback: (canvas: StaticCanvas) => void): void; - - /** - * Callback; invoked right before object is about to be scaled/rotated - */ - onBeforeScaleRotate(target: Object): void; - - // Functions from object straighten mixin - // -------------------------------------------------------------------------------------------------------------------------------- - - /** - * Straightens object, then rerenders canvas - * @param object Object to straighten - */ - straightenObject(object: Object): this; - - /** - * Same as straightenObject, but animated - * @param object Object to straighten - */ - fxStraightenObject(object: Object): this; - - static EMPTY_JSON: string; - /** - * Provides a way to check support of some of the canvas methods - * (either those of HTMLCanvasElement itself, or rendering context) - * @param methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" - */ - static supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; - /** - * Returns JSON representation of canvas - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - static toJSON(propertiesToInclude?: string[]): string; -} - -interface ICanvasOptions extends IStaticCanvasOptions { - /** - * When true, objects can be transformed by one side (unproportionally) - */ - uniScaleTransform?: boolean; - - /** - * When true, objects use center point as the origin of scale transformation. - * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). - */ - centeredScaling?: boolean; - - /** - * When true, objects use center point as the origin of rotate transformation. - * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). - */ - centeredRotation?: boolean; - - /** - * Indicates that canvas is interactive. This property should not be changed. - */ - interactive?: boolean; - - /** - * Indicates whether group selection should be enabled - */ - selection?: boolean; - - /** - * Color of selection - */ - selectionColor?: string; - - /** - * Default dash array pattern - * If not empty the selection border is dashed - */ - selectionDashArray?: any[]; - - /** - * Color of the border of selection (usually slightly darker than color of selection itself) - */ - selectionBorderColor?: string; - - /** - * Width of a line used in object/group selection - */ - selectionLineWidth?: number; - - /** - * Default cursor value used when hovering over an object on canvas - */ - hoverCursor?: string; - - /** - * Default cursor value used when moving an object on canvas - */ - moveCursor?: string; - - /** - * Default cursor value used for the entire canvas - */ - defaultCursor?: string; - - /** - * Cursor value used during free drawing - */ - freeDrawingCursor?: string; - - /** - * Cursor value used for rotation point - */ - rotationCursor?: string; - - /** - * Default element class that's given to wrapper (div) element of canvas - */ - containerClass?: string; - - /** - * When true, object detection happens on per-pixel basis rather than on per-bounding-box - */ - perPixelTargetFind?: boolean; - - /** - * Number of pixels around target pixel to tolerate (consider active) during object detection - */ - targetFindTolerance?: number; - - /** - * When true, target detection is skipped when hovering over canvas. This can be used to improve performance. - */ - skipTargetFind?: boolean; - - /** - * When true, mouse events on canvas (mousedown/mousemove/mouseup) result in free drawing. - * After mousedown, mousemove creates a shape, - * and then mouseup finalizes it and adds an instance of `fabric.Path` onto canvas. - */ - isDrawingMode?: boolean; -} -export interface Canvas extends StaticCanvas {} -export interface Canvas extends ICanvasOptions {} -export class Canvas { - /** - * Constructor - * @param element element to initialize instance on - * @param [options] Options object - */ - constructor(element: HTMLCanvasElement | string, options?: ICanvasOptions); - - _objects: Object[]; - - /** - * Checks if point is contained within an area of given object - * @param e Event object - * @param target Object to test against - */ - containsPoint(e: Event, target: Object): boolean; - /** - * Deactivates all objects on canvas, removing any active group or object - * @return thisArg - */ - deactivateAll(): Canvas; - /** - * Deactivates all objects and dispatches appropriate events - * @param [e] Event (passed along when firing) - * @return thisArg - */ - deactivateAllWithDispatch(e?: Event): Canvas; - /** - * Discards currently active group - * @param [e] Event (passed along when firing) - * @return thisArg - */ - discardActiveGroup(e?: Event): Canvas; - /** - * Discards currently active object - * @param [e] Event (passed along when firing) - * @return thisArg - * @chainable - */ - discardActiveObject(e?: Event): Canvas; - /** - * Draws objects' controls (borders/controls) - * @param ctx Context to render controls on - */ - drawControls(ctx: CanvasRenderingContext2D): void; - /** - * Method that determines what object we are clicking on - * @param e mouse event - * @param skipGroup when true, group is skipped and only objects are traversed through - */ - findTarget(e: MouseEvent, skipGroup: boolean): Canvas; - /** - * Returns currently active group - * @return Current group - */ - getActiveGroup(): Group; - /** - * Returns currently active object - * @return active object - */ - getActiveObject(): Object; - /** - * Returns pointer coordinates relative to canvas. - * @return object with "x" and "y" number values - */ - getPointer(e: Event, ignoreZoom?: boolean, upperCanvasEl?: CanvasRenderingContext2D): { x: number; y: number; }; - /** - * Returns context of canvas where object selection is drawn - */ - getSelectionContext(): CanvasRenderingContext2D; - /** - * Returns element on which object selection is drawn - */ - getSelectionElement(): HTMLCanvasElement; - /** - * Returns true if object is transparent at a certain location - * @param target Object to check - * @param x Left coordinate - * @param y Top coordinate - */ - isTargetTransparent(target: Object, x: number, y: number): boolean; - /** - * Sets active group to a speicified one - * @param group Group to set as a current one - * @param [e] Event (passed along when firing) - */ - setActiveGroup(group: Group, e?: Event): Canvas; - /** - * Sets given object as the only active object on canvas - * @param object Object to set as an active one - * @param [e] Event (passed along when firing "object:selected") - */ - setActiveObject(object: Object, e?: Event): Canvas; - /** - * Set the cursor type of the canvas element - * @param value Cursor type of the canvas element. - * @see http://www.w3.org/TR/css3-ui/#cursor - */ - setCursor(value: string): void; - - /** - * Removes all event listeners - */ - removeListeners(): void; - - static EMPTY_JSON: string; - /** - * Provides a way to check support of some of the canvas methods - * (either those of HTMLCanvasElement itself, or rendering context) - * @param methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" - */ - static supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; - /** - * Returns JSON representation of canvas - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - static toJSON(propertiesToInclude?: string[]): string; -} - -/////////////////////////////////////////////////////////////////////////////// -// Shape Interfaces -////////////////////////////////////////////////////////////////////////////// - -interface ICircleOptions extends IObjectOptions { - /** - * Radius of this circle - */ - radius?: number; - /** - * Start angle of the circle, moving clockwise - */ - startAngle?: number; - - /** - * End angle of the circle - */ - endAngle?: number; -} -export interface Circle extends Object, ICircleOptions {} -export class Circle { - constructor(options?: ICircleOptions); - - /** - * Returns complexity of an instance - * @return complexity of this instance - */ - complexity(): number; - /** - * Returns horizontal radius of an object (according to how an object is scaled) - */ - getRadiusX(): number; - /** - * Returns vertical radius of an object (according to how an object is scaled) - */ - getRadiusY(): number; - /** - * Sets radius of an object (and updates width accordingly) - */ - setRadius(value: number): number; - - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns svg representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - - /** - * List of attribute names to account for when parsing SVG element (used by {@link fabric.Circle.fromElement}) - */ - static ATTRIBUTE_NAMES: string[]; - /** - * Returns Circle instance from an SVG element - * @param element Element to parse - * @param [options] Options object - */ - static fromElement(element: SVGElement, options: ICircleOptions): Circle; - /** - * Returns Circle instance from an object representation - * @param object Object to create an instance from - */ - static fromObject(object: any): Circle; -} - -interface IEllipseOptions extends IObjectOptions { - /** - * Horizontal radius - */ - rx?: number; - /** - * Vertical radius - */ - ry?: number; -} -export interface Ellipse extends Object, IEllipseOptions {} -export class Ellipse { - constructor(options?: IEllipseOptions); - - /** - * Returns horizontal radius of an object (according to how an object is scaled) - */ - getRx(): number; - - /** - * Returns Vertical radius of an object (according to how an object is scaled) - */ - getRy(): number; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns svg representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - /** - * Returns complexity of an instance - * @return complexity - */ - complexity(): number; - - /** - * List of attribute names to account for when parsing SVG element (used by {@link fabric.Ellipse.fromElement}) - */ - static ATTRIBUTE_NAMES: string[]; - - /** - * Returns Ellipse instance from an SVG element - * @param element Element to parse - * @param [options] Options object - */ - static fromElement(element: SVGElement, options?: IEllipseOptions): Ellipse; - - /** - * Returns Ellipse instance from an object representation - * @param object Object to create an instance from - */ - static fromObject(object: any): Ellipse; -} - -export interface Group extends Object, ICollection {} -export class Group { - /** - * Constructor - * @param objects Group objects - * @param [options] Options object - */ - constructor(items?: any[], options?: IObjectOptions); - - activateAllObjects(): Group; - /** - * Adds an object to a group; Then recalculates group's dimension, position. - * @return thisArg - * @chainable - */ - addWithUpdate(object: Object): Group; - containsPoint(point: Point): boolean; - /** - * Destroys a group (restoring state of its objects) - * @return thisArg - * @chainable - */ - destroy(): Group; - /** - * Returns requested property - * @param prop Property to get - */ - get(prop: string): any; - /** - * Checks whether this group was moved (since `saveCoords` was called last) - * @return true if an object was moved (since fabric.Group#saveCoords was called) - */ - hasMoved(): boolean; - /** - * Removes an object from a group; Then recalculates group's dimension, position. - * @return thisArg - * @chainable - */ - removeWithUpdate(object: Object): Group; - /** - * Renders instance on a given context - * @param ctx context to render instance on - */ - render(ctx: CanvasRenderingContext2D): void; - /** - * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`) - * @param object Zero or more fabric instances - * @return thisArg - * @chainable - */ - remove(...object: Object[]): Group; - /** - * Saves coordinates of this instance (to be used together with `hasMoved`) - * @saveCoords - * @return thisArg - * @chainable - */ - saveCoords(): Group; - /** - * Sets coordinates of all group objects - * @return thisArg - * @chainable - */ - setObjectsCoords(): Group; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns string represenation of a group - */ - toString(): string; - /** - * Returns svg representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - - /** - * Returns {@link fabric.Group} instance from an object representation - * @param object Object to create a group from - * @param [callback] Callback to invoke when an group instance is created - */ - static fromObject(object: any, callback: (group: Group) => any): void; -} - -interface IImageOptions extends IObjectOptions { - /** - * crossOrigin value (one of "", "anonymous", "allow-credentials") - */ - crossOrigin?: string; - - /** - * AlignX value, part of preserveAspectRatio (one of "none", "mid", "min", "max") - * This parameter defines how the picture is aligned to its viewport when image element width differs from image width. - */ - alignX?: string; - - /** - * AlignY value, part of preserveAspectRatio (one of "none", "mid", "min", "max") - * This parameter defines how the picture is aligned to its viewport when image element height differs from image height. - */ - alignY?: string; - - /** - * meetOrSlice value, part of preserveAspectRatio (one of "meet", "slice"). - * if meet the image is always fully visibile, if slice the viewport is always filled with image. - * @see http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute - */ - meetOrSlice?: string; - - /** - * Image filter array - */ - filters?: IBaseFilter[]; -} -interface Image extends Object, IImageOptions {} -export class Image { - /** - * Constructor - * @param element Image element - * @param [options] Options object - */ - constructor(element: HTMLImageElement, objObjects: IObjectOptions); - - initialize(element?: string|HTMLImageElement, options?: IImageOptions): void; - /** - * Applies filters assigned to this image (from "filters" array) - * @param callback Callback is invoked when all filters have been applied and new image is generated - */ - applyFilters(callback: Function): void; - /** - * Returns a clone of an instance - * @param callback Callback is invoked with a clone as a first argument - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - clone(callback?: Function, propertiesToInclude?: string[]): void; - /** - * Returns complexity of an instance - * @return complexity of this instance - */ - complexity(): number; - /** - * Returns image element which this instance if based on - * @return Image element - */ - getElement(): HTMLImageElement; - /** - * Returns original size of an image - * @return Object with "width" and "height" properties - */ - getOriginalSize(): { width: number; height: number; }; - /** - * Returns source of an image - * @return Source of an image - */ - getSrc(): string; - render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; - - /** - * Sets image element for this instance to a specified one. - * If filters defined they are applied to new image. - * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area. - * @param [callback] Callback is invoked when all filters have been applied and new image is generated - * @param [options] Options object - */ - setElement(element: HTMLImageElement, callback: Function, options: IImageOptions): Image; - /** - * Sets crossOrigin value (on an instance and corresponding image element) - */ - setCrossOrigin(value: string): Image; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return Object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns string representation of an instance - * @return String representation of an instance - */ - toString(): string; - /** - * Returns SVG representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - /** - * Sets source of an image - * @param src Source string (URL) - * @param [callback] Callback is invoked when image has been loaded (and all filters have been applied) - * @param [options] Options object - */ - setSrc(src: string, callback?: Function, options?: IImageOptions): Image; - - /** - * Creates an instance of fabric.Image from an URL string - * @param url URL to create an image from - * @param [callback] Callback to invoke when image is created (newly created image is passed as a first argument) - * @param [imgOptions] Options object - */ - static fromURL(url: string, callback?: (image: Image) => void, objObjects?: IObjectOptions): Image; - /** - * Creates an instance of fabric.Image from its object representation - * @param object Object to create an instance from - * @param [callback] Callback to invoke when an image instance is created - */ - static fromObject(object: any, callback: (image: Image) => void): void; - /** - * Returns Image instance from an SVG element - * @param element Element to parse - * @param callback Callback to execute when fabric.Image object is created - * @param [options] Options object - */ - static fromElement(element: SVGElement, callback: (image: Image) => void, options?: IImageOptions): void; - /** - * Default CSS class name for canvas - */ - static CSS_CANVAS: string; - - static filters: IAllFilters; -} - -interface ILineOptions extends IObjectOptions { - /** - * x value or first line edge - */ - x1: number; - /** - * x value or second line edge - */ - x2: number; - /** - * y value or first line edge - */ - y1: number; - /** - * y value or second line edge - */ - y2: number; -} -export interface Line extends Object, ILineOptions {} -export class Line { - /** - * Constructor - * @param [points] Array of points - * @param [options] Options object - */ - constructor(points?: number[], objObjects?: IObjectOptions); - /** - * Returns complexity of an instance - * @return complexity - */ - complexity(): number; - initialize(points?: number[], options?: ILineOptions): Line; - /** - * Returns object representation of an instance - * @methd toObject - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude: string[]): any; - /** - * Returns SVG representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - - static ATTRIBUTE_NAMES: string[]; - /** - * Returns fabric.Line instance from an SVG element - * @param element Element to parse - * @param [options] Options object - */ - static fromElement(element: SVGElement, options?: ILineOptions): Line; - /** - * Returns fabric.Line instance from an object representation - * @param object Object to create an instance from - */ - static fromObject(object: any): Line; -} - -interface IObjectOptions { - /** - * Type of an object (rect, circle, path, etc.). - * Note that this property is meant to be read-only and not meant to be modified. - * If you modify, certain parts of Fabric (such as JSON loading) won't work correctly. - */ - type?: string; - - /** - * Horizontal origin of transformation of an object (one of "left", "right", "center") - */ - originX?: string; - - /** - * Vertical origin of transformation of an object (one of "top", "bottom", "center") - */ - originY?: string; - - /** - * Top position of an object. Note that by default it's relative to object center. You can change this by setting originY={top/center/bottom} - */ - top?: number; - - /** - * Left position of an object. Note that by default it's relative to object center. You can change this by setting originX={left/center/right} - */ - left?: number; - - /** - * Object width - */ - width?: number; - - /** - * Object height - */ - height?: number; - - /** - * Object scale factor (horizontal) - */ - scaleX?: number; - - /** - * Object scale factor (vertical) - */ - scaleY?: number; - - /** - * When true, an object is rendered as flipped horizontally - */ - flipX?: boolean; - - /** - * When true, an object is rendered as flipped vertically - */ - flipY?: boolean; - - /** - * Opacity of an object - */ - opacity?: number; - - /** - * Angle of rotation of an object (in degrees) - */ - angle?: number; - - /** - * When true, object's controlling corners are rendered as transparent inside (i.e. stroke instead of fill) - */ - transparentCorners?: boolean; - - /** - * Default cursor value used when hovering over this object on canvas - */ - hoverCursor?: string; - - /** - * Padding between object and its controlling borders (in pixels) - */ - padding?: number; - - /** - * Color of controlling borders of an object (when it's active) - */ - borderColor?: string; - - /** - * Color of controlling corners of an object (when it's active) - */ - cornerColor?: string; - - /** - * Array specifying dash pattern of an object's control (hasBorder must be true) - */ - cornerDashArray?: number[]; - - /** - * Size of object's controlling corners (in pixels) - */ - cornerSize?: number; - - /** - * Color of controlling corners of an object (when it's active and transparentCorners false) - */ - cornerStrokeColor?: string; - - /** - * Specify style of control, 'rect' or 'circle' - */ - cornerStyle?: "rect" | "circle"; - - /** - * When true, this object will use center point as the origin of transformation - * when being scaled via the controls. - * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). - */ - centeredScaling?: boolean; - - /** - * When true, this object will use center point as the origin of transformation - * when being rotated via the controls. - * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). - */ - centeredRotation?: boolean; - - /** - * Color of object's fill - */ - fill?: string; - - /** - * Fill rule used to fill an object - * accepted values are nonzero, evenodd - * Backwards incompatibility note: This property was used for setting globalCompositeOperation until v1.4.12, use `globalCompositeOperation` instead - */ - fillRule?: string; - - /** - * Composite rule used for canvas globalCompositeOperation - */ - globalCompositeOperation?: string; - - /** - * Background color of an object. Only works with text objects at the moment. - */ - backgroundColor?: string; - - /** - * When defined, an object is rendered via stroke and this property specifies its color - */ - stroke?: string; - - /** - * Width of a stroke used to render this object - */ - strokeWidth?: number; - - /** - * Array specifying dash pattern of an object's stroke (stroke must be defined) - */ - strokeDashArray?: any[]; - - /** - * Line endings style of an object's stroke (one of "butt", "round", "square") - */ - strokeLineCap?: string; - - /** - * Corner style of an object's stroke (one of "bevil", "round", "miter") - */ - strokeLineJoin?: string; - - /** - * Maximum miter length (used for strokeLineJoin = "miter") of an object's stroke - */ - strokeMiterLimit?: number; - - /** - * Shadow object representing shadow of this shape - */ - shadow?: Shadow|string; - - /** - * Opacity of object's controlling borders when object is active and moving - */ - borderOpacityWhenMoving?: number; - - /** - * Scale factor of object's controlling borders - */ - borderScaleFactor?: number; - - /** - * Transform matrix (similar to SVG's transform matrix) - */ - transformMatrix?: any[]; - - /** - * Minimum allowed scale value of an object - */ - minScaleLimit?: number; - - /** - * When set to `false`, an object can not be selected for modification (using either point-click-based or group-based selection). - * But events still fire on it. - */ - selectable?: boolean; - - /** - * When set to `false`, an object can not be a target of events. All events propagate through it. Introduced in v1.3.4 - */ - evented?: boolean; - - /** - * When set to `false`, an object is not rendered on canvas - */ - visible?: boolean; - - /** - * When set to `false`, object's controls are not displayed and can not be used to manipulate object - */ - hasControls?: boolean; - - /** - * When set to `false`, object's controlling borders are not rendered - */ - hasBorders?: boolean; - - /** - * When set to `false`, object's controlling rotating point will not be visible or selectable - */ - hasRotatingPoint?: boolean; - - /** - * Offset for object's controlling rotating point (when enabled via `hasRotatingPoint`) - */ - rotatingPointOffset?: number; - - /** - * When set to `true`, objects are "found" on canvas on per-pixel basis rather than according to bounding box - */ - perPixelTargetFind?: boolean; - - /** - * When `false`, default object's values are not included in its serialization - */ - includeDefaultValues?: boolean; - - /** - * Function that determines clipping of an object (context is passed as a first argument) - * Note that context origin is at the object's center point (not left/top corner) - */ - clipTo?: Function; - - /** - * When `true`, object horizontal movement is locked - */ - lockMovementX?: boolean; - - /** - * When `true`, object vertical movement is locked - */ - lockMovementY?: boolean; - - /** - * When `true`, object rotation is locked - */ - lockRotation?: boolean; - - /** - * When `true`, object horizontal scaling is locked - */ - lockScalingX?: boolean; - - /** - * When `true`, object vertical scaling is locked - */ - lockScalingY?: boolean; - - /** - * When `true`, object non-uniform scaling is locked - */ - lockUniScaling?: boolean; - - /** - * When `true`, object cannot be flipped by scaling into negative values - */ - lockScalingFlip?: boolean; - - /** - * Not used by fabric, just for convenience - */ - name?: string; - - /** - * Not used by fabric, just for convenience - */ - data?: any; -} -export interface Object extends IObservable, IObjectOptions, IObjectAnimation {} -export class Object { - getCurrentWidth(): number; - getCurrentHeight(): number; - - getAngle(): number; - setAngle(value: number): Object; - - getBorderColor(): string; - setBorderColor(value: string): Object; - - getBorderScaleFactor(): number; - - getCornersize(): number; - setCornersize(value: number): Object; - - getFill(): string; - setFill(value: string): Object; - - getFillRule(): string; - setFillRule(value: string): Object; - - getFlipX(): boolean; - setFlipX(value: boolean): Object; - - getFlipY(): boolean; - setFlipY(value: boolean): Object; - - getHeight(): number; - setHeight(value: number): Object; - - getLeft(): number; - setLeft(value: number): Object; - - getOpacity(): number; - setOpacity(value: number): Object; - - overlayFill: string; - getOverlayFill(): string; - setOverlayFill(value: string): Object; - - getScaleX(): number; - setScaleX(value: number): Object; - - getScaleY(): number; - setScaleY(value: number): Object; - - setShadow(options: any): Object; - getShadow(): Object; - - stateProperties: any[]; - getTop(): number; - setTop(value: number): Object; - - getWidth(): number; - setWidth(value: number): Object; - - /* * Sets object's properties from options - * @param {Object} [options] Options object - */ - setOptions(options: IObjectOptions): void; - - /** - * Transforms context when rendering an object - * @param ctx Context - * @param fromLeft When true, context is transformed to object's top/left corner. This is used when rendering text on Node - */ - transform(ctx: CanvasRenderingContext2D, fromLeft: boolean): void; - - /** - * Returns an object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - toObject(propertiesToInclude?: string[]): any; - - /** - * Returns (dataless) object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - toDatalessObject(propertiesToInclude?: string[]): any; - - /** - * Returns a string representation of an instance - */ - toString(): string; - - /** - * Basic getter - * @param property Property name - */ - get(property: K): this[K]; - - /** - * Sets property to a given value. - * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. - * If you need to update those, call `setCoords()`. - * @param key Property name - * @param value Property value (if function, the value is passed into it and its return value is used as a new one) - */ - set(key: K, value: this[K] | ((value: this[K]) => this[K])): this; - /** - * Sets property to a given value. - * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. - * If you need to update those, call `setCoords()`. - * @param options Property object, iterate over the object properties - */ - set(options: Partial): this; - - /** - * Toggles specified property from `true` to `false` or from `false` to `true` - * @param property Property to toggle - */ - toggle(property: keyof this): this; - - /** - * Sets sourcePath of an object - * @param value Value to set sourcePath to - */ - setSourcePath(value: string): this; - - /** - * Retrieves viewportTransform from Object's canvas if possible - */ - getViewportTransform(): boolean; - - /** - * Renders an object on a specified context - * @param ctx Context to render on - * @param [noTransform] When true, context is not transformed - */ - render(ctx: CanvasRenderingContext2D, noTransform?: boolean): void; - - /** - * Clones an instance, using a callback method will work for every object. - * @param callback Callback is invoked with a clone as a first argument - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - clone(callback: (clone: Object) => void, propertiesToInclude?: string[]): void; - - /** - * Creates an instance of fabric.Image out of an object - * @param callback callback, invoked with an instance as a first argument - */ - cloneAsImage(callback: (image: Image) => void): this; - - /** - * Converts an object into a data-url-like string - * @param options Options object - */ - toDataURL(options: IDataURLOptions): string; - - /** - * Returns true if specified type is identical to the type of an instance - * @param type Type to check against - */ - isType(type: string): boolean; - - /** - * Returns complexity of an instance - */ - complexity(): number; - - /** - * Returns a JSON representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - toJSON(propertiesToInclude?: string[]): any; - - /** - * Sets gradient (fill or stroke) of an object - * **Backwards incompatibility note:** This method was named "setGradientFill" until v1.1.0 - * @param property Property name 'stroke' or 'fill' - * @param [options] Options object - */ - setGradient(property: "stroke" | "fill", options: IGradientOptions): this; - /** - * Sets pattern fill of an object - * @param options Options object - */ - setPatternFill(options: IFillOptions): this; - - /** - * Sets shadow of an object - * @param [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)") - */ - setShadow(options?: string | Shadow): this; - - /** - * Sets "color" of an instance (alias of `set('fill', …)`) - * @param color Color value - */ - setColor(color: string): this; - - /** - * Sets "angle" of an instance - * @param angle Angle value - */ - setAngle(angle: number): this; - - /** - * Sets "angle" of an instance - * @param angle Angle value - */ - rotate(angle: number): this; - - /** - * Centers object horizontally on canvas to which it was added last. - * You might need to call `setCoords` on an object after centering, to update controls area. - */ - centerH(): this; - - /** - * Centers object vertically on canvas to which it was added last. - * You might need to call `setCoords` on an object after centering, to update controls area. - */ - centerV(): this; - - /** - * Centers object vertically and horizontally on canvas to which is was added last - * You might need to call `setCoords` on an object after centering, to update controls area. - */ - center(): this; - - /** - * Removes object from canvas to which it was added last - */ - remove(): Object; - - /** - * Returns coordinates of a pointer relative to an object - * @param e Event to operate upon - * @param [pointer] Pointer to operate upon (instead of event) - */ - getLocalPointer(e: Event, pointer?: { x: number, y: number }): { x: number, y: number }; - - /** - * Sets object's properties from options - * @param [options] Options object - */ - setOptions(options: any): void; - /** - * Sets sourcePath of an object - * @param value Value to set sourcePath to - */ - setSourcePath(value: string): Object; - // functions from object svg export mixin - // ----------------------------------------------------------------------------------------------------------------------------------- - /** - * Returns styles-string for svg-export - */ - getSvgStyles(): string; - /** - * Returns transform-string for svg-export - */ - getSvgTransform(): string; - /** - * Returns transform-string for svg-export from the transform matrix of single elements - */ - getSvgTransformMatrix(): string; - - // functions from stateful mixin - // ----------------------------------------------------------------------------------------------------------------------------------- - /** - * Returns true if object state (one of its state properties) was changed - */ - hasStateChanged(): boolean; - /** - * Saves state of an object - * @param [options] Object with additional `stateProperties` array to include when saving state - * @return thisArg - */ - saveState(options?: { stateProperties: any[] }): this; - /** - * Setups state of an object - */ - setupState(): this; - // functions from object straightening mixin - // ----------------------------------------------------------------------------------------------------------------------------------- - /** - * Straightens an object (rotating it from current angle to one of 0, 90, 180, 270, etc. depending on which is closer) - */ - straighten(): this; - /** - * Same as straighten but with animation - */ - fxStraighten(callbacks: Callbacks): this; - - // functions from object stacking mixin - // ----------------------------------------------------------------------------------------------------------------------------------- - /** - * Moves an object up in stack of drawn objects - * @param [intersecting] If `true`, send object in front of next upper intersecting object - */ - bringForward(intersecting?: boolean): this; - /** - * Moves an object to the top of the stack of drawn objects - */ - bringToFront(): this; - /** - * Moves an object down in stack of drawn objects - * @param [intersecting] If `true`, send object behind next lower intersecting object - */ - sendBackwards(intersecting?: boolean): this; - /** - * Moves an object to the bottom of the stack of drawn objects - */ - sendToBack(): this; - /** - * Moves an object to specified level in stack of drawn objects - * @param index New position of object - */ - moveTo(index: number): this; - - // functions from object origin mixin - // ----------------------------------------------------------------------------------------------------------------------------------- - /** - * Translates the coordinates from origin to center coordinates (based on the object's dimensions) - * @param point The point which corresponds to the originX and originY params - * @param originX Horizontal origin: 'left', 'center' or 'right' - * @param originY Vertical origin: 'top', 'center' or 'bottom' - */ - translateToCenterPoint(point: Point, originX: string, originY: string): Point; - - /** - * Translates the coordinates from center to origin coordinates (based on the object's dimensions) - * @param center The point which corresponds to center of the object - * @param originX Horizontal origin: 'left', 'center' or 'right' - * @param originY Vertical origin: 'top', 'center' or 'bottom' - */ - translateToOriginPoint(center: Point, originX: string, originY: string): Point; - /** - * Returns the real center coordinates of the object - */ - getCenterPoint(): Point; - - /** - * Returns the coordinates of the object as if it has a different origin - * @param originX Horizontal origin: 'left', 'center' or 'right' - * @param originY Vertical origin: 'top', 'center' or 'bottom' - */ - getPointByOrigin(): Point; - - /** - * Returns the point in local coordinates - * @param point The point relative to the global coordinate system - * @param originX Horizontal origin: 'left', 'center' or 'right' - * @param originY Vertical origin: 'top', 'center' or 'bottom' - */ - toLocalPoint(point: Point, originX: string, originY: string): Point; - - /** - * Sets the position of the object taking into consideration the object's origin - * @param pos The new position of the object - * @param originX Horizontal origin: 'left', 'center' or 'right' - * @param originY Vertical origin: 'top', 'center' or 'bottom' - */ - setPositionByOrigin(pos: Point, originX: string, originY: string): void; - - /** - * @param to One of 'left', 'center', 'right' - */ - adjustPosition(to: string): void; - - // functions from interactivity mixin - // ----------------------------------------------------------------------------------------------------------------------------------- - /** - * Draws borders of an object's bounding box. - * Requires public properties: width, height - * Requires public options: padding, borderColor - * @param ctx Context to draw on - */ - drawBorders(context: CanvasRenderingContext2D): this; - - /** - * Draws corners of an object's bounding box. - * Requires public properties: width, height - * Requires public options: cornerSize, padding - * @param ctx Context to draw on - */ - drawCorners(context: CanvasRenderingContext2D): Object; - - /** - * Returns true if the specified control is visible, false otherwise. - * @param controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'. - */ - isControlVisible(controlName: string): boolean; - /** - * Sets the visibility of the specified control. - * @param controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'. - * @param visible true to set the specified control visible, false otherwise - */ - setControlVisible(controlName: string, visible: boolean): this; - - /** - * Sets the visibility state of object controls. - * @param [options] Options object - */ - setControlsVisibility(options?: { - bl?: boolean; - br?: boolean; - mb?: boolean; - ml?: boolean; - mr?: boolean; - mt?: boolean; - tl?: boolean; - tr?: boolean; - mtr?: boolean; }): this; - - // functions from geometry mixin - // ------------------------------------------------------------------------------------------------------------------------------- - /** - * Sets corner position coordinates based on current angle, width and height - * See https://github.com/kangax/fabric.js/wiki/When-to-call-setCoords - */ - setCoords(): this; - /** - * Returns coordinates of object's bounding rectangle (left, top, width, height) - * @return Object with left, top, width, height properties - */ - getBoundingRect(): { left: number; top: number; width: number; height: number }; - /** - * Checks if object is fully contained within area of another object - * @param other Object to test - */ - isContainedWithinObject(other: Object): boolean; - /** - * Checks if object is fully contained within area formed by 2 points - * @param pointTL top-left point of area - * @param pointBR bottom-right point of area - */ - isContainedWithinRect(pointTL: any, pointBR: any): boolean; - /** - * Checks if point is inside the object - * @param point Point to check against - */ - containsPoint(point: Point): boolean; - /** - * Scales an object (equally by x and y) - * @param value Scale factor - * @return thisArg - */ - scale(value: number): this; - /** - * Scales an object to a given height, with respect to bounding box (scaling by x/y equally) - * @param value New height value - */ - scaleToHeight(value: number): this; - /** - * Scales an object to a given width, with respect to bounding box (scaling by x/y equally) - * @param value New width value - */ - scaleToWidth(value: number): this; - /** - * Checks if object intersects with another object - * @param other Object to test - */ - intersectsWithObject(other: Object): boolean; - /** - * Checks if object intersects with an area formed by 2 points - * @param pointTL top-left point of area - * @param pointBR bottom-right point of area - */ - intersectsWithRect(pointTL: any, pointBR: any): boolean; -} - -interface IPathOptions extends IObjectOptions { - /** - * Array of path points - */ - path?: any[]; - - /** - * Minimum X from points values, necessary to offset points - */ - minX?: number; - - /** - * Minimum Y from points values, necessary to offset points - */ - minY?: number; -} -export interface Path extends Object, IPathOptions {} -export class Path { - /** - * Constructor - * @param path Path data (sequence of coordinates and corresponding "command" tokens) - * @param [options] Options object - */ - constructor(path?: string|any[], options?: IPathOptions); - - initialize(path?: any[], options?: IPathOptions): Path; - - /** - * Returns number representation of an instance complexity - * @return complexity of this instance - */ - complexity(): number; - - /** - * Renders path on a specified context - * @param ctx context to render path on - * @param [noTransform] When true, context is not transformed - */ - render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; - /** - * Returns dataless object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toDatalessObject(propertiesToInclude?: string[]): any; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns string representation of an instance - * @return string representation of an instance - */ - toString(): string; - /** - * Returns svg representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - - /** - * Creates an instance of fabric.Path from an SVG element - * @param element to parse - * @param callback Callback to invoke when an fabric.Path instance is created - * @param [options] Options object - */ - static fromElement(element: SVGElement, callback: (path: Path) => any, options?: IPathOptions): void; - /** - * Creates an instance of fabric.Path from an object - * @param callback Callback to invoke when an fabric.Path instance is created - */ - static fromObject(object: any, callback: (path: Path) => any): void; -} - -export class PathGroup extends Object { - /** - * Constructor - * @param [options] Options object - */ - constructor(paths: Path[], options?: IObjectOptions); - - initialize(paths: Path[], options?: IObjectOptions): void; - /** - * Returns number representation of object's complexity - * @return complexity - */ - complexity(): number; - /** - * Returns true if all paths in this group are of same color - * @return true if all paths are of the same color (`fill`) - */ - isSameColor(): boolean; - /** - * Renders this group on a specified context - * @param ctx Context to render this instance on - */ - render(ctx: CanvasRenderingContext2D): void; - /** - * Returns dataless object representation of this path group - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return dataless object representation of an instance - */ - toDatalessObject(propertiesToInclude?: string[]): any; - /** - * Returns object representation of this path group - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns a string representation of this path group - * @return string representation of an object - */ - toString(): string; - /** - * Returns svg representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - /** - * Returns all paths in this path group - * @return array of path objects included in this path group - */ - getObjects(): Path[]; - - static fromObject(object: any): PathGroup; - /** - * Creates fabric.PathGroup instance from an object representation - * @param object Object to create an instance from - * @param callback Callback to invoke when an fabric.PathGroup instance is created - */ - static fromObject(object: any, callback: (group: PathGroup) => any): void; -} - -interface IPolygonOptions extends IObjectOptions { - /** - * Points array - */ - points?: Point[]; - - /** - * Minimum X from points values, necessary to offset points - */ - minX?: number; - - /** - * Minimum Y from points values, necessary to offset points - */ - minY?: number; -} -export interface Polygon extends IPolygonOptions {} -export class Polygon extends Object { - /** - * Constructor - * @param points Array of points - * @param [options] Options object - */ - constructor(points: Array<{ x: number; y: number }>, options?: IObjectOptions, skipOffset?: boolean); - - /** - * Returns complexity of an instance - * @return complexity of this instance - */ - complexity(): number; - - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns svg representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - - /** - * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) - */ - static ATTRIBUTE_NAMES: string[]; - - /** - * Returns Polygon instance from an SVG element - * @param element Element to parse - * @param [options] Options object - */ - static fromElement(element: SVGElement, options?: IPolygonOptions): Polygon; - /** - * Returns fabric.Polygon instance from an object representation - * @param object Object to create an instance from - */ - static fromObject(object: any): Polygon; -} - -interface IPolylineOptions extends IObjectOptions { - /** - * Points array - */ - points?: Point[]; - - /** - * Minimum X from points values, necessary to offset points - */ - minX?: number; - - /** - * Minimum Y from points values, necessary to offset points - */ - minY?: number; -} -export interface Polyline extends IPolylineOptions {} -export class Polyline extends Object { - /** - * Constructor - * @param points Array of points (where each point is an object with x and y) - * @param [options] Options object - * @param [skipOffset] Whether points offsetting should be skipped - */ - constructor(points: Array<{ x: number; y: number }>, options?: IPolylineOptions); - initialize(points: Point[], options?: IPolylineOptions): void; - /** - * Returns complexity of an instance - * @return complexity of this instance - */ - complexity(): number; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return Object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns SVG representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - - /** - * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) - */ - static ATTRIBUTE_NAMES: string[]; - - /** - * Returns Polyline instance from an SVG element - * @param element Element to parse - * @param [options] Options object - */ - static fromElement(element: SVGElement, options?: IPolylineOptions): Polyline; - /** - * Returns fabric.Polyline instance from an object representation - * @param object Object to create an instance from - */ - static fromObject(object: any): Polyline; -} - -interface IRectOptions extends IObjectOptions { - x?: number; - y?: number; - /** - * Horizontal border radius - */ - rx?: number; - - /** - * Vertical border radius - */ - ry?: number; -} - -export interface Rect extends IRectOptions {} -export class Rect extends Object { - /** - * Constructor - * @param [options] Options object - */ - constructor(options?: IRectOptions); - initialize(points?: number[], options?: any): Rect; - /** - * Returns complexity of an instance - * @return complexity - */ - complexity(): number; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude: any[]): any; - /** - * Returns svg representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - - /** - * List of attribute names to account for when parsing SVG element (used by `fabric.Rect.fromElement`) - */ - static ATTRIBUTE_NAMES: string[]; - /** - * Returns Rect instance from an SVG element - * @param element Element to parse - * @param [options] Options object - */ - static fromElement(element: SVGElement, options?: IRectOptions): Rect; - /** - * Returns Rect instance from an object representation - * @param object Object to create an instance from - */ - static fromObject(object: any): Rect; -} - -interface ITextOptions extends IObjectOptions { - /** - * Font size (in pixels) - */ - fontSize?: number; - /** - * Font weight (e.g. bold, normal, 400, 600, 800) - */ - fontWeight?: number|string; - /** - * Font family - */ - fontFamily?: string; - /** - * Text decoration Possible values?: "", "underline", "overline" or "line-through". - */ - textDecoration?: string; - /** - * Text alignment. Possible values?: "left", "center", or "right". - */ - textAlign?: string; - /** - * Font style . Possible values?: "", "normal", "italic" or "oblique". - */ - fontStyle?: string; - /** - * Line height - */ - lineHeight?: number; - /** - * When defined, an object is rendered via stroke and this property specifies its color. - * Backwards incompatibility note?: This property was named "strokeStyle" until v1.1.6 - */ - stroke?: string; - /** - * Shadow object representing shadow of this shape. - * Backwards incompatibility note?: This property was named "textShadow" (String) until v1.2.11 - */ - shadow?: Shadow|string; - /** - * Background color of text lines - */ - textBackgroundColor?: string; - - path?: string; - useNative?: boolean; - text?: string; -} -export interface Text extends ITextOptions {} -export class Text extends Object { - /** - * Constructor - * @param text Text string - * @param [options] Options object - */ - constructor(text: string, options?: ITextOptions); - /** - * Returns complexity of an instance - */ - complexity(): number; - /** - * Returns string representation of an instance - */ - toString(): string; - /** - * Renders text instance on a specified context - * @param ctx Context to render on - */ - render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns SVG representation of an instance - * @param [reviver] Method for further parsing of svg representation. - */ - toSVG(reviver?: Function): string; - /** - * Retrieves object's fontSize - */ - getFontSize(): number; - /** - * Sets object's fontSize - * @param fontSize Font size (in pixels) - */ - setFontSize(fontSize: number): Text; - /** - * Retrieves object's fontWeight - */ - getFontWeight(): number|string; - /** - * Sets object's fontWeight - * @param fontWeight Font weight - */ - setFontWeight(fontWeight: string|number): Text; - /** - * Retrieves object's fontFamily - */ - getFontFamily(): string; - /** - * Sets object's fontFamily - * @param fontFamily Font family - */ - setFontFamily(fontFamily: string): Text; - /** - * Retrieves object's text - */ - getText(): string; - /** - * Sets object's text - * @param text Text - */ - setText(text: string): Text; - /** - * Retrieves object's textDecoration - */ - getTextDecoration(): string; - /** - * Sets object's textDecoration - * @param textDecoration Text decoration - */ - setTextDecoration(textDecoration: string): Text; - /** - * Retrieves object's fontStyle - */ - getFontStyle(): string; - /** - * Sets object's fontStyle - * @param fontStyle Font style - */ - setFontStyle(fontStyle: string): Text; - /** - * Retrieves object's lineHeight - */ - getLineHeight(): number; - /** - * Sets object's lineHeight - * @param lineHeight Line height - */ - setLineHeight(lineHeight: number): Text; - /** - * Retrieves object's textAlign - */ - getTextAlign(): string; - /** - * Sets object's textAlign - * @param textAlign Text alignment - */ - setTextAlign(textAlign: string): Text; - /** - * Retrieves object's textBackgroundColor - */ - getTextBackgroundColor(): string; - /** - * Sets object's textBackgroundColor - * @param textBackgroundColor Text background color - */ - setTextBackgroundColor(textBackgroundColor: string): Text; - - /** - * List of attribute names to account for when parsing SVG element (used by `fabric.Text.fromElement`) - */ - static ATTRIBUTE_NAMES: string[]; - /** - * Default SVG font size - */ - static DEFAULT_SVG_FONT_SIZE: number; - - /** - * Returns fabric.Text instance from an SVG element (not yet implemented) - * @param element Element to parse - * @param [options] Options object - */ - static fromElement(element: SVGElement, options?: ITextOptions): Text; - /** - * Returns fabric.Text instance from an object representation - * @param object Object to create an instance from - */ - static fromObject(object: any): Text; -} - -interface IITextOptions extends IObjectOptions, ITextOptions { - /** - * Index where text selection starts (or where cursor is when there is no selection) - */ - selectionStart?: number; - - /** - * Index where text selection ends - */ - selectionEnd?: number; - - /** - * Color of text selection - */ - selectionColor?: string; - - /** - * Indicates whether text is in editing mode - */ - isEditing?: boolean; - - /** - * Indicates whether a text can be edited - */ - editable?: boolean; - - /** - * Border color of text object while it's in editing mode - */ - editingBorderColor?: string; - - /** - * Width of cursor (in px) - */ - cursorWidth?: number; - - /** - * Color of default cursor (when not overwritten by character style) - */ - cursorColor?: string; - - /** - * Delay between cursor blink (in ms) - */ - cursorDelay?: number; - - /** - * Duration of cursor fadein (in ms) - */ - cursorDuration?: number; - - /** - * Object containing character styles - * (where top-level properties corresponds to line number and 2nd-level properties -- to char number in a line) - */ - styles?: any; - - /** - * Indicates whether internal text char widths can be cached - */ - caching?: boolean; -} -export interface IText extends Text, IITextOptions {} -export class IText extends Object { - /** - * Constructor - * @param text Text string - * @param [options] Options object - */ - constructor(text: string, options?: IITextOptions); - /** - * Returns true if object has no styling - */ - isEmptyStyles(): boolean; - render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - - setText(value: string): Text; - /** - * Sets selection start (left boundary of a selection) - * @param index Index to set selection start to - */ - setSelectionStart(index: number): void; - /** - * Sets selection end (right boundary of a selection) - * @param index Index to set selection end to - */ - setSelectionEnd(index: number): void; - /** - * Gets style of a current selection/cursor (at the start position) - * @param [startIndex] Start index to get styles at - * @param [endIndex] End index to get styles at - * @return styles Style object at a specified (or current) index - */ - getSelectionStyles(startIndex: number, endIndex: number): any; - /** - * Sets style of a current selection - * @param [styles] Styles object - * @return thisArg - * @chainable - */ - setSelectionStyles(styles: any): Text; - - /** - * Renders cursor or selection (depending on what exists) - */ - renderCursorOrSelection(): void; - - /** - * Returns 2d representation (lineIndex and charIndex) of cursor (or selection start) - * @param [selectionStart] Optional index. When not given, current selectionStart is used. - */ - get2DCursorLocation(selectionStart?: number): void; - /** - * Returns complete style of char at the current cursor - * @param lineIndex Line index - * @param charIndex Char index - * @return Character style - */ - getCurrentCharStyle(lineIndex: number, charIndex: number): any; - - /** - * Returns fontSize of char at the current cursor - * @param lineIndex Line index - * @param charIndex Char index - * @return Character font size - */ - getCurrentCharFontSize(lineIndex: number, charIndex: number): number; - - /** - * Returns color (fill) of char at the current cursor - * @param lineIndex Line index - * @param charIndex Char index - * @return Character color (fill) - */ - getCurrentCharColor(lineIndex: number, charIndex: number): string; - /** - * Renders cursor - */ - renderCursor(boundaries: any): void; - - /** - * Renders text selection - * @param chars Array of characters - * @param boundaries Object with left/top/leftOffset/topOffset - */ - renderSelection(chars: string[], boundaries: any): void; - - // functions from itext behavior mixin - // ------------------------------------------------------------------------------------------------------------------------ - /** - * Initializes all the interactive behavior of IText - */ - initBehavior(): void; - - /** - * Initializes "selected" event handler - */ - initSelectedHandler(): void; - - /** - * Initializes "added" event handler - */ - initAddedHandler(): void; - - initRemovedHandler(): void; - - /** - * Initializes delayed cursor - */ - initDelayedCursor(restart: boolean): void; - - /** - * Aborts cursor animation and clears all timeouts - */ - abortCursorAnimation(): void; - - /** - * Selects entire text - */ - selectAll(): void; - - /** - * Returns selected text - */ - getSelectedText(): string; - - /** - * Find new selection index representing start of current word according to current selection index - * @param startFrom Surrent selection index - * @return New selection index - */ - findWordBoundaryLeft(startFrom: number): number; - - /** - * Find new selection index representing end of current word according to current selection index - * @param startFrom Current selection index - * @return New selection index - */ - findWordBoundaryRight(startFrom: number): number; - - /** - * Find new selection index representing start of current line according to current selection index - * @param startFrom Current selection index - */ - findLineBoundaryLeft(startFrom: number): number; - - /** - * Find new selection index representing end of current line according to current selection index - * @param startFrom Current selection index - */ - findLineBoundaryRight(startFrom: number): number; - - /** - * Returns number of newlines in selected text - */ - getNumNewLinesInSelectedText(): number; - - /** - * Finds index corresponding to beginning or end of a word - * @param selectionStart Index of a character - * @param direction: 1 or -1 - */ - searchWordBoundary(selectionStart: number, direction: number): number; - - /** - * Selects a word based on the index - * @param selectionStart Index of a character - */ - selectWord(selectionStart: number): void; - /** - * Selects a line based on the index - * @param selectionStart Index of a character - */ - selectLine(selectionStart: number): void; - - /** - * Enters editing state - */ - enterEditing(): IText; - - /** - * Initializes "mousemove" event handler - */ - initMouseMoveHandler(): void; - /** - * Exits from editing state - * @return thisArg - * @chainable - */ - exitEditing(): IText; - - /** - * Inserts a character where cursor is (replacing selection if one exists) - * @param _chars Characters to insert - */ - insertChars(_chars: string, useCopiedStyle?: boolean): void; - /** - * Inserts new style object - * @param lineIndex Index of a line - * @param charIndex Index of a char - * @param isEndOfLine True if it's end of line - */ - insertNewlineStyleObject(lineIndex: number, charIndex: number, isEndOfLine: boolean): void; - - /** - * Inserts style object for a given line/char index - * @param lineIndex Index of a line - * @param charIndex Index of a char - * @param [style] Style object to insert, if given - */ - insertCharStyleObject(lineIndex: number, charIndex: number, isEndOfLine: boolean): void; - - /** - * Inserts style object(s) - * @param _chars Characters at the location where style is inserted - * @param isEndOfLine True if it's end of line - * @param [useCopiedStyle] Style to insert - */ - insertStyleObjects(_chars: string, isEndOfLine: boolean, useCopiedStyle?: boolean): void; - - /** - * Shifts line styles up or down - * @param lineIndex Index of a line - * @param offset Can be -1 or +1 - */ - shiftLineStyles(lineIndex: number, offset: number): void; - - /** - * Removes style object - * @param isBeginningOfLine True if cursor is at the beginning of line - * @param [index] Optional index. When not given, current selectionStart is used. - */ - removeStyleObject(isBeginningOfLine: boolean, index?: number): void; - /** - * Inserts new line - */ - insertNewline(): void; - - /** - * Returns fabric.IText instance from an object representation - * @param object Object to create an instance from - */ - static fromObject(object: any): IText; -} - -interface ITriangleOptions extends IObjectOptions { } -export class Triangle extends Object { - /** - * Constructor - * @param [options] Options object - */ - constructor(options?: ITriangleOptions); - - /** - * Returns complexity of an instance - * @return complexity of this instance - */ - complexity(): number; - /** - * Returns SVG representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - - /** - * Returns Triangle instance from an object representation - * @param object Object to create an instance from - */ - static fromObject(object: any): Triangle; -} - -//////////////////////////////////////////////////////////// -// Filters -//////////////////////////////////////////////////////////// -interface IAllFilters { - BaseFilter: { - /** - * Constructor - * @param [options] Options object - */ - new (options?: any): IBaseFilter; - }; - Blend: { - /** - * Constructor - * @param [options] Options object - */ - new (options?: { color?: string; mode?: string; alpha?: number; image?: Image }): IBlendFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): IBlendFilter - }; - Brightness: { - new (options?: { - /** - * Value to brighten the image up (0..255) - * @default 0 - */ - brightness: number - }): IBrightnessFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): IBrightnessFilter - }; - Convolute: { - new (options?: { - opaque?: boolean, - /** Filter matrix */ - matrix?: number[], - }): IConvoluteFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): IConvoluteFilter - }; - GradientTransparency: { - new (options?: { - /** @default 100 */ - threshold?: number; - }): IGradientTransparencyFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): IGradientTransparencyFilter - }; - Grayscale: { - new (options?: any): IGrayscaleFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): IGrayscaleFilter - }; - Invert: { - /** - * Constructor - * @param [options] Options object - */ - new (options?: any): IInvertFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): IInvertFilter - }; - Mask: { - new (options?: { - /** Mask image object */ - mask?: Image, - /** - * Rgb channel (0, 1, 2 or 3) - * @default 0 - */ - channel: number, - }): IMaskFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): IMaskFilter - }; - Multiply: { - new (options?: { - /** - * Color to multiply the image pixels with - * @default #000000 - */ - color: string; - }): IMultiplyFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): IMultiplyFilter - }; - Noise: { - new (options?: { - /** @default 0 */ - noise: number, - }): INoiseFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): INoiseFilter - }; - Pixelate: { - new (options?: { - /** - * Blocksize for pixelate - * @default 4 - */ - blocksize?: number, - }): IPixelateFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): IPixelateFilter - }; - RemoveWhite: { - new (options?: { - /** @default 30 */ - threshold?: number, - /** @default 20 */ - distance?: number, - }): IRemoveWhiteFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): IRemoveWhiteFilter - }; - Resize: { - new (options?: any): IResizeFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): IResizeFilter - }; - Sepia2: { - new (options?: any): ISepia2Filter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): ISepia2Filter - }; - Sepia: { - new (options?: any): ISepiaFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): ISepiaFilter - }; - Tint: { - new (options?: { - /** - * Color to tint the image with - * @default #000000 - */ - color?: string; - /** Opacity value that controls the tint effect's transparency (0..1) */ - opacity?: number; - }): ITintFilter; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): ITintFilter - }; -} -interface IBaseFilter { - /** - * Sets filter's properties from options - * @param [options] Options object - */ - setOptions(options?: any): void; - /** - * Returns object representation of an instance - */ - toObject(): any; - /** - * Returns a JSON representation of an instance - */ - toJSON(): string; -} -interface IBlendFilter extends IBaseFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface IBrightnessFilter extends IBaseFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface IConvoluteFilter extends IBaseFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface IGradientTransparencyFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface IGrayscaleFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface IInvertFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface IMaskFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface IMultiplyFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface INoiseFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface IPixelateFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface IRemoveWhiteFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface IResizeFilter { - /** - * Resize type - */ - resizeType: string; - - /** - * Scale factor for resizing, x axis - */ - scaleX: number; - - /** - * Scale factor for resizing, y axis - */ - scaleY: number; - - /** - * LanczosLobes parameter for lanczos filter - */ - lanczosLobes: number; - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface ISepiaFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface ISepia2Filter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} -interface ITintFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; -} - -//////////////////////////////////////////////////////////// -// Brushes -//////////////////////////////////////////////////////////// -export class BaseBrush { - /** - * Color of a brush - */ - color: string; - - /** - * Width of a brush - */ - width: number; - - /** - * Shadow object representing shadow of this shape. - * Backwards incompatibility note: This property replaces "shadowColor" (String), "shadowOffsetX" (Number), - * "shadowOffsetY" (Number) and "shadowBlur" (Number) since v1.2.12 - */ - shadow: Shadow|string; - /** - * Line endings style of a brush (one of "butt", "round", "square") - */ - strokeLineCap: string; - - /** - * Corner style of a brush (one of "bevil", "round", "miter") - */ - strokeLineJoin: string; - - /** - * Stroke Dash Array. - */ - strokeDashArray: any[]; - - /** - * Sets shadow of an object - * @param [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)") - */ - setShadow(options: string|any): BaseBrush; -} - -export class CircleBrush extends BaseBrush { - /** - * Width of a brush - */ - width: number; - /** - * Invoked inside on mouse down and mouse move - */ - drawDot(pointer: any): void; - - /** - * @return Just added pointer point - */ - addPoint(pointer: any): Point; -} - -export class SprayBrush extends BaseBrush { - /** - * Width of a brush - */ - width: number; - /** - * Density of a spray (number of dots per chunk) - */ - density: number; - - /** - * Width of spray dots - */ - dotWidth: number; - /** - * Width variance of spray dots - */ - dotWidthVariance: number; - - /** - * Whether opacity of a dot should be random - */ - randomOpacity: boolean; - /** - * Whether overlapping dots (rectangles) should be removed (for performance reasons) - */ - optimizeOverlapping: boolean; - - addSprayChunk(pointer: any): void; -} -export class PatternBrush extends PencilBrush { - getPatternSrc(): HTMLCanvasElement; - - getPatternSrcFunction(): string; - - /** - * Creates "pattern" instance property - */ - getPattern(): any; - /** - * Creates path - */ - createPath(pathData: string): Path; -} -export class PencilBrush extends BaseBrush { - /** - * Converts points to SVG path - * @param points Array of points - */ - convertPointsToSVGPath(points: Array<{ x: number; y: number }>, minX?: number, minY?: number): string[]; - - /** - * Creates fabric.Path object to add on canvas - * @param pathData Path data - */ - createPath(pathData: string): Path; -} - -/////////////////////////////////////////////////////////////////////////////// -// Fabric util Interface -////////////////////////////////////////////////////////////////////////////// -interface IUtilAnimationOptions { - /** - * Starting value - */ - startValue?: number; - /** - * Ending value - */ - endValue?: number; - /** - * Value to modify the property by - */ - byValue: number; - /** - * Duration of change (in ms) - */ - duration?: number; - /** - * Callback; invoked on every value change - */ - onChange?: Function; - /** - * Callback; invoked when value change is completed - */ - onComplete?: Function; - /** - * Easing function - */ - easing?: Function; -} -interface IUtilAnimation { - /** - * Changes value from one to another within certain period of time, invoking callbacks as value is being changed. - * @param [options] Animation options - */ - animate(options?: IUtilAnimationOptions): void; - /** - * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/ - * In order to get a precise start time, `requestAnimFrame` should be called as an entry into the method - * @param callback Callback to invoke - */ - requestAnimFrame(callback: Function): void; -} - -type IUtilAminEaseFunction = (t: number, b: number, c: number, d: number) => number; - -interface IUtilAnimEase { - easeInBack: IUtilAminEaseFunction; - easeInBounce: IUtilAminEaseFunction; - easeInCirc: IUtilAminEaseFunction; - easeInCubic: IUtilAminEaseFunction; - easeInElastic: IUtilAminEaseFunction; - easeInExpo: IUtilAminEaseFunction; - easeInOutBack: IUtilAminEaseFunction; - easeInOutBounce: IUtilAminEaseFunction; - easeInOutCirc: IUtilAminEaseFunction; - easeInOutCubic: IUtilAminEaseFunction; - easeInOutElastic: IUtilAminEaseFunction; - easeInOutExpo: IUtilAminEaseFunction; - easeInOutQuad: IUtilAminEaseFunction; - easeInOutQuart: IUtilAminEaseFunction; - easeInOutQuint: IUtilAminEaseFunction; - easeInOutSine: IUtilAminEaseFunction; - easeInQuad: IUtilAminEaseFunction; - easeInQuart: IUtilAminEaseFunction; - easeInQuint: IUtilAminEaseFunction; - easeInSine: IUtilAminEaseFunction; - easeOutBack: IUtilAminEaseFunction; - easeOutBounce: IUtilAminEaseFunction; - easeOutCirc: IUtilAminEaseFunction; - easeOutCubic: IUtilAminEaseFunction; - easeOutElastic: IUtilAminEaseFunction; - easeOutExpo: IUtilAminEaseFunction; - easeOutQuad: IUtilAminEaseFunction; - easeOutQuart: IUtilAminEaseFunction; - easeOutQuint: IUtilAminEaseFunction; - easeOutSine: IUtilAminEaseFunction; -} - -interface IUtilArc { - /** - * Draws arc - */ - drawArc(ctx: CanvasRenderingContext2D, fx: number, fy: number, coords: number[]): void; - /** - * Calculate bounding box of a elliptic-arc - * @param fx start point of arc - * @param rx horizontal radius - * @param ry vertical radius - * @param rot angle of horizontal axe - * @param large 1 or 0, whatever the arc is the big or the small on the 2 points - * @param sweep 1 or 0, 1 clockwise or counterclockwise direction - * @param tx end point of arc - */ - getBoundsOfArc(fx: number, fy: number, rx: number, ry: number, rot: number, large: number, sweep: number, tx: number, ty: number): Point[]; - /** - * Calculate bounding box of a beziercurve - * @param x0 starting point - * @param x1 first control point - * @param x2 secondo control point - * @param x3 end of beizer - */ - getBoundsOfCurve(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): Point[]; -} - -interface IUtilDomEvent { - /** - * Cross-browser wrapper for getting event's coordinates - * @param event Event object - * @param upperCanvasEl <canvas> element on which object selection is drawn - */ - getPointer(event: Event, upperCanvasEl: HTMLCanvasElement): Point; - - /** - * Adds an event listener to an element - */ - addListener(element: HTMLElement, eventName: string, handler: Function): void; - - /** - * Removes an event listener from an element - */ - removeListener(element: HTMLElement, eventName: string, handler: Function): void; -} - -interface IUtilDomMisc { - /** - * Takes id and returns an element with that id (if one exists in a document) - */ - getById(id: string|HTMLElement): HTMLElement; - /** - * Converts an array-like object (e.g. arguments or NodeList) to an array - */ - toArray(arrayLike: any): any[]; - /** - * Creates specified element with specified attributes - * @param tagName Type of an element to create - * @param [attributes] Attributes to set on an element - * @return Newly created element - */ - makeElement(tagName: string, attributes?: any): HTMLElement; - /** - * Adds class to an element - * @param element Element to add class to - * @param className Class to add to an element - */ - addClass(element: HTMLElement, classname: string): void; - /** - * Wraps element with another element - * @param element Element to wrap - * @param wrapper Element to wrap with - * @param [attributes] Attributes to set on a wrapper - */ - wrapElement(element: HTMLElement, wrapper: HTMLElement|string, attributes?: any): HTMLElement; - /** - * Returns element scroll offsets - * @param element Element to operate on - * @param upperCanvasEl Upper canvas element - */ - getScrollLeftTop(element: HTMLElement, upperCanvasEl: HTMLElement): { left: number; right: number; }; - /** - * Returns offset for a given element - * @param element Element to get offset for - */ - getElementOffset(element: HTMLElement): { left: number; right: number; }; - /** - * Returns style attribute value of a given element - * @param element Element to get style attribute for - * @param attr Style attribute to get for element - */ - getElementStyle(elment: HTMLElement, attr: string): string; - /** - * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading - * @param url URL of a script to load - * @param callback Callback to execute when script is finished loading - */ - getScript(url: string, callback: Function): void; - /** - * Makes element unselectable - * @param element Element to make unselectable - */ - makeElementUnselectable(element: HTMLElement): HTMLElement; - /** - * Makes element selectable - * @param element Element to make selectable - */ - makeElementSelectable(element: HTMLElement): HTMLElement; -} - -interface IUtilDomRequest { - /** - * Cross-browser abstraction for sending XMLHttpRequest - * @param url URL to send XMLHttpRequest to - */ - request(url: string, options?: { - /** @default "GET" */ - method?: string, - /** Callback to invoke when request is completed */ - onComplete: Function, - }): XMLHttpRequest; -} - -interface IUtilDomStyle { - /** - * Cross-browser wrapper for setting element's style - */ - setStyle(element: HTMLElement, styles: any): HTMLElement; -} - -interface IUtilArray { - /** - * Invokes method on all items in a given array - * @param array Array to iterate over - * @param method Name of a method to invoke - */ - invoke(array: any[], method: string): any[]; - /** - * Finds minimum value in array (not necessarily "first" one) - * @param array Array to iterate over - */ - min(array: any[], byProperty: string): any; - /** - * Finds maximum value in array (not necessarily "first" one) - * @param array Array to iterate over - */ - max(array: any[], byProperty: string): any; -} - -interface IUtilClass { - /** - * Helper for creation of "classes". - * @param [parent] optional "Class" to inherit from - * @param [properties] Properties shared by all instances of this class - * (be careful modifying objects defined here as this would affect all instances) - */ - createClass(parent: Function, properties?: any): void; - /** - * Helper for creation of "classes". - * @param [properties] Properties shared by all instances of this class - * (be careful modifying objects defined here as this would affect all instances) - */ - createClass(properties?: any): void; -} - -interface IUtilObject { - /** - * Copies all enumerable properties of one object to another - * @param destination Where to copy to - * @param source Where to copy from - */ - extend(destination: any, source: any): any; - - /** - * Creates an empty object and copies all enumerable properties of another object to it - * @param object Object to clone - */ - clone(object: any): any; -} - -interface IUtilString { - /** - * Camelizes a string - * @param string String to camelize - */ - camelize(string: string): string; - - /** - * Capitalizes a string - * @param string String to capitalize - * @param [firstLetterOnly] If true only first letter is capitalized - * and other letters stay untouched, if false first letter is capitalized - * and other letters are converted to lowercase. - */ - capitalize(string: string, firstLetterOnly: boolean): string; - - /** - * Escapes XML in a string - * @param string String to escape - */ - escapeXml(string: string): string; -} - -interface IUtilMisc { - /** - * Removes value from an array. - * Presence of value (and its position in an array) is determined via `Array.prototype.indexOf` - */ - removeFromArray(array: any[], value: any): any[]; - - /** - * Returns random number between 2 specified ones. - * @param min lower limit - * @param max upper limit - */ - getRandomInt(min: number, max: number): number; - - /** - * Transforms degrees to radians. - * @param degrees value in degrees - */ - degreesToRadians(degrees: number): number; - - /** - * Transforms radians to degrees. - * @param radians value in radians - */ - radiansToDegrees(radians: number): number; - - /** - * Rotates `point` around `origin` with `radians` - * @param point The point to rotate - * @param origin The origin of the rotation - * @param radians The radians of the angle for the rotation - */ - rotatePoint(point: Point, origin: Point, radians: number): Point; - - /** - * Rotates `vector` with `radians` - * @param vector The vector to rotate (x and y) - * @param radians The radians of the angle for the rotation - */ - rotateVector(vector: { x: number, y: number }, radians: number): { x: number, y: number }; - - /** - * Apply transform t to point p - * @param p The point to transform - * @param t The transform - * @param [ignoreOffset] Indicates that the offset should not be applied - */ - transformPoint(p: Point, t: any[], ignoreOffset?: boolean): Point; - - /** - * Invert transformation t - * @param t The transform - */ - invertTransform(t: any[]): any[]; - - /** - * A wrapper around Number#toFixed, which contrary to native method returns number, not string. - * @param number number to operate on - * @param fractionDigits number of fraction digits to "leave" - */ - toFixed(number: number, fractionDigits: number): number; - - /** - * Converts from attribute value to pixel value if applicable. - * Returns converted pixels or original value not converted. - * @param value number to operate on - */ - parseUnit(value: number|string, fontSize?: number): number|string; - - /** - * Function which always returns `false`. - */ - falseFunction(): boolean; - - /** - * Returns klass "Class" object of given namespace - * @param type Type of object (eg. 'circle') - * @param namespace Namespace to get klass "Class" object from - */ - getKlass(type: string, namespace: string): any; - - /** - * Returns object of given namespace - * @param namespace Namespace string e.g. 'fabric.Image.filter' or 'fabric' - */ - resolveNamespace(namespace: string): any; - - /** - * Loads image element from given url and passes it to a callback - * @param url URL representing an image - * @param callback Callback; invoked with loaded image - * @param [context] Context to invoke callback in - * @param [crossOrigin] crossOrigin value to set image element to - */ - loadImage(url: string, callback: (image: HTMLImageElement) => {}, context?: any, crossOrigin?: boolean): void; - - /** - * Creates corresponding fabric instances from their object representations - * @param objects Objects to enliven - * @param callback Callback to invoke when all objects are created - * @param namespace Namespace to get klass "Class" object from - * @param reviver Method for further parsing of object elements, called after each fabric object created. - */ - enlivenObjects(objects: any[], callback: Function, namespace: string, reviver?: Function): void; - - /** - * Groups SVG elements (usually those retrieved from SVG document) - * @param elements SVG elements to group - * @param [options] Options object - */ - groupSVGElements(elements: any[], options?: any, path?: any): PathGroup; - - /** - * Populates an object with properties of another object - * @param source Source object - * @param destination Destination object - * @param properties Propertie names to include - */ - populateWithProperties(source: any, destination: any, properties: any): void; - - /** - * Draws a dashed line between two points - * This method is used to draw dashed line around selection area. - * @param ctx context - * @param x start x coordinate - * @param y start y coordinate - * @param x2 end x coordinate - * @param y2 end y coordinate - * @param da dash array pattern - */ - drawDashedLine(ctx: CanvasRenderingContext2D, x: number, y: number, x2: number, y2: number, da: any[]): void; - - /** - * Creates canvas element and initializes it via excanvas if necessary - * @param [canvasEl] optional canvas element to initialize; - * when not given, element is created implicitly - */ - createCanvasElement(canvasEl?: HTMLCanvasElement): HTMLCanvasElement; - - /** - * Creates image element (works on client and node) - */ - createImage(): HTMLImageElement; - - /** - * Creates accessors (getXXX, setXXX) for a "class", based on "stateProperties" array - * @param klass "Class" to create accessors for - */ - createAccessors(klass: any): any; - - /** - * @param receiver Object implementing `clipTo` method - * @param ctx Context to clip - */ - clipContext(receiver: Object, ctx: CanvasRenderingContext2D): void; - - /** - * Multiply matrix A by matrix B to nest transformations - * @param a First transformMatrix - * @param b Second transformMatrix - */ - multiplyTransformMatrices(a: number[], b: number[]): number[]; - - /** - * Decomposes standard 2x2 matrix into transform componentes - * @param a transformMatrix - */ - qrDecompose(a: number[]): { angle: number, scaleX: number, scaleY: number, skewX: number, skewY: number, translateX: number, translateY: number }; - - /** - * Returns string representation of function body - * @param fn Function to get body of - */ - getFunctionBody(fn: Function): string; - - /** - * Returns true if context has transparent pixel - * at specified location (taking tolerance into account) - * @param ctx context - * @param x x coordinate - * @param y y coordinate - * @param tolerance Tolerance - */ - isTransparent(ctx: CanvasRenderingContext2D, x: number, y: number, tolerance: number): boolean; -} - -export const util: IUtil; -interface IUtil extends IUtilAnimation, IUtilArc, IObservable, IUtilDomEvent, IUtilDomMisc, - IUtilDomRequest, IUtilDomStyle, IUtilClass, IUtilMisc { - ease: IUtilAnimEase; - array: IUtilArray; - object: IUtilObject; - string: IUtilString; -} +export import fabric = require("./fabric-impl"); diff --git a/types/fabric/test/import.ts b/types/fabric/test/import.ts new file mode 100644 index 0000000000..c1aa7a2896 --- /dev/null +++ b/types/fabric/test/import.ts @@ -0,0 +1,2 @@ +import { fabric } from "fabric"; +new fabric.Canvas("C"); diff --git a/types/fabric/fabric-tests.ts b/types/fabric/test/index.ts similarity index 100% rename from types/fabric/fabric-tests.ts rename to types/fabric/test/index.ts diff --git a/types/fabric/tsconfig.json b/types/fabric/tsconfig.json index fc7ce8ddc9..eca1407551 100644 --- a/types/fabric/tsconfig.json +++ b/types/fabric/tsconfig.json @@ -19,6 +19,7 @@ }, "files": [ "index.d.ts", - "fabric-tests.ts" + "test/index.ts", + "test/import.ts" ] } \ No newline at end of file From 1d841b17e82df903ca3ade77f6b6f44504346da3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Richard=20Jedli=C4=8Dka?= Date: Tue, 20 Feb 2018 22:06:14 +0100 Subject: [PATCH 055/128] Fix global object --- types/fingerprintjs2/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/fingerprintjs2/index.d.ts b/types/fingerprintjs2/index.d.ts index b4d8d5ff6c..5778eebeed 100644 --- a/types/fingerprintjs2/index.d.ts +++ b/types/fingerprintjs2/index.d.ts @@ -43,3 +43,4 @@ interface Fingerprint2Options { } export = Fingerprint2; +export as namespace Fingerprint2; From f807b33420e2221f9dd6ce979507ff6819582aee Mon Sep 17 00:00:00 2001 From: Todd Bealmear Date: Tue, 20 Feb 2018 16:47:35 -0800 Subject: [PATCH 056/128] Fix issue where Sequelize.Model.scope would not respect children (#23494) --- types/sequelize/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index 4de155e6ee..643a9a8167 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -11,6 +11,7 @@ // Carven Zhang // Nikola Vidic // Florian Oellerich +// Todd Bealmear // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -3780,7 +3781,7 @@ declare namespace sequelize { * @return Model A reference to the model, with the scope(s) applied. Calling scope again on the returned * model will clear the previous scope. */ - scope(options?: string | ScopeOptions | AnyWhereOptions | Array): this; + scope(options?: string | ScopeOptions | AnyWhereOptions | Array): Model; /** * Search for multiple instances. From 03be5516a48031bc9fe41a1d6718077aabb21e5b Mon Sep 17 00:00:00 2001 From: Mischa King Date: Wed, 21 Feb 2018 15:11:46 +1000 Subject: [PATCH 057/128] Update Type to match v2.3.0 Added trimWhitespace boolean to match version 2.3.0 --- types/react-truncate/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/react-truncate/index.d.ts b/types/react-truncate/index.d.ts index cb97ccafe7..54618a9a8e 100644 --- a/types/react-truncate/index.d.ts +++ b/types/react-truncate/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-truncate 2.1 +// Type definitions for react-truncate 2.3.0 // Project: https://github.com/One-com/react-truncate // Definitions by: Matt Perry // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,6 +9,7 @@ import * as React from 'react'; export interface TruncateProps extends React.HTMLProps { lines?: number | false; ellipsis?: React.ReactNode; + trimWhitespace?: boolean; onTruncate?(isTruncated: boolean): void; } From 2623588675a7b5ea2c3845edb8af7df9b13840c0 Mon Sep 17 00:00:00 2001 From: Anatoly Belonog Date: Wed, 21 Feb 2018 14:44:09 +0700 Subject: [PATCH 058/128] enable all tslint rules --- types/async-lock/async-lock-tests.ts | 3 +- types/async-lock/index.d.ts | 9 ++-- types/async-lock/tslint.json | 76 +--------------------------- 3 files changed, 5 insertions(+), 83 deletions(-) diff --git a/types/async-lock/async-lock-tests.ts b/types/async-lock/async-lock-tests.ts index 64a1e89c75..9e8920ca4b 100755 --- a/types/async-lock/async-lock-tests.ts +++ b/types/async-lock/async-lock-tests.ts @@ -1,4 +1,3 @@ - import * as AsyncLock from "async-lock"; const lock = new AsyncLock(); @@ -23,7 +22,7 @@ lock.acquire([ "key1", "key2" ], (done) => { }, (err, ret) => { /* ... */ }); lock.isBusy(); -lock.isBusy('key') +lock.isBusy('key'); const lock2 = new AsyncLock({ timeout : 5000 }); const lock3 = new AsyncLock({ maxPending : 5000 }); diff --git a/types/async-lock/index.d.ts b/types/async-lock/index.d.ts index 9e56e00a21..cd2b1e4b40 100755 --- a/types/async-lock/index.d.ts +++ b/types/async-lock/index.d.ts @@ -1,15 +1,12 @@ -// Type definitions for async-lock 1.1.0 +// Type definitions for async-lock 1.1 // Project: https://github.com/rain1017/async-lock -// Definitions by: Elisée MAURER +// Definitions by: Elisée MAURER // Alejandro // Anatoly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 - -interface AsyncLockDoneCallback { - (err?: Error, ret?: T): void; -} +type AsyncLockDoneCallback = (err?: Error, ret?: T) => void; interface AsyncLockOptions { timeout?: number; diff --git a/types/async-lock/tslint.json b/types/async-lock/tslint.json index 35039ba334..f93cf8562a 100755 --- a/types/async-lock/tslint.json +++ b/types/async-lock/tslint.json @@ -1,77 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } From d52f4f7b327af576cd33174d48602ad4ce47f9aa Mon Sep 17 00:00:00 2001 From: Anatoly Belonog Date: Wed, 21 Feb 2018 14:45:37 +0700 Subject: [PATCH 059/128] change file permissions to 644 --- types/async-lock/async-lock-tests.ts | 0 types/async-lock/index.d.ts | 0 types/async-lock/tsconfig.json | 0 types/async-lock/tslint.json | 0 4 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 types/async-lock/async-lock-tests.ts mode change 100755 => 100644 types/async-lock/index.d.ts mode change 100755 => 100644 types/async-lock/tsconfig.json mode change 100755 => 100644 types/async-lock/tslint.json diff --git a/types/async-lock/async-lock-tests.ts b/types/async-lock/async-lock-tests.ts old mode 100755 new mode 100644 diff --git a/types/async-lock/index.d.ts b/types/async-lock/index.d.ts old mode 100755 new mode 100644 diff --git a/types/async-lock/tsconfig.json b/types/async-lock/tsconfig.json old mode 100755 new mode 100644 diff --git a/types/async-lock/tslint.json b/types/async-lock/tslint.json old mode 100755 new mode 100644 From f9f4a8036345360a3c83757a253c87e9a864acb5 Mon Sep 17 00:00:00 2001 From: Florian Keller Date: Thu, 22 Feb 2018 00:04:50 +0100 Subject: [PATCH 060/128] Add single-line-log --- types/single-line-log/index.d.ts | 13 +++++++++++ .../single-line-log/single-line-log-tests.ts | 20 ++++++++++++++++ types/single-line-log/tsconfig.json | 23 +++++++++++++++++++ types/single-line-log/tslint.json | 1 + 4 files changed, 57 insertions(+) create mode 100644 types/single-line-log/index.d.ts create mode 100644 types/single-line-log/single-line-log-tests.ts create mode 100644 types/single-line-log/tsconfig.json create mode 100644 types/single-line-log/tslint.json diff --git a/types/single-line-log/index.d.ts b/types/single-line-log/index.d.ts new file mode 100644 index 0000000000..ecb60f1d3a --- /dev/null +++ b/types/single-line-log/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for single-line-log 1.1 +// Project: https://github.com/freeall/single-line-log +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface SingleLineLog { + (data: string): void; + clear(): void; + write(data: string): void; +} + +export const stdout: SingleLineLog; +export const stderr: SingleLineLog; diff --git a/types/single-line-log/single-line-log-tests.ts b/types/single-line-log/single-line-log-tests.ts new file mode 100644 index 0000000000..3814c64400 --- /dev/null +++ b/types/single-line-log/single-line-log-tests.ts @@ -0,0 +1,20 @@ +// @ts-check +/// + +import singleLineLog = require('single-line-log'); +const log = singleLineLog.stderr; + +let i = 0; + +setInterval(() => { + i++; + + const s = `line 1: ${Math.random()}`; + + log(s); + + if (i === 50) { + log.clear(); + process.exit(0); + } +}, 200); diff --git a/types/single-line-log/tsconfig.json b/types/single-line-log/tsconfig.json new file mode 100644 index 0000000000..f353aaca45 --- /dev/null +++ b/types/single-line-log/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "single-line-log-tests.ts" + ] +} diff --git a/types/single-line-log/tslint.json b/types/single-line-log/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/single-line-log/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 252e542b35f9aa1d97e5696e210dc36fef38be5b Mon Sep 17 00:00:00 2001 From: Zev Spitz Date: Thu, 22 Feb 2018 08:36:20 +0200 Subject: [PATCH 061/128] Added no-const-enum disable to tslint.json --- types/activex-wia/index.d.ts | 12 ------------ types/activex-wia/tslint.json | 5 ++++- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/types/activex-wia/index.d.ts b/types/activex-wia/index.d.ts index ae21c9c77c..18e474e09c 100644 --- a/types/activex-wia/index.d.ts +++ b/types/activex-wia/index.d.ts @@ -6,7 +6,6 @@ declare namespace WIA { /** String versions of globally unique identifiers (GUIDs) that identify common Device and Item commands. */ - // tslint:disable-next-line no-const-enum const enum CommandID { wiaCommandChangeDocument = '{04E725B0-ACAE-11D2-A093-00C04F72DC3C}', wiaCommandDeleteAllItems = '{E208C170-ACAD-11D2-A093-00C04F72DC3C}', @@ -16,7 +15,6 @@ declare namespace WIA { } /** String versions of globally unique identifiers (GUIDs) that identify DeviceManager events. */ - // tslint:disable-next-line no-const-enum const enum EventID { wiaEventDeviceConnected = '{A28BBADE-64B6-11D2-A231-00C04FA31809}', wiaEventDeviceDisconnected = '{143E4E83-6497-11D2-A231-00C04FA31809}', @@ -34,7 +32,6 @@ declare namespace WIA { } /** String versions of globally unique identifiers (GUIDs) that indicate the file format of an image. */ - // tslint:disable-next-line no-const-enum const enum FormatID { wiaFormatBMP = '{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}', wiaFormatGIF = '{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}', @@ -44,7 +41,6 @@ declare namespace WIA { } /** Miscellaneous string constants */ - // tslint:disable-next-line no-const-enum const enum Miscellaneous { wiaAnyDeviceID = '*', wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}', @@ -54,7 +50,6 @@ declare namespace WIA { * The WiaDeviceType enumeration specifies the type of device attached to a user's computer. Use the Type property on the DeviceInfo object or the Device * object to obtain these values from the device. */ - // tslint:disable-next-line no-const-enum const enum WiaDeviceType { CameraDeviceType = 2, ScannerDeviceType = 1, @@ -66,21 +61,18 @@ declare namespace WIA { * A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with * DeviceEvent.Type and a member from the WiaEventFlags enumeration. */ - // tslint:disable-next-line no-const-enum const enum WiaEventFlag { ActionEvent = 2, NotificationEvent = 1, } /** The WiaImageBias enumeration helps specify what type of data the image is intended to represent. */ - // tslint:disable-next-line no-const-enum const enum WiaImageBias { MaximizeQuality = 131072, MinimizeSize = 65536, } /** The WiaImageIntent enumeration helps specify what type of data the image is intended to represent. */ - // tslint:disable-next-line no-const-enum const enum WiaImageIntent { ColorIntent = 1, GrayscaleIntent = 2, @@ -92,7 +84,6 @@ declare namespace WIA { * The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection * of an ImageFile object. */ - // tslint:disable-next-line no-const-enum const enum WiaImagePropertyType { ByteImagePropertyType = 1001, LongImagePropertyType = 1004, @@ -115,7 +106,6 @@ declare namespace WIA { * An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with * Item.Properties("Item Flags") and a member from the WiaItemFlags enumeration. */ - // tslint:disable-next-line no-const-enum const enum WiaItemFlag { AnalyzeItemFlag = 16, AudioItemFlag = 32, @@ -142,7 +132,6 @@ declare namespace WIA { * The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a * Device or Item object. */ - // tslint:disable-next-line no-const-enum const enum WiaPropertyType { BooleanPropertyType = 1, BytePropertyType = 2, @@ -187,7 +176,6 @@ declare namespace WIA { * The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for * the property. */ - // tslint:disable-next-line no-const-enum const enum WiaSubType { FlagSubType = 3, ListSubType = 2, diff --git a/types/activex-wia/tslint.json b/types/activex-wia/tslint.json index f93cf8562a..457cebbb55 100644 --- a/types/activex-wia/tslint.json +++ b/types/activex-wia/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules":{ + "no-const-enum": false + } } From 2056f990d016a06e312b741ec7295adfc0da1ebd Mon Sep 17 00:00:00 2001 From: Justin Simms <526791+jhsimms@users.noreply.github.com> Date: Thu, 22 Feb 2018 09:06:11 -0600 Subject: [PATCH 062/128] Fix issues identified with the Hapi 17 update (#23691) * Fix issues identified with the Hapi 17 update This commit introduces a variety of changes, primarily fixes, but it also collapses the typings into a single file. Collapsing it into a single file means simpler augmentation of types, which is common in Hapi. Thank you to SimonSchick for contributing a number of changes here. * fix response property --- types/h2o2/tsconfig.json | 2 +- .../hapi-auth-basic/hapi-auth-basic-tests.ts | 2 +- .../definitions/plugin/plugin-registered.d.ts | 32 - types/hapi/definitions/plugin/plugin.d.ts | 58 - .../definitions/request/request-auth.d.ts | 34 - .../definitions/request/request-events.d.ts | 45 - .../definitions/request/request-info.d.ts | 41 - .../definitions/request/request-route.d.ts | 45 - types/hapi/definitions/request/request.d.ts | 224 - .../definitions/response/response-events.d.ts | 29 - .../definitions/response/response-object.d.ts | 288 -- .../response/response-settings.d.ts | 33 - .../response/response-toolkit.d.ts | 139 - .../route/route-options-access.d.ts | 82 - .../route/route-options-cache.d.ts | 27 - .../definitions/route/route-options-cors.d.ts | 42 - .../route/route-options-payload.d.ts | 122 - .../definitions/route/route-options-pre.d.ts | 33 - .../route/route-options-response.d.ts | 76 - .../route/route-options-secure.d.ts | 74 - .../route/route-options-validate.d.ts | 92 - .../hapi/definitions/route/route-options.d.ts | 284 -- .../server/server-auth-scheme.d.ts | 74 - .../hapi/definitions/server/server-auth.d.ts | 82 - .../hapi/definitions/server/server-cache.d.ts | 42 - .../definitions/server/server-events.d.ts | 146 - types/hapi/definitions/server/server-ext.d.ts | 146 - .../hapi/definitions/server/server-info.d.ts | 55 - .../definitions/server/server-inject.d.ts | 71 - .../definitions/server/server-method.d.ts | 64 - .../server/server-options-cache.d.ts | 25 - .../definitions/server/server-options.d.ts | 186 - .../hapi/definitions/server/server-realm.d.ts | 35 - .../definitions/server/server-register.d.ts | 62 - .../hapi/definitions/server/server-route.d.ts | 55 - .../server/server-state-options.d.ts | 63 - .../hapi/definitions/server/server-state.d.ts | 67 - types/hapi/definitions/server/server.d.ts | 563 --- types/hapi/definitions/util/common.d.ts | 8 - types/hapi/definitions/util/json.d.ts | 27 - types/hapi/definitions/util/lifecycle.d.ts | 59 - types/hapi/definitions/util/util.d.ts | 8 - types/hapi/index.d.ts | 3907 ++++++++++++++++- types/hapi/test/request/catch-all.ts | 5 +- types/hapi/test/request/event-types.ts | 10 +- types/hapi/test/request/get-log.ts | 2 +- types/hapi/test/request/parameters.ts | 4 +- types/hapi/test/request/query.ts | 2 +- types/hapi/test/response/continue.ts | 4 +- types/hapi/test/response/error.ts | 4 +- types/hapi/test/response/redirect.ts | 2 +- types/hapi/test/response/response-events.ts | 8 +- types/hapi/test/response/response.ts | 4 +- types/hapi/test/route/adding-routes.ts | 6 +- types/hapi/test/route/config.ts | 6 +- types/hapi/test/route/ext.ts | 15 + types/hapi/test/route/handler.ts | 4 +- types/hapi/test/route/route-options-pre.ts | 12 +- types/hapi/test/route/route-options.ts | 17 +- types/hapi/test/route/validation.ts | 8 +- types/hapi/test/server/server-app.ts | 2 +- types/hapi/test/server/server-auth-api.ts | 4 +- types/hapi/test/server/server-auth-default.ts | 14 +- types/hapi/test/server/server-auth-test.ts | 4 +- types/hapi/test/server/server-bind.ts | 6 +- types/hapi/test/server/server-decorations.ts | 106 +- types/hapi/test/server/server-events-once.ts | 13 +- types/hapi/test/server/server-events.ts | 15 +- types/hapi/test/server/server-expose.ts | 4 +- types/hapi/test/server/server-inject.ts | 2 +- types/hapi/test/server/server-lookup.ts | 2 +- types/hapi/test/server/server-match.ts | 2 +- types/hapi/test/server/server-path.ts | 7 + types/hapi/test/server/server-state.ts | 2 +- types/hapi/test/server/server-table.ts | 2 +- types/hapi/tsconfig.json | 3 +- .../v16/test/response/error-representation.ts | 10 - types/hapi/v16/tsconfig.json | 2 +- types/nes/index.d.ts | 4 +- types/nes/test/nes-tests.ts | 6 +- types/nes/test/route-authentication-server.ts | 4 +- types/nes/test/route-invocation-server.ts | 2 +- types/vision/index.d.ts | 22 +- types/yar/index.d.ts | 2 +- 84 files changed, 4103 insertions(+), 3799 deletions(-) delete mode 100644 types/hapi/definitions/plugin/plugin-registered.d.ts delete mode 100644 types/hapi/definitions/plugin/plugin.d.ts delete mode 100644 types/hapi/definitions/request/request-auth.d.ts delete mode 100644 types/hapi/definitions/request/request-events.d.ts delete mode 100644 types/hapi/definitions/request/request-info.d.ts delete mode 100644 types/hapi/definitions/request/request-route.d.ts delete mode 100644 types/hapi/definitions/request/request.d.ts delete mode 100644 types/hapi/definitions/response/response-events.d.ts delete mode 100644 types/hapi/definitions/response/response-object.d.ts delete mode 100644 types/hapi/definitions/response/response-settings.d.ts delete mode 100644 types/hapi/definitions/response/response-toolkit.d.ts delete mode 100644 types/hapi/definitions/route/route-options-access.d.ts delete mode 100644 types/hapi/definitions/route/route-options-cache.d.ts delete mode 100644 types/hapi/definitions/route/route-options-cors.d.ts delete mode 100644 types/hapi/definitions/route/route-options-payload.d.ts delete mode 100644 types/hapi/definitions/route/route-options-pre.d.ts delete mode 100644 types/hapi/definitions/route/route-options-response.d.ts delete mode 100644 types/hapi/definitions/route/route-options-secure.d.ts delete mode 100644 types/hapi/definitions/route/route-options-validate.d.ts delete mode 100644 types/hapi/definitions/route/route-options.d.ts delete mode 100644 types/hapi/definitions/server/server-auth-scheme.d.ts delete mode 100644 types/hapi/definitions/server/server-auth.d.ts delete mode 100644 types/hapi/definitions/server/server-cache.d.ts delete mode 100644 types/hapi/definitions/server/server-events.d.ts delete mode 100644 types/hapi/definitions/server/server-ext.d.ts delete mode 100644 types/hapi/definitions/server/server-info.d.ts delete mode 100644 types/hapi/definitions/server/server-inject.d.ts delete mode 100644 types/hapi/definitions/server/server-method.d.ts delete mode 100644 types/hapi/definitions/server/server-options-cache.d.ts delete mode 100644 types/hapi/definitions/server/server-options.d.ts delete mode 100644 types/hapi/definitions/server/server-realm.d.ts delete mode 100644 types/hapi/definitions/server/server-register.d.ts delete mode 100644 types/hapi/definitions/server/server-route.d.ts delete mode 100644 types/hapi/definitions/server/server-state-options.d.ts delete mode 100644 types/hapi/definitions/server/server-state.d.ts delete mode 100644 types/hapi/definitions/server/server.d.ts delete mode 100644 types/hapi/definitions/util/common.d.ts delete mode 100644 types/hapi/definitions/util/json.d.ts delete mode 100644 types/hapi/definitions/util/lifecycle.d.ts delete mode 100644 types/hapi/definitions/util/util.d.ts create mode 100644 types/hapi/test/route/ext.ts diff --git a/types/h2o2/tsconfig.json b/types/h2o2/tsconfig.json index 7cc2bc6d91..9d5b689ee1 100644 --- a/types/h2o2/tsconfig.json +++ b/types/h2o2/tsconfig.json @@ -28,4 +28,4 @@ "index.d.ts", "h2o2-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/hapi-auth-basic/hapi-auth-basic-tests.ts b/types/hapi-auth-basic/hapi-auth-basic-tests.ts index 875a53c104..e984656537 100644 --- a/types/hapi-auth-basic/hapi-auth-basic-tests.ts +++ b/types/hapi-auth-basic/hapi-auth-basic-tests.ts @@ -39,5 +39,5 @@ server.register(Basic).then(() => { server.auth.strategy('simple', 'basic', { validate }); server.auth.default('simple'); - server.route({ method: 'GET', path: '/', config: { auth: 'simple' } }); + server.route({ method: 'GET', path: '/', options: { auth: 'simple' } }); }); diff --git a/types/hapi/definitions/plugin/plugin-registered.d.ts b/types/hapi/definitions/plugin/plugin-registered.d.ts deleted file mode 100644 index 6ce68e5e85..0000000000 --- a/types/hapi/definitions/plugin/plugin-registered.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) - */ -export interface PluginsListRegistered { -} - -/** - * An object of the currently registered plugins where each key is a registered plugin name and the value is an - * object containing: - * * version - the plugin version. - * * name - the plugin name. - * * options - (optional) options passed to the plugin during registration. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) - */ -export interface PluginRegistered { - - /** - * the plugin version. - */ - version: string; - - /** - * the plugin name. - */ - name: string; - - /** - * options used to register the plugin. - */ - options: object; - -} diff --git a/types/hapi/definitions/plugin/plugin.d.ts b/types/hapi/definitions/plugin/plugin.d.ts deleted file mode 100644 index 925ac02205..0000000000 --- a/types/hapi/definitions/plugin/plugin.d.ts +++ /dev/null @@ -1,58 +0,0 @@ -import {Server, ServerRegisterOptions} from "hapi"; - -export interface PluginsStates { -} - -export interface PluginSpecificConfiguration { - -} - -export interface PluginNameVersion { - /** - * (required) the plugin name string. The name is used as a unique key. Published plugins (e.g. published in the npm - * registry) should use the same name as the name field in their 'package.json' file. Names must be - * unique within each application. - */ - name: string; - - /** optional plugin version. The version is only used informatively to enable other plugins to find out the versions loaded. The version should be the same as the one specified in the plugin's 'package.json' file. */ - version?: string; -} - -export interface PluginPackage { - - /** - * Alternatively, the name and version can be included via the pkg property containing the 'package.json' file for the module which already has the name and version included - */ - pkg: any; -} - -/** - * Plugins provide a way to organize application code by splitting the server logic into smaller components. Each - * plugin can manipulate the server through the standard server interface, but with the added ability to sandbox - * certain properties. For example, setting a file path in one plugin doesn't affect the file path set - * in another plugin. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#plugins) - * - * The type T is the type of the plugin options. - */ -export interface PluginBase { - - /** - * (required) the registration function with the signature async function(server, options) where: - * * server - the server object with a plugin-specific server.realm. - * * options - any options passed to the plugin during registration via server.register(). - */ - register: (server: Server, options: T) => Promise; - - /** (optional) if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */ - multiple?: boolean; - - /** (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via server.dependency(). */ - dependencies?: string | string[]; - - /** once - (optional) if true, will only register the plugin once per server. If set, overrides the once option passed to server.register(). Defaults to no override. */ - once?: boolean; -} - -export type Plugin = PluginBase & (PluginNameVersion | PluginPackage); diff --git a/types/hapi/definitions/request/request-auth.d.ts b/types/hapi/definitions/request/request-auth.d.ts deleted file mode 100644 index d2f22e81cd..0000000000 --- a/types/hapi/definitions/request/request-auth.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * User-extensible type for request.auth credentials. - */ -export interface AuthCredentials { - user?: string; -} - -/** - * Authentication information: - * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. - * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. - * * error - the authentication error is failed and mode set to 'try'. - * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. - * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization, set to false. - * * mode - the route authentication mode. - * * strategy - the name of the strategy used. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) - */ -export interface RequestAuth { - /** an artifact object received from the authentication strategy and used in authentication-related actions. */ - artifacts: object; - /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ - credentials: AuthCredentials; - /** the authentication error is failed and mode set to 'try'. */ - error: Error; - /** true if the request has been successfully authenticated, otherwise false. */ - isAuthenticated: boolean; - /** true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization, set to false. */ - isAuthorized: boolean; - /** the route authentication mode. */ - mode: string; - /** the name of the strategy used. */ - strategy: string; -} diff --git a/types/hapi/definitions/request/request-events.d.ts b/types/hapi/definitions/request/request-events.d.ts deleted file mode 100644 index dfcb004d24..0000000000 --- a/types/hapi/definitions/request/request-events.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -import * as Podium from "podium"; -import {PeekListener} from "hapi"; - -/** - * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). - * 'finish' - emitted when the request payload finished reading. The event method signature is function (). - * 'disconnect' - emitted when a request errors or aborts unexpectedly. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) - */ -export type RequestEventType = "peek" | "finish" | "disconnect"; - -/** - * Access: read only and the public podium interface. - * The request.events supports the following events: - * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). - * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). - * * 'disconnect' - emitted when a request errors or aborts unexpectedly. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) - */ -export interface RequestEvents extends Podium { - - /** - * Access: read only and the public podium interface. - * The request.events supports the following events: - * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). - * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). - * * 'disconnect' - emitted when a request errors or aborts unexpectedly. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) - */ - on(criteria: "peek", listener: PeekListener): void; - on(criteria: "finish" | "disconnect", listener: () => void): void; - on(criteria: RequestEventType, listener: Function): void; - - /** - * Access: read only and the public podium interface. - * The request.events supports the following events: - * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). - * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). - * * 'disconnect' - emitted when a request errors or aborts unexpectedly. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) - */ - once(criteria: "peek", listener: PeekListener): void; - once(criteria: "finish" | "disconnect", listener: () => void): void; - once(criteria: RequestEventType, listener: Function): void; -} diff --git a/types/hapi/definitions/request/request-info.d.ts b/types/hapi/definitions/request/request-info.d.ts deleted file mode 100644 index a4892438a2..0000000000 --- a/types/hapi/definitions/request/request-info.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Request information: - * * acceptEncoding - the request preferred encoding. - * * cors - if CORS is enabled for the route, contains the following: - * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. - * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). - * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). - * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). - * * received - request reception timestamp. - * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. - * * remoteAddress - remote client IP address. - * * remotePort - remote client port. - * * responded - request response timestamp (0 is not responded yet). - * Note that the request.info object is not meant to be modified. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) - */ -export interface RequestInfo { - /** the request preferred encoding. */ - acceptEncoding: string; - /** if CORS is enabled for the route, contains the following: */ - cors: { - /** - * true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. - */ - isOriginMatch?: boolean; - }; - /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ - host: string; - /** the hostname part of the 'Host' header (e.g. 'example.com'). */ - hostname: string; - /** request reception timestamp. */ - received: number; - /** content of the HTTP 'Referrer' (or 'Referer') header. */ - referrer: string; - /** remote client IP address. */ - remoteAddress: string; - /** remote client port. */ - remotePort: string; - /** request response timestamp (0 is not responded yet). */ - responded: number; -} diff --git a/types/hapi/definitions/request/request-route.d.ts b/types/hapi/definitions/request/request-route.d.ts deleted file mode 100644 index fbafd033a6..0000000000 --- a/types/hapi/definitions/request/request-route.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -import {Request, RouteOptions, ServerRealm, Util} from "hapi"; - -/** - * The request route information object, where: - * * method - the route HTTP method. - * * path - the route path. - * * vhost - the route vhost option if configured. - * * realm - the active realm associated with the route. - * * settings - the route options object with all defaults applied. - * * fingerprint - the route internal normalized string representing the normalized path. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) - */ -export interface RequestRoute { - - /** the route HTTP method. */ - method: Util.HTTP_METHODS_PARTIAL; - - /** the route path. */ - path: string; - - /** the route vhost option if configured. */ - vhost?: string | string[]; - - /** the active realm associated with the route.*/ - realm: ServerRealm; - - /** the route options object with all defaults applied. */ - settings: RouteOptions; - - /** the route internal normalized string representing the normalized path. */ - fingerprint: string; - - auth: { - /** - * Validates a request against the route's authentication access configuration, where: - * @param request - the request object. - * @return Return value: true if the request would have passed the route's access requirements. - * Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access configuration. - * If the route uses dynamic scopes, the scopes are constructed against the request.query, request.params, request.payload, and request.auth.credentials which may or may not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or not at all), it will return false if the route requires any authentication. - * [See docs](https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest) - */ - access(request: Request): boolean; - } - -} diff --git a/types/hapi/definitions/request/request.d.ts b/types/hapi/definitions/request/request.d.ts deleted file mode 100644 index f04a57be96..0000000000 --- a/types/hapi/definitions/request/request.d.ts +++ /dev/null @@ -1,224 +0,0 @@ -import * as stream from "stream"; -import * as url from "url"; -import * as http from "http"; -import * as Podium from "podium"; -import {ApplicationState, PluginsStates, RequestAuth, RequestEvents, RequestInfo, RequestRoute, ResponseObject, ResponseValue, Server, Util} from "hapi"; - -/** - * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestorig) - */ -export interface RequestOrig { - params: object; - query: object; - payload: object; -} - -export interface RequestLog { - request: string; - timestamp: number; - tags: string[]; - data: string | object; - channel: string; -} - -/** - * The request object is created internally for each incoming request. It is not the same object received from the node - * HTTP server callback (which is available via [request.raw.req](https://github.com/hapijs/hapi/blob/master/API.md#request.raw)). The request properties change throughout - * the request [lifecycle](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle). - */ -export interface Request extends Podium { - - /** - * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestapp) - */ - app: ApplicationState; - - /** - * Authentication information: - * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. - * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. - * * error - the authentication error is failed and mode set to 'try'. - * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. - * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization, set to false. - * * mode - the route authentication mode. - * * strategy - the name of the strategy used. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) - */ - readonly auth: RequestAuth; - - /** - * Access: read only and the public podium interface. - * The request.events supports the following events: - * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). - * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). - * * 'disconnect' - emitted when a request errors or aborts unexpectedly. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) - */ - events: RequestEvents; - - /** - * The raw request headers (references request.raw.req.headers). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders) - */ - readonly headers: Util.Dictionary; - - /** - * Request information: - * * acceptEncoding - the request preferred encoding. - * * cors - if CORS is enabled for the route, contains the following: - * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. - * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). - * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). - * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). - * * received - request reception timestamp. - * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. - * * remoteAddress - remote client IP address. - * * remotePort - remote client port. - * * responded - request response timestamp (0 is not responded yet). - * Note that the request.info object is not meant to be modified. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) - */ - readonly info: RequestInfo; - - /** - * An array containing the logged request events. - * Note that this array will be empty if route log.collect is set to false. - */ - readonly logs: RequestLog[]; - - /** - * The request method in lower case (e.g. 'get', 'post'). - */ - readonly method: Util.HTTP_METHODS_PARTIAL_LOWERCASE; - - /** - * The parsed content-type header. Only available when payload parsing enabled and no payload error occurred. - */ - readonly mime: string; - - /** - * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. - */ - readonly orig: RequestOrig; - - /** - * An object where each key is a path parameter name with matching value as described in [Path parameters](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters). - */ - readonly params: Util.Dictionary; - - /** - * An array containing all the path params values in the order they appeared in the path. - */ - readonly paramsArray: string[]; - - /** - * The request URI's pathname component. - */ - readonly path: string; - - /** - * The request payload based on the route payload.output and payload.parse settings. - * TODO check this typing and add references / links. - */ - readonly payload: stream.Readable | Buffer | string | object; - - /** - * Plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. - */ - plugins: PluginsStates; - - /** - * An object where each key is the name assigned by a route pre-handler methods function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses. - */ - readonly pre: Util.Dictionary; - - /** - * Access: read / write (see limitations below). - * The response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects). - */ - response: ResponseObject | null; - - /** - * Same as pre but represented as the response object created by the pre method. - */ - readonly preResponses: Util.Dictionary; - - /** - * By default the object outputted from node's URL parse() method. Might also be set indirectly via request.setUrl in which case it may be a string (if url is set to an object with the query attribute as an unparsed string). - */ - readonly query: any; - - /** - * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended. - * * req - the node request object. - * * res - the node response object. - */ - readonly raw: { - req: http.IncomingMessage; - res: http.ServerResponse; - }; - - /** - * The request route information object and method - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestrouteauthaccessrequest) - */ - readonly route: RequestRoute; - - /** - * Access: read only and the public server interface. - * The server object. - */ - server: Server; - - /** - * An object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. - */ - readonly state: Util.Dictionary; - - /** - * The parsed request URI. - */ - readonly url: url.Url; - - /** - * Returns a response which you can pass into the reply interface where: - * @param source - the value to set as the source of the reply interface, optional. - * @param options - options for the method, optional. - * @return ResponseObject - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestgenerateresponsesource-options) - */ - generateResponse(source: string | object | null, options?: {variety?: string; prepare?: (response: ResponseObject) => Promise; marshal?: (response: ResponseObject) => Promise; close?: (response: ResponseObject) => void; }): ResponseObject; - - /** - * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: - * @param tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. - * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. - * Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. - * @return void - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data) - */ - log(tags: string | string[], data?: string | object | (() => string | object)): void; - - /** - * Changes the request method before the router begins processing the request where: - * @param method - is the request HTTP method (e.g. 'GET'). - * @return void - * Can only be called from an 'onRequest' extension method. - * [See docs](https://hapijs.com/api/17.0.1#-requestsetmethodmethod) - */ - setMethod(method: Util.HTTP_METHODS_PARTIAL): void; - - /** - * Changes the request URI before the router begins processing the request where: - * Can only be called from an 'onRequest' extension method. - * @param url - the new request URI. If url is a string, it is parsed with node's URL parse() method with parseQueryString set to true. url can also be set to an object compatible with node's URL parse() method output. - * @param stripTrailingSlash - if true, strip the trailing slash from the path. Defaults to false. - * @return void - * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) - */ - setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void; - -} diff --git a/types/hapi/definitions/response/response-events.d.ts b/types/hapi/definitions/response/response-events.d.ts deleted file mode 100644 index b31fe0c21e..0000000000 --- a/types/hapi/definitions/response/response-events.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -import * as Podium from "podium"; -import {PeekListener} from "hapi"; - -/** - * Access: read only and the public podium interface. - * The response.events object supports the following events: - * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). - * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). - * [See docs](https://hapijs.com/api/17.0.1#-responseevents) - */ -export interface ResponseEvents extends Podium { - - /** - * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). - * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). - */ - on(criteria: 'peek', listener: PeekListener): void; - on(criteria: 'finish', listener: () => void): void; - on(criteria: 'peek' | 'finish', listener: Function): void; - - /** - * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). - * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). - */ - once(criteria: 'peek', listener: PeekListener): void; - once(criteria: 'finish', listener: () => void): void; - once(criteria: 'peek' | 'finish', listener: Function): void; - -} diff --git a/types/hapi/definitions/response/response-object.d.ts b/types/hapi/definitions/response/response-object.d.ts deleted file mode 100644 index 4382338551..0000000000 --- a/types/hapi/definitions/response/response-object.d.ts +++ /dev/null @@ -1,288 +0,0 @@ -import * as Podium from "podium"; -import {ApplicationState, Json, Lifecycle, PluginsStates, ResponseEvents, ResponseSettings, ServerStateCookieOptions, Util} from "hapi"; - -/** - * Object where: - * * append - if true, the value is appended to any existing header value using separator. Defaults to false. - * * separator - string used as separator when appending to an existing value. Defaults to ','. - * * override - if false, the header value is not set if an existing value present. Defaults to true. - * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) - */ -export interface ResponseObjectHeaderOptions { - append?: boolean; - separator?: string; - override?: boolean; - duplicate?: boolean; -} - -/** - * The response object contains the request response value along with various HTTP headers and flags. When a lifecycle - * method returns a value, the value is wrapped in a response object along with some default flags (e.g. 200 status - * code). In order to customize a response before it is returned, the h.response() method is provided. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) - * TODO, check extending from Podium is correct. Extending because of "The response object supports the following events" [See docs](https://hapijs.com/api/17.0.1#-responseevents) - */ -export interface ResponseObject extends Podium { - - /** - * Default value: {}. - * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseapp) - */ - app: ApplicationState; - - /** - * Access: read only and the public podium interface. - * The response.events object supports the following events: - * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). - * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). - * [See docs](https://hapijs.com/api/17.0.1#-responseevents) - */ - readonly events: ResponseEvents; - - /** - * Default value: {}. - * An object containing the response headers where each key is a header field name and the value is the string header value or array of string. - * Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders) - */ - readonly headers: Util.Dictionary; - - /** - * Default value: {}. - * Plugin-specific state. Provides a place to store and pass request-level plugin data. plugins is an object where each key is a plugin name and the value is the state. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseplugins) - */ - plugins: PluginsStates; - - /** - * Object containing the response handling flags. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) - */ - readonly settings: ResponseSettings; - - /** - * The raw value returned by the lifecycle method. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesource) - */ - readonly source: Lifecycle.ReturnValue; - - /** - * Default value: 200. - * The HTTP response status code. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatuscode) - */ - readonly statusCode: number; - - /** - * A string indicating the type of source with available values: - * * 'plain' - a plain response such as string, number, null, or simple object. - * * 'buffer' - a Buffer. - * * 'stream' - a Stream. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevariety) - */ - readonly variety: 'plain' | 'buffer' | 'stream'; - - /** - * Sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: - * @param length - the header value. Must match the actual payload size. - * @return Return value: the current response object. - * [See docs](https://hapijs.com/api/17.0.1#-responsebyteslength) - */ - bytes(length: number): ResponseObject; - - /** - * Sets the 'Content-Type' HTTP header 'charset' property where: - * @param charset - the charset property value. - * @return Return value: the current response object. - * [See docs](https://hapijs.com/api/17.0.1#-responsecharsetcharset) - */ - charset(charset: string): ResponseObject; - - /** - * Sets the 'Content-Type' HTTP header 'charset' property where: - * $param charset - the charset property value. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecodestatuscode) - */ - code(statusCode: number): ResponseObject; - - /** - * Sets the HTTP status message where: - * @param httpMessage - the HTTP status message (e.g. 'Ok' for status code 200). - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsemessagehttpmessage) - */ - message(httpMessage: string): ResponseObject; - - /** - * Sets the HTTP status code to Created (201) and the HTTP 'Location' header where: - * @param uri - an absolute or relative URI used as the 'Location' header value. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecreateduri) - */ - created(uri: string): ResponseObject; - - /** - * Sets the string encoding scheme used to serial data into the HTTP payload where: - * @param encoding the encoding property value (see node Buffer encoding [See docs](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)). - * * 'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set. - * * 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. - * * 'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported. - * * 'ucs2' - Alias of 'utf16le'. - * * 'base64' - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5. - * * 'latin1' - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes). - * * 'binary' - Alias for 'latin1'. - * * 'hex' - Encode each byte as two hexadecimal characters. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseencodingencoding) - */ - encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): ResponseObject; - - /** - * Sets the representation entity tag where: - * @param tag - the entity tag string without the double-quote. - * @param options - (optional) settings where: - * * weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. - * * vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseetagtag-options) - */ - etag(tag: string, options?: {weak: boolean, vary: boolean}): ResponseObject; - - /** - * Sets an HTTP header where: - * @param name - the header name. - * @param value - the header value. - * @param options - (optional) object where: - * * append - if true, the value is appended to any existing header value using separator. Defaults to false. - * * separator - string used as separator when appending to an existing value. Defaults to ','. - * * override - if false, the header value is not set if an existing value present. Defaults to true. - * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) - */ - header(name: string, value: string, options?: ResponseObjectHeaderOptions): ResponseObject; - - /** - * Sets the HTTP 'Location' header where: - * @param uri - an absolute or relative URI used as the 'Location' header value. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responselocationuri) - */ - location(uri: string): ResponseObject; - - /** - * Sets an HTTP redirection response (302) and decorates the response with additional methods, where: - * @param uri - an absolute or relative URI used to redirect the client to another resource. - * @return Return value: the current response object. - * Decorates the response object with the response.temporary(), response.permanent(), and response.rewritable() methods to easily change the default redirection code (302). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseredirecturi) - */ - redirect(uri: string): ResponseObject; - - /** - * Sets the JSON.stringify() replacer argument where: - * @param method - the replacer function or array. Defaults to none. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsereplacermethod) - */ - replacer(method: Json.StringifyReplacer): ResponseObject; - - /** - * Sets the JSON.stringify() space argument where: - * @param count - the number of spaces to indent nested object keys. Defaults to no indentation. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsespacescount) - */ - spaces(count: number): ResponseObject; - - /** - * Sets an HTTP cookie where: - * @param name - the cookie name. - * @param value - the cookie value. If no options.encoding is defined, must be a string. See server.state() for supported encoding values. - * @param options - (optional) configuration. If the state was previously registered with the server using server.state(), the specified keys in options are merged with the default server definition. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options) - */ - state(name: string, value: object | string, options?: ServerStateCookieOptions): ResponseObject; - - /** - * Sets a string suffix when the response is process via JSON.stringify() where: - * @param suffix - the string suffix. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesuffixsuffix) - */ - suffix(suffix: string): ResponseObject; - - /** - * Overrides the default route cache expiration rule for this response instance where: - * @param msec - the time-to-live value in milliseconds. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsettlmsec) - */ - ttl(msec: number): ResponseObject; - - /** - * Sets the HTTP 'Content-Type' header where: - * @param mimeType - is the mime type. - * @return Return value: the current response object. - * Should only be used to override the built-in default for each response type. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetypemimetype) - */ - type(mimeType: string): ResponseObject; - - /** - * Clears the HTTP cookie by setting an expired value where: - * @param name - the cookie name. - * @param options - (optional) configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified options are merged with the server definition. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseunstatename-options) - */ - unstate(name: string, options?: ServerStateCookieOptions): ResponseObject; - - /** - * Adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: - * @param header - the HTTP request header name. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevaryheader) - */ - vary(header: string): ResponseObject; - - /** - * Marks the response object as a takeover response. - * @return Return value: the current response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetakeover) - */ - takeover(): ResponseObject; - - /** - * Sets the status code to 302 or 307 (based on the response.rewritable() setting) where: - * @param isTemporary - if false, sets status to permanent. Defaults to true. - * @return Return value: the current response object. - * Only available after calling the response.redirect() method. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetemporaryistemporary) - */ - temporary(isTemporary: boolean): ResponseObject; - - /** - * Sets the status code to 301 or 308 (based on the response.rewritable() setting) where: - * @param isPermanent - if false, sets status to temporary. Defaults to true. - * @return Return value: the current response object. - * Only available after calling the response.redirect() method. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsepermanentispermanent) - */ - permanent(isPermanent: boolean): ResponseObject; - - /** - * Sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the response.temporary() or response.permanent() setting. Arguments: - * @param isRewritable - if false, sets to non-rewritable. Defaults to true. - * @return Return value: the current response object. - * Only available after calling the response.redirect() method. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responserewritableisrewritable) - */ - rewritable(isRewritable: boolean): ResponseObject; - -} diff --git a/types/hapi/definitions/response/response-settings.d.ts b/types/hapi/definitions/response/response-settings.d.ts deleted file mode 100644 index 0926878d1c..0000000000 --- a/types/hapi/definitions/response/response-settings.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -import {Json} from "hapi"; - -/** - * Object containing the response handling flags. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) - */ -export interface ResponseSettings { - - /** - * Defaults value: true. - * If true and source is a Stream, copies the statusCode and headers properties of the stream object to the outbound response. - */ - readonly passThrough: boolean; - - /** - * Default value: null (use route defaults). - * Override the route json options used when source value requires stringification. - */ - readonly stringify: Json.StringifyArguments; - - /** - * Default value: null (use route defaults). - * If set, overrides the route cache with an expiration value in milliseconds. - */ - readonly ttl: number; - - /** - * Default value: false. - * If true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present. - */ - varyEtag: boolean; - -} diff --git a/types/hapi/definitions/response/response-toolkit.d.ts b/types/hapi/definitions/response/response-toolkit.d.ts deleted file mode 100644 index 8fb64a6ea3..0000000000 --- a/types/hapi/definitions/response/response-toolkit.d.ts +++ /dev/null @@ -1,139 +0,0 @@ -import {Request, ResponseObject, ServerRealm, ServerStateCookieOptions} from "hapi"; - -/** - * See more about Lifecycle - * https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle - * - */ - -export type ResponseValue = string | object; - -export interface AuthenticationData { - credentials: object; - artifacts?: object; -} - -/** - * The response toolkit is a collection of properties and utilities passed to every [lifecycle method](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) - * It is somewhat hard to define as it provides both utilities for manipulating responses as well as other information. Since the - * toolkit is passed as a function argument, developers can name it whatever they want. For the purpose of this - * document the h notation is used. It is named in the spirit of the RethinkDB r method, with h for hapi. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit) - */ -export interface ResponseToolkit { - - /** - * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step - * without further interaction with the node response stream. It is the developer's responsibility to write - * and end the response directly via [request.raw.res](https://github.com/hapijs/hapi/blob/master/API.md#request.raw). - */ - readonly abandon: symbol; - - /** - * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step after - * calling request.raw.res.end()) to close the the node response stream. - */ - readonly close: symbol; - - /** - * A response symbol. Provides access to the route or server context set via the route [bind](https://github.com/hapijs/hapi/blob/master/API.md#route.options.bind) - * option or [server.bind()](https://github.com/hapijs/hapi/blob/master/API.md#server.bind()). - */ - readonly context: any; - - /** - * A response symbol. When returned by a lifecycle method, the request lifecycle continues without changing the response. - */ - readonly continue: symbol; - - /** - * The [server realm](https://github.com/hapijs/hapi/blob/master/API.md#server.realm) associated with the matching - * route. Defaults to the root server realm in the onRequest step. - */ - readonly realm: ServerRealm; - - /** - * Access: read only and public request interface. - * The [request] object. This is a duplication of the request lifecycle method argument used by - * [toolkit decorations](https://github.com/hapijs/hapi/blob/master/API.md#server.decorate()) to access the current request. - */ - readonly request: Readonly - - /** - * Used by the [authentication] method to pass back valid credentials where: - * @param data - an object with: - * * credentials - (required) object representing the authenticated entity. - * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. - * @return Return value: an internal authentication object. - */ - authenticated(data: AuthenticationData): object; - - /** - * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if - * the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request - * conditions, h.entity() returns a response object for the lifecycle method to return as its value which will - * set a 304 response. Otherwise, it sets the provided entity headers and returns undefined. - * The method argumetns are: - * @param options - a required configuration object with: - * * etag - the ETag string. Required if modified is not present. Defaults to no header. - * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header. - * * vary - same as the response.etag() option. Defaults to true. - * @return Return value: - a response object if the response is unmodified. - undefined if the response has changed. - * If undefined is returned, the developer must return a valid lifecycle method value. If a response is returned, - * it should be used as the return value (but may be customize using the response methods). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hentityoptions) - */ - entity(options?: {etag?: string, modified?: string, vary?: boolean}): ResponseObject | undefined; - - /** - * Redirects the client to the specified uri. Same as calling h.response().redirect(uri). - * @param url - * @return Returns a response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi) - */ - redirect(uri?: string): ResponseObject; - - /** - * Wraps the provided value and returns a response object which allows customizing the response - * (e.g. setting the HTTP status code, custom headers, etc.), where: - * @param value - (optional) return value. Defaults to null. - * @return Returns a response object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue) - */ - response(value?: ResponseValue): ResponseObject; - - /** - * Sets a response cookie using the same arguments as response.state(). - * @param name of the cookie - * @param value of the cookie - * @param (optional) ServerStateCookieOptions object. - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hstatename-value-options) - */ - state(name: string, value: string, options?: ServerStateCookieOptions): void; - - /** - * Used by the [authentication] method to indicate authentication failed and pass back the credentials received where: - * @param error - (required) the authentication error. - * @param data - (optional) an object with: - * * credentials - (required) object representing the authenticated entity. - * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. - * @return void. - * The method is used to pass both the authentication error and the credentials. For example, if a request included - * expired credentials, it allows the method to pass back the user information (combined with a 'try' - * authentication mode) for error customization. - * There is no difference between throwing the error or passing it with the h.unauthenticated() method is no credentials are passed, but it might still be helpful for code clarity. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunauthenticatederror-data) - */ - unauthenticated(error: Error, data?: AuthenticationData): void; - - /** - * Clears a response cookie using the same arguments as - * @param name of the cookie - * @param options (optional) ServerStateCookieOptions object. - * @return void. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunstatename-options) - */ - unstate(name: string, options?: ServerStateCookieOptions): void; - -} diff --git a/types/hapi/definitions/route/route-options-access.d.ts b/types/hapi/definitions/route/route-options-access.d.ts deleted file mode 100644 index 2446d7b1c4..0000000000 --- a/types/hapi/definitions/route/route-options-access.d.ts +++ /dev/null @@ -1,82 +0,0 @@ - -export type RouteOptionsAccessScope = false | string | string[]; - -export type RouteOptionsAccessEntity = 'any' | 'user' | 'app'; - -export interface RouteOptionsAccessScopeObject { - scope: RouteOptionsAccessScope; -} - -export interface RouteOptionsAccessEntityObject { - entity: RouteOptionsAccessEntity; -} - -export type RouteOptionsAccessObject = RouteOptionsAccessScopeObject | RouteOptionsAccessEntityObject | (RouteOptionsAccessScopeObject & RouteOptionsAccessEntityObject); - -/** - * Route Authentication Options - */ -export interface RouteOptionsAccess { - - /** - * Default value: none. - * An object or array of objects specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one of the rules matches. Each rule object must include at least one of scope or entity. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccess) - */ - access?: RouteOptionsAccessObject | RouteOptionsAccessObject[]; - - /** - * Default value: false (no scope requirements). - * The application scope required to access the route. Value can be a scope string or an array of scope strings. When authenticated, the credentials object scope property must contain at least one of the scopes defined to access the route. - * If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' scope must not include 'a', must include 'b', and must include one of 'c' or 'd'. - * You may also access properties on the request object (query, params, payload, and credentials) to populate a dynamic scope by using the '{' and '}' characters around the property name, such as 'user-{params.id}'. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope) - */ - scope?: RouteOptionsAccessScope; - - /** - * Default value: 'any'. - * The required authenticated entity type. If set, must match the entity value of the request authenticated credentials. Available values: - * * 'any' - the authentication can be on behalf of a user or application. - * * 'user' - the authentication must be on behalf of a user which is identified by the presence of a 'user' attribute in the credentials object returned by the authentication strategy. - * * 'app' - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessentity) - */ - entity?: RouteOptionsAccessEntity; - - /** - * Default value: 'required'. - * The authentication mode. Available values: - * * 'required' - authentication is required. - * * 'optional' - authentication is optional - the request must include valid credentials or no credentials at all. - * * 'try' - similar to 'optional', any request credentials are attempted authentication, but if the credentials are invalid, the request proceeds regardless of the authentication error. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthmode) - */ - mode?: 'required' | 'optional' | 'try'; - - /** - * Default value: false, unless the scheme requires payload authentication. - * If set, the incoming request payload is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. Hawk). Cannot be set to a value other than 'required' when the scheme sets the authentication options.payload to true. - * Available values: - * * false - no payload authentication. - * * 'required' - payload authentication required. - * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthpayload) - */ - payload?: false | 'required' | 'optional'; - - /** - * Default value: the default strategy set via server.auth.default(). - * An array of string strategy names in the order they should be attempted. Cannot be used together with strategy. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategies) - */ - strategies?: string[]; - - /** - * Default value: the default strategy set via server.auth.default(). - * A string strategy names. Cannot be used together with strategies. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategy) - */ - strategy?: string; - -} diff --git a/types/hapi/definitions/route/route-options-cache.d.ts b/types/hapi/definitions/route/route-options-cache.d.ts deleted file mode 100644 index 1b17ee4e96..0000000000 --- a/types/hapi/definitions/route/route-options-cache.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Values are: - * * * 'default' - no privacy flag. - * * * 'public' - mark the response as suitable for public caching. - * * * 'private' - mark the response as suitable only for private caching. - * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. - * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. - * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. - * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) - */ -export type RouteOptionsCache = { - privacy?: 'default' | 'public' | 'privacy'; - statuses?: number[]; - otherwise?: string; -} & ( - { - expiresIn?: number; - expiresAt?: undefined; - } | { - expiresIn?: undefined; - expiresAt?: string; - } | { - expiresIn?: undefined; - expiresAt?: undefined; - } -); diff --git a/types/hapi/definitions/route/route-options-cors.d.ts b/types/hapi/definitions/route/route-options-cors.d.ts deleted file mode 100644 index 8264680ec8..0000000000 --- a/types/hapi/definitions/route/route-options-cors.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Default value: false (no CORS headers). - * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain than the API server. To enable, set cors to true, or to an object with the following options: - * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any origin ['*']. - * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to 86400 (one day). - * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. - * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. - * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. - * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. - * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) - */ -export interface RouteOptionsCors { - /** - * an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any origin ['*']. - */ - origin?: string[] | '*'| 'ignore'; - /** - * number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to 86400 (one day). - */ - maxAge?: number; - /** - * a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. - */ - headers?: string[]; - /** - * a strings array of additional headers to headers. Use this to keep the default headers in place. - */ - additionalHeaders?: string[]; - /** - * a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. - */ - exposedHeaders?: string[]; - /** - * a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. - */ - additionalExposedHeaders?: string[]; - /** - * if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. - */ - credentials?: boolean; -} diff --git a/types/hapi/definitions/route/route-options-payload.d.ts b/types/hapi/definitions/route/route-options-payload.d.ts deleted file mode 100644 index a13db35c32..0000000000 --- a/types/hapi/definitions/route/route-options-payload.d.ts +++ /dev/null @@ -1,122 +0,0 @@ -import {Lifecycle, Util} from "hapi"; - -/** - * The value must be one of: - * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw Buffer is returned. - * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the multipart payload in the handler using a streaming parser (e.g. pez). - * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) - */ -export type PayloadOutput = 'data' | 'stream' | 'file'; - -/** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) - */ -export type PayloadCompressionDecoderSettings = object; - -/** - * Determines how the request payload is processed. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) - */ -export interface RouteOptionsPayload { - - /** - * Default value: allows parsing of the following mime types: - * * application/json - * * application/*+json - * * application/octet-stream - * * application/x-www-form-urlencoded - * * multipart/form-data - * * text/* - * A string or an array of strings with the allowed mime types for the endpoint. Use this settings to limit the set of allowed mime types. Note that allowing additional mime types not listed above will not enable them to be parsed, and if parse is true, the request will result in an error response. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadallow) - */ - allow?: string | string[]; - - /** - * Default value: none. - * An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) - */ - compression?: Util.Dictionary; - - /** - * Default value: 'application/json'. - * The default content type if the 'Content-Type' request header is missing. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaddefaultcontenttype) - */ - defaultContentType?: string; - - /** - * Default value: 'error' (return a Bad Request (400) error response). - * A failAction value which determines how to handle payload parsing errors. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadfailaction) - */ - failAction?: Lifecycle.FailAction; - - /** - * Default value: 1048576 (1MB). - * Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmaxbytes) - */ - maxBytes?: number; - - /** - * Default value: none. - * Overrides payload processing for multipart requests. Value can be one of: - * * false - disable multipart processing. - * an object with the following required options: - * * output - same as the output option with an additional value option: - * * * annotated - wraps each multipart part in an object with the following keys: // TODO type this? - * * * * headers - the part headers. - * * * * filename - the part file name. - * * * * payload - the processed part payload. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmultipart) - */ - multipart?: false | { - output: PayloadOutput | 'annotated'; - }; - - /** - * Default value: 'data'. - * The processed payload format. The value must be one of: - * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw Buffer is returned. - * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the multipart payload in the handler using a streaming parser (e.g. pez). - * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) - */ - output?: PayloadOutput; - - /** - * Default value: none. - * A mime type string overriding the 'Content-Type' header value received. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoverride) - */ - override?: string; - - /** - * Default value: true. - * Determines if the incoming payload is processed or presented raw. Available values: - * * true - if the request 'Content-Type' matches the allowed mime types set by allow (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Any known content encoding is decoded. - * * false - the raw payload is returned unmodified. - * * 'gunzip' - the raw payload is returned unmodified after any known content encoding is decoded. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadparse) - */ - parse?: boolean | 'gunzip'; - - /** - * Default value: to 10000 (10 seconds). - * Payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response. - * Set to false to disable. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadtimeout) - */ - timeout?: false | number; - - /** - * Default value: os.tmpdir(). - * The directory used for writing file uploads. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaduploads) - */ - uploads?: string; - -} diff --git a/types/hapi/definitions/route/route-options-pre.d.ts b/types/hapi/definitions/route/route-options-pre.d.ts deleted file mode 100644 index 8745bf5a00..0000000000 --- a/types/hapi/definitions/route/route-options-pre.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -import {Lifecycle} from "hapi"; - -/** - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) - */ -export type RouteOptionsPreArray = RouteOptionsPreAllOptions[]; - -/** - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) - */ -export type RouteOptionsPreAllOptions = RouteOptionsPreObject | RouteOptionsPreObject[] | Lifecycle.Method; - -/** - * An object with: - * * method - a lifecycle method. - * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. - * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) - */ -export interface RouteOptionsPreObject { - /** - * a lifecycle method. - */ - method: Lifecycle.Method; - /** - * key name used to assign the response of the method to in request.pre and request.preResponses. - */ - assign: string; - /** - * A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. - */ - failAction?: Lifecycle.FailAction; -} diff --git a/types/hapi/definitions/route/route-options-response.d.ts b/types/hapi/definitions/route/route-options-response.d.ts deleted file mode 100644 index b0c3925bfe..0000000000 --- a/types/hapi/definitions/route/route-options-response.d.ts +++ /dev/null @@ -1,76 +0,0 @@ -import {Lifecycle, Util} from "hapi"; -import {ValidationOptions} from "joi"; - -export type RouteOptionsResponseSchema = boolean | ValidationOptions | ((value: object | Buffer | string, options: ValidationOptions) => Promise); - -/** - * Processing rules for the outgoing response. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) - */ -export interface RouteOptionsResponse { - - /** - * Default value: 200. - * The default HTTP status code when the payload is considered empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time of response transmission (the response status code will remain 200 throughout the request lifecycle unless manually set). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseemptystatuscode) - */ - emptyStatusCode?: 200 | 204; - - /** - * Default value: 'error' (return an Internal Server Error (500) error response). - * A failAction value which defines what to do when a response fails payload validation. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsefailaction) - */ - failAction?: Lifecycle.FailAction; - - /** - * Default value: false. - * If true, applies the validation rule changes to the response payload. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsemodify) - */ - modify?: boolean; - - /** - * Default value: none. - * [joi](http://github.com/hapijs/joi) options object pass to the validation function. Useful to set global options such as stripUnknown or abortEarly (the complete list is available here). If a custom validation function is defined via schema or status then options can an arbitrary object that will be passed to this function as the second argument. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseoptions) - */ - options?: ValidationOptions; // TODO needs validation - - /** - * Default value: true. - * If false, payload range support is disabled. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseranges) - */ - ranges?: boolean; - - /** - * Default value: 100 (all responses). - * The percent of response payloads validated (0 - 100). Set to 0 to disable all validation. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsesample) - */ - sample?: number; - - /** - * Default value: true (no validation). - * The default response payload validation rules (for all non-error responses) expressed as one of: - * * true - any payload allowed (no validation). - * * false - no payload allowed. - * * a joi validation object. The options along with the request context ({ headers, params, query, payload, app, auth }) are passed to the validation function. - * * a validation function using the signature async function(value, options) where: - * * * value - the pending response payload. - * * * options - The options along with the request context ({ headers, params, query, payload, app, auth }). - * * * if the function returns a value and modify is true, the value is used as the new response. If the original response is an error, the return value is used to override the original error output.payload. If an error is thrown, the error is processed according to failAction. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseschema) - */ - schema?: RouteOptionsResponseSchema; - - /** - * Default value: none. - * Validation schemas for specific HTTP status codes. Responses (excluding errors) not matching the listed status codes are validated using the default schema. - * status is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus) - */ - status?: Util.Dictionary; - -} diff --git a/types/hapi/definitions/route/route-options-secure.d.ts b/types/hapi/definitions/route/route-options-secure.d.ts deleted file mode 100644 index 669d1371ed..0000000000 --- a/types/hapi/definitions/route/route-options-secure.d.ts +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Default value: false (security headers disabled). - * Sets common security headers. To enable, set security to true or to an object with the following options: - * * hsts - controls the 'Strict-Transport-Security' header, where: - * * * true - the header will be set to max-age=15768000. This is the default value. - * * * a number - the maxAge parameter will be set to the provided value. - * * * an object with the following fields: - * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000. - * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header. - * * * * preload - a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. - * * xframe - controls the 'X-Frame-Options' header, where: - * * * true - the header will be set to 'DENY'. This is the default value. - * * * 'deny' - the headers will be set to 'DENY'. - * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'. - * * * an object for specifying the 'allow-from' rule, where: - * * * * rule - one of: - * * * * * 'deny' - * * * * * 'sameorigin' - * * * * * 'allow-from' - * * * * source - when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. - * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. - * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively support old versions of IE, it may be wise to explicitly set this flag to false. - * * noOpen - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. - * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) - */ -export interface RouteOptionsSecureObject { - /** - * hsts - controls the 'Strict-Transport-Security' header - */ - hsts?: boolean | number | { - /** - * the max-age portion of the header, as a number. Default is 15768000. - */ - maxAge: number; - /** - * a boolean specifying whether to add the includeSubDomains flag to the header. - */ - includeSubdomains: boolean; - /** - * a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. - */ - preload: boolean; - }; - /** - * controls the 'X-Frame-Options' header - */ - xframe?: true | 'deny' | 'sameorigin' | { - /** - * an object for specifying the 'allow-from' rule, - */ - rule: 'deny' | 'sameorigin' | 'allow-from'; - /** - * when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. - */ - source: string; - }; - /** - * boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. - * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively support old versions of IE, it may be wise to explicitly set this flag to false. - */ - xss: boolean; - /** - * boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. - */ - noOpen?: boolean; - /** - * boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. - */ - noSniff?: boolean; -} - - -export type RouteOptionsSecure = boolean | RouteOptionsSecureObject; diff --git a/types/hapi/definitions/route/route-options-validate.d.ts b/types/hapi/definitions/route/route-options-validate.d.ts deleted file mode 100644 index 7fa61d5bef..0000000000 --- a/types/hapi/definitions/route/route-options-validate.d.ts +++ /dev/null @@ -1,92 +0,0 @@ -import {Lifecycle, RouteOptionsResponseSchema} from "hapi"; -import {ValidationOptions} from "joi"; - -/** - * Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. - * Request input validation rules for various request components. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) - */ -export interface RouteOptionsValidate { - - /** - * Default value: none. - * An optional object with error fields copied into every validation error response. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateerrorfields) - */ - errorFields?: object; - - /** - * Default value: 'error' (return a Bad Request (400) error response). - * A failAction value which determines how to handle failed validations. When set to a function, the err argument includes the type of validation error under err.output.payload.validation.source. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatefailaction) - */ - failAction?: Lifecycle.FailAction; - - /** - * Default value: true (no validation). - * Validation rules for incoming request headers: - * * true - any headers allowed (no validation performed). - * * a joi validation object. - * * a validation function using the signature async function(value, options) where: - * * * value - the request.headers object containing the request headers. - * * * options - options. - * * * if a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error is thrown, the error is handled according to failAction. - * Note that all header field names must be in lowercase to match the headers normalized by node. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateheaders) - */ - headers?: RouteOptionsResponseSchema; - - /** - * Default value: none. - * An options object passed to the joi rules or the custom validation methods. Used for setting global options such as stripUnknown or abortEarly (the complete list is available here). - * If a custom validation function (see headers, params, query, or payload above) is defined then options can an arbitrary object that will be passed to this function as the second parameter. - * The values of the other inputs (i.e. headers, query, params, payload, app, and auth) are added to the options object under the validation context (accessible in rules as Joi.ref('$query.key')). - * Note that validation is performed in order (i.e. headers, params, query, and payload) and if type casting is used (e.g. converting a string to a number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values. - * If the validation rules for headers, params, query, and payload are defined at both the server routes level and at the route level, the individual route settings override the routes defaults (the rules are not merged). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) - */ - options?: ValidationOptions | object; - - /** - * Default value: true (no validation). - * Validation rules for incoming request path parameters, after matching the path against the route, extracting any parameters, and storing them in request.params, where: - * * true - any path parameter value allowed (no validation performed). - * * a joi validation object. - * * a validation function using the signature async function(value, options) where: - * * * value - the request.params object containing the request path parameters. - * * * options - options. - * if a value is returned, the value is used as the new request.params value and the original value is stored in request.orig.params. Otherwise, the path parameters are left unchanged. If an error is thrown, the error is handled according to failAction. - * Note that failing to match the validation rules to the route path parameters definition will cause all requests to fail. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) - */ - params?: RouteOptionsResponseSchema; - - /** - * Default value: true (no validation). - * Validation rules for incoming request payload (request body), where: - * * true - any payload allowed (no validation performed). false - no payload allowed. - * * a joi validation object. Note that empty payloads are represented by a null value. If a validation schema is provided and empty payload are allowed, the schema must be explicitly defined by setting the rule to a joi schema with null allowed (e.g. Joi.object({ keys here }).allow(null)). - * * a validation function using the signature async function(value, options) where: - * * * value - the request.query object containing the request query parameters. - * * * options - options. - * if a value is returned, the value is used as the new request.payload value and the original value is stored in request.orig.payload. Otherwise, the payload is left unchanged. If an error is thrown, the error is handled according to failAction. - * Note that validating large payloads and modifying them will cause memory duplication of the payload (since the original is kept), as well as the significant performance cost of validating large amounts of data. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatepayload) - */ - payload?: RouteOptionsResponseSchema; - - /** - * Default value: true (no validation). - * Validation rules for incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs, decoded, and stored in request.query prior to validation. Where: - * * true - any query parameter value allowed (no validation performed). false - no query parameter value allowed. - * * a joi validation object. - * * a validation function using the signature async function(value, options) where: - * * * value - the request.query object containing the request query parameters. - * * * options - options. - * if a value is returned, the value is used as the new request.query value and the original value is stored in request.orig.query. Otherwise, the query parameters are left unchanged. If an error is thrown, the error is handled according to failAction. - * Note that changes to the query parameters will not be reflected in request.url. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatequery) - */ - query?: RouteOptionsResponseSchema; - -} diff --git a/types/hapi/definitions/route/route-options.d.ts b/types/hapi/definitions/route/route-options.d.ts deleted file mode 100644 index e66668c75c..0000000000 --- a/types/hapi/definitions/route/route-options.d.ts +++ /dev/null @@ -1,284 +0,0 @@ -import { - Json, - Lifecycle, - PluginSpecificConfiguration, - RouteOptionsAccess, - RouteOptionsCache, - RouteOptionsCors, - RouteOptionsPayload, - RouteOptionsPreArray, - RouteOptionsResponse, - RouteOptionsSecure, - RouteOptionsValidate, - Util -} from "hapi"; - -/** - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) - */ -export type RouteCompressionEncoderSettings = object; - -/** - * Each route can be customized to change the default behavior of the request lifecycle. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#route-options) - */ -export interface RouteOptions { - - /** - * Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) - */ - app?: any; - - /** - * Route authentication configuration. Value can be: - * false to disable authentication if a default strategy is set. - * a string with the name of an authentication strategy registered with server.auth.strategy(). The strategy will be set to 'required' mode. - * an authentication configuration object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) - */ - auth?: false | string | RouteOptionsAccess; - - /** - * Default value: null. - * An object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsbind) - */ - bind?: object | null; - - /** - * Default value: { privacy: 'default', statuses: [200], otherwise: 'no-cache' }. - * If the route method is 'GET', the route can be configured to include HTTP caching directives in the response. Caching can be customized using an object with the following options: - * privacy - determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are: - * * * 'default' - no privacy flag. - * * * 'public' - mark the response as suitable for public caching. - * * * 'private' - mark the response as suitable only for private caching. - * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. - * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. - * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. - * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. - * The default Cache-Control: no-cache header can be disabled by setting cache to false. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) - */ - cache?: false | RouteOptionsCache; - - /** - * An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) - */ - compression?: Util.Dictionary; - - /** - * Default value: false (no CORS headers). - * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain than the API server. To enable, set cors to true, or to an object with the following options: - * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any origin ['*']. - * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to 86400 (one day). - * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. - * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. - * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. - * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. - * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) - */ - cors?: false | RouteOptionsCors; - - /** - * Default value: none. - * Route description used for generating documentation (string). - * This setting is not available when setting server route defaults using server.options.routes. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsdescription) - */ - description?: string; - - /** - * Default value: none. - * Route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the server.ext(events) event argument. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsext) - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) - */ - ext?: object; - - /** - * Default value: { relativeTo: '.' }. - * Defines the behavior for accessing files: - * * relativeTo - determines the folder relative paths are resolved against. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsfiles) - */ - files?: { - relativeTo: string; - } - - /** - * Default value: none. - * The route handler function performs the main business logic of the route and sets the response. handler can be assigned: - * * a lifecycle method. - * * an object with a single property using the name of a handler type registred with the server.handler() method. The matching property value is passed as options to the registered handler generator. - * Note: handlers using a fat arrow style function cannot be bound to any bind property. Instead, the bound context is available under h.context. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionshandler) - */ - handler?: Lifecycle.Method | object; - - /** - * Default value: none. - * An optional unique identifier used to look up the route using server.lookup(). Cannot be assigned to routes added with an array of methods. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsid) - */ - id?: string; - - /** - * Default value: false. - * If true, the route cannot be accessed through the HTTP listener but only through the server.inject() interface with the allowInternals option set to true. Used for internal routes that should not be accessible to the outside world. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsisinternal) - */ - isInternal?: boolean; - - /** - * Default value: none. - * Optional arguments passed to JSON.stringify() when converting an object or error response to a string payload or escaping it after stringification. Supports the following: - * * replacer - the replacer function or array. Defaults to no action. - * * space - number of spaces to indent nested object keys. Defaults to no indentation. - * * suffix - string suffix added after conversion to JSON string. Defaults to no suffix. - * * escape - calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) - */ - json?: Json.StringifyArguments; - - /** - * Default value: none. - * Enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload. - * For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'. Cannot be used with stream responses. - * The 'Content-Type' response header is set to 'text/javascript' and the 'X-Content-Type-Options' response header is set to 'nosniff', and will override those headers even if explicitly set by response.type(). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjsonp) - */ - jsonp?: string; - - /** - * Default value: { collect: false }. - * Request logging options: - * collect - if true, request-level logs (both internal and application) are collected and accessible via request.logs. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionslog) - */ - log?: { - collect: boolean; - } - - /** - * Default value: none. - * Route notes used for generating documentation (string or array of strings). - * This setting is not available when setting server route defaults using server.options.routes. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsnotes) - */ - notes?: string | string[]; - - /** - * Determines how the request payload is processed. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) - */ - payload?: RouteOptionsPayload; - - /** - * Default value: {}. - * Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsplugins) - */ - plugins?: Util.Dictionary; - - /** - * Default value: none. - * The pre option allows defining methods for performing actions before the handler is called. These methods allow breaking the handler logic into smaller, reusable components that can be shared ascross routes, as well as provide a cleaner error handling of prerequisite operations (e.g. load required reference data from a database). - * pre is assigned an ordered array of methods which are called serially in order. If the pre array contains another array of methods as one of its elements, those methods are called in parallel. Note that during parallel execution, if any of the methods error, return a takeover response, or abort signal, the other parallel methods will continue to execute but will be ignored once completed. - * pre can be assigned a mixed array of: - * * an array containing the elements listed below, which are executed in parallel. - * * an object with: - * * * method - a lifecycle method. - * * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. - * * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. - * * a method function - same as including an object with a single method key. - * Note that pre-handler methods do not behave the same way other lifecycle methods do when a value is returned. Instead of the return value becoming the new response payload, the value is used to assign the corresponding request.pre and request.preResponses properties. Otherwise, the handling of errors, takeover response response, or abort signal behave the same as any other lifecycle methods. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) - */ - pre?: RouteOptionsPreArray; - - /** - * Processing rules for the outgoing response. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) - */ - response?: RouteOptionsResponse; - - /** - * Default value: false (security headers disabled). - * Sets common security headers. To enable, set security to true or to an object with the following options: - * * hsts - controls the 'Strict-Transport-Security' header, where: - * * * true - the header will be set to max-age=15768000. This is the default value. - * * * a number - the maxAge parameter will be set to the provided value. - * * * an object with the following fields: - * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000. - * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header. - * * * * preload - a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. - * * xframe - controls the 'X-Frame-Options' header, where: - * * * true - the header will be set to 'DENY'. This is the default value. - * * * 'deny' - the headers will be set to 'DENY'. - * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'. - * * * an object for specifying the 'allow-from' rule, where: - * * * * rule - one of: - * * * * * 'deny' - * * * * * 'sameorigin' - * * * * * 'allow-from' - * * * * source - when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. - * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. - * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively support old versions of IE, it may be wise to explicitly set this flag to false. - * * noOpen - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. - * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) - */ - security?: RouteOptionsSecure; - - /** - * Default value: { parse: true, failAction: 'error' }. - * HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265). state supports the following options: - * parse - determines if incoming 'Cookie' headers are parsed and stored in the request.state object. - * failAction - A failAction value which determines how to handle cookie parsing errors. Defaults to 'error' (return a Bad Request (400) error response). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsstate) - */ - state?: { - parse?: boolean; - failAction?: Lifecycle.FailAction; - } - - /** - * Default value: none. - * Route tags used for generating documentation (array of strings). - * This setting is not available when setting server route defaults using server.options.routes. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstags) - */ - tags?: string[]; - - /** - * Default value: { server: false }. - * Timeouts for processing durations. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstimeout) - */ - timeout?: { - - /** - * Response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming request before giving up and responding with a Service Unavailable (503) error response. - */ - server?: boolean | number; - - /** - * Default value: none (use node default of 2 minutes). - * By default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Set to false to disable socket timeouts. - */ - socket?: boolean | number; - - }; - - /** - * Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. - * Request input validation rules for various request components. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) - */ - validate?: RouteOptionsValidate; - -} diff --git a/types/hapi/definitions/server/server-auth-scheme.d.ts b/types/hapi/definitions/server/server-auth-scheme.d.ts deleted file mode 100644 index 5eed01f0a0..0000000000 --- a/types/hapi/definitions/server/server-auth-scheme.d.ts +++ /dev/null @@ -1,74 +0,0 @@ -import {Lifecycle, Request, ResponseToolkit, Server} from "hapi"; - -/** - * The scheme options argument passed to server.auth.strategy() when instantiation a strategy. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) - */ -export type ServerAuthSchemeOptions = object; - -/** - * the method implementing the scheme with signature function(server, options) where: - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) - * @param server - a reference to the server object the scheme is added to. - * @param options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. - */ -export interface ServerAuthScheme { - (server: Server, options?: ServerAuthSchemeOptions): ServerAuthSchemeObject; -} - -export interface ServerAuthSchemeObjectApi { -} - -/** - * The scheme method must return an object with the following - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#authentication-scheme) - */ -export interface ServerAuthSchemeObject { - - /** - * optional object which is exposed via the [server.auth.api](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.api) object. - */ - api?: ServerAuthSchemeObjectApi; - - /** - * A lifecycle method function called for each incoming request configured with the authentication scheme. The - * method is provided with two special toolkit methods for returning an authenticated or an unauthenticate result: - * * h.authenticated() - indicate request authenticated successfully. - * * h.unauthenticated() - indicate request failed to authenticate. - * @param request the request object. - * @param h the ResponseToolkit - * @return the Lifecycle.ReturnValue - */ - authenticate(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; - - /** - * A lifecycle method to authenticate the request payload. - * 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'. - * @param request the request object. - * @param h the ResponseToolkit - * @return the Lifecycle.ReturnValue - */ - payload?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; - - /** - * A lifecycle method to decorate the response with authentication headers before the response headers or payload is written. - * @param request the request object. - * @param h the ResponseToolkit - * @return the Lifecycle.ReturnValue - */ - response?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; - - /** - * An object with the following keys: - * * payload - */ - options?: { - /** - * if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false. - */ - payload?: boolean; - }; - -} diff --git a/types/hapi/definitions/server/server-auth.d.ts b/types/hapi/definitions/server/server-auth.d.ts deleted file mode 100644 index 92cb0c4c98..0000000000 --- a/types/hapi/definitions/server/server-auth.d.ts +++ /dev/null @@ -1,82 +0,0 @@ -import {Request, RouteOptionsAccess, ServerAuthScheme, Util} from "hapi"; - -/** - * An authentication configuration object using the same format as the route auth handler options. - * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) - */ -export interface ServerAuthConfig extends RouteOptionsAccess { - -} - -export interface ServerAuth { - - /** - * An object where each key is an authentication strategy name and the value is the exposed strategy API. - * Available only when the authentication scheme exposes an API by returning an api key in the object - * returned from its implementation function. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi) - */ - api: Util.Dictionary; - - /** - * Contains the default authentication configuration is a default strategy was set via - * [server.auth.default()](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.default()). - */ - readonly settings: { - default: ServerAuthConfig; - } - - /** - * Sets a default strategy which is applied to every route where: - * @param options - one of: - * * a string with the default strategy name - * * an authentication configuration object using the same format as the route auth handler options. - * @return void. - * The default does not apply when a route config specifies auth as false, or has an authentication strategy - * configured (contains the strategy or strategies authentication settings). Otherwise, the route authentication - * config is applied to the defaults. - * Note that if the route has authentication configured, the default only applies at the time of adding the route, - * not at runtime. This means that calling server.auth.default() after adding a route with some authentication - * config will have no impact on the routes added prior. However, the default will apply to routes added - * before server.auth.default() is called if those routes lack any authentication config. - * The default auth strategy configuration can be accessed via server.auth.settings.default. To obtain the active - * authentication configuration of a route, use server.auth.lookup(request.route). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) - */ - default(options: string | ServerAuthConfig): void; - - /** - * Registers an authentication scheme where: - * @param name the scheme name. - * @param scheme - the method implementing the scheme with signature function(server, options) where: - * * server - a reference to the server object the scheme is added to. - * * options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. - * @return void. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) - */ - scheme(name: string, scheme: ServerAuthScheme): void; - - /** - * Registers an authentication strategy where: - * @param name - the strategy name. - * @param scheme - the scheme name (must be previously registered using server.auth.scheme()). - * @param options - scheme options based on the scheme requirements. - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthstrategyname-scheme-options) - */ - strategy(name: string, scheme: string, options?: object): void; - - /** - * Tests a request against an authentication strategy where: - * @param strategy - the strategy name registered with server.auth.strategy(). - * @param request - the request object. - * @return Return value: the authentication credentials object if authentication was successful, otherwise throws an error. - * Note that the test() method does not take into account the route authentication configuration. It also does not - * perform payload authentication. It is limited to the basic strategy authentication execution. It does not - * include verifying scope, entity, or other route properties. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) - */ - test(strategy: string, request: Request): Promise; - -} - diff --git a/types/hapi/definitions/server/server-cache.d.ts b/types/hapi/definitions/server/server-cache.d.ts deleted file mode 100644 index 730f5e8675..0000000000 --- a/types/hapi/definitions/server/server-cache.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -import * as catbox from "catbox"; -import {ServerOptionsCache} from "hapi"; - -/** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) - */ -export interface ServerCache { - - /** - * Provisions a cache segment within the server cache facility where: - * @param options - [catbox policy](https://github.com/hapijs/catbox#policy) configuration where: - * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. - * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. - * * generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is async function(id, flags) where: - * - `id` - the `id` string or object provided to the `get()` method. - * - `flags` - an object used to pass back additional flags to the cache where: - * - `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy. - * * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. - * * staleTimeout - number of milliseconds to wait before checking if an item is stale. - * * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. - * * generateOnReadError - if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. - * * generateIgnoreWriteError - if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. - * * dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. - * * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of concurrent generateFunc calls beyond staleTimeout). - * * cache - the cache name configured in server.cache. Defaults to the default cache. - * * segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. - * * shared - if true, allows multiple cache provisions to share the same segment. Default to false. - * @return Catbox Policy. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) - */ - (options: ServerOptionsCache): catbox.Policy; - - /** - * Provisions a server cache as described in server.cache where: - * @param options - same as the server cache configuration options. - * @return Return value: none. - * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions) - */ - provision(options: ServerOptionsCache): Promise; - -} diff --git a/types/hapi/definitions/server/server-events.d.ts b/types/hapi/definitions/server/server-events.d.ts deleted file mode 100644 index b1e0c05405..0000000000 --- a/types/hapi/definitions/server/server-events.d.ts +++ /dev/null @@ -1,146 +0,0 @@ -import * as Podium from "podium"; - -/** - * an event name string. - * an event options object. - * a podium emitter object. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) - */ -export type ServerEventsApplication = string | ServerEventsApplicationObject | Podium; - -/** - * Object that it will be used in Event - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) - */ -export interface ServerEventsApplicationObject { - /** the event name string (required). */ - name: string; - /** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */ - channels?: string | string[]; - /** if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). */ - clone?: boolean; - /** if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). */ - spread?: boolean; - /** if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false. */ - tags?: boolean; - /** if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first configuration is used. Defaults to false (a duplicate registration will throw an error). */ - shared?: boolean; -} - -/** - * A criteria object with the following optional keys (unless noted otherwise): - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) - */ -export interface ServerEventCriteria { - /** (required) the event name string. */ - name: string; - /** a string or array of strings specifying the event channels to subscribe to. If the event registration specified a list of allowed channels, the channels array must match the allowed channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter. */ - channels?: string | string[]; - /** if true, the data object passed to server.event.emit() is cloned before it is passed to the listener method. Defaults to the event registration option (which defaults to false). */ - clone?: boolean; - /** a positive integer indicating the number of times the listener can be called after which the subscription is automatically removed. A count of 1 is the same as calling server.events.once(). Defaults to no limit. */ - count?: number; - /** - * filter - the event tags (if present) to subscribe to which can be one of: - * * a tag string. - * * an array of tag strings. - * * an object with the following: - * * * tags - a tag string or array of tag strings. - * * * all - if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag). - */ - filter?: string | string[] | {tags: string | string[], all?: boolean}; - /** if true, and the data object passed to server.event.emit() is an array, the listener method is called with each array element passed as a separate argument. This should only be used when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false). */ - spread?: boolean; - /** if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. Defaults to the event registration option (which defaults to false). */ - tags?: boolean; -} - -/** - * Access: podium public interface. - * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. - * Use the following methods to interact with server.events: - * [server.event(events)](https://github.com/hapijs/hapi/blob/master/API.md#server.event()) - register application events. - * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. - * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. - * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to - * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) - */ -export interface ServerEvents extends Podium { - - /** - * Emits a custom application event to all the subscribed listeners where: - * @param criteria - the event update criteria which must be one of: - * * the event name string. - * * an object with the following optional keys (unless noted otherwise): - * * * name - the event name string (required). - * * * channel - the channel name string. - * * * tags - a tag string or array of tag strings. - * @param data - the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. - * @return Return value: none. - * Note that events must be registered before they can be emitted or subscribed to by calling server.event(events). This is done to detect event name misspelling and invalid event activities. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsemitcriteria-data) - */ - emit(criteria: string, data: any | Function): Promise; - emit(criteria: {name: string, channel?: string, tags?: string | string[]}, data: any): Promise; - - /** - * Subscribe to an event where: - * @param criteria - the subscription criteria which must be one of: - * * event name string which can be any of the built-in server events - * * a custom application event registered with server.event(). - * * a criteria object - * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) - * See ['log' event](https://github.com/hapijs/hapi/blob/master/API.md#-log-event) - * See ['request' event](https://github.com/hapijs/hapi/blob/master/API.md#-request-event) - * See ['response' event](https://github.com/hapijs/hapi/blob/master/API.md#-response-event) - * See ['route' event](https://github.com/hapijs/hapi/blob/master/API.md#-route-event) - * See ['start' event](https://github.com/hapijs/hapi/blob/master/API.md#-start-event) - * See ['stop' event](https://github.com/hapijs/hapi/blob/master/API.md#-stop-event) - */ - on(criteria: string | ServerEventsApplicationObject | ServerEventCriteria, listener: Function): void; - - /** - * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. - * @param criteria - the subscription criteria which must be one of: - * * event name string which can be any of the built-in server events - * * a custom application event registered with server.event(). - * * a criteria object - * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) - */ - once(criteria: string | ServerEventsApplicationObject | ServerEventCriteria, listener: Function): void; - - /** - * Same as calling server.events.on() with the count option set to 1. - * @param criteria - the subscription criteria which must be one of: - * * event name string which can be any of the built-in server events - * * a custom application event registered with server.event(). - * * a criteria object - * @return Return value: a promise that resolves when the event is emitted. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) - */ - once(criteria: string | ServerEventsApplicationObject | ServerEventCriteria): Promise; - - /** - * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener) - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) - */ - removeListener(name: string, listener: Podium.Listener): Podium; - - /** - * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovealllistenersname) - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) - */ - removeAllListeners(name: string): Podium; - - /** - * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumhaslistenersname) - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) - */ - hasListeners(name: string): boolean; - -} diff --git a/types/hapi/definitions/server/server-ext.d.ts b/types/hapi/definitions/server/server-ext.d.ts deleted file mode 100644 index 8bd29cbb18..0000000000 --- a/types/hapi/definitions/server/server-ext.d.ts +++ /dev/null @@ -1,146 +0,0 @@ -import {Lifecycle, Server} from "hapi"; - -/** - * The extension point event name. The available extension points include the request extension points as well as the following server extension points: - * 'onPreStart' - called before the connection listeners are started. - * 'onPostStart' - called after the connection listeners are started. - * 'onPreStop' - called before the connection listeners are stopped. - * 'onPostStop' - called after the connection listeners are stopped. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) - */ -export type ServerExtType = 'onRequest' | 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop'| 'onPreResponse'; - -/** - * The extension point event name for Request - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) - */ -export type ServerExtRequestType = 'onRequest'; - -/** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) - * Registers an extension function in one of the request lifecycle extension points where: - * @param events - an object or array of objects with the following: - * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: - * * * 'onPreStart' - called before the connection listeners are started. - * * * 'onPostStart' - called after the connection listeners are started. - * * * 'onPreStop' - called before the connection listeners are stopped. - * * * 'onPostStop' - called after the connection listeners are stopped. - * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: - * * * server extension points: async function(server) where: - * * * * server - the server object. - * * * * this - the object provided via options.bind or the current active context set with server.bind(). - * * * request extension points: a lifecycle method. - * * options - (optional) an object with the following: - * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. - * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. - * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. - * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. - * @return void - */ -export interface ServerExtEventsObject { - /** - * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: - * * 'onPreStart' - called before the connection listeners are started. - * * 'onPostStart' - called after the connection listeners are started. - * * 'onPreStop' - called before the connection listeners are stopped. - */ - type: ServerExtType; - /** - * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: - * * server extension points: async function(server) where: - * * * server - the server object. - * * * this - the object provided via options.bind or the current active context set with server.bind(). - * * request extension points: a lifecycle method. - */ - method: ServerExtPointFunction | ServerExtPointFunction[] | Function; - /** - * options - (optional) an object with the following: - * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. - * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. - * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. - * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. - */ - options?: ServerExtOptions; -} - -/** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) - * Registers an extension function in one of the request lifecycle extension points where: - * @param events - an object or array of objects with the following: - * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: - * * * 'onPreStart' - called before the connection listeners are started. - * * * 'onPostStart' - called after the connection listeners are started. - * * * 'onPreStop' - called before the connection listeners are stopped. - * * * 'onPostStop' - called after the connection listeners are stopped. - * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: - * * * server extension points: async function(server) where: - * * * * server - the server object. - * * * * this - the object provided via options.bind or the current active context set with server.bind(). - * * * request extension points: a lifecycle method. - * * options - (optional) an object with the following: - * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. - * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. - * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. - * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. - * @return void - */ -export interface ServerExtEventsRequestObject { - /** - * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: - * * 'onPreStart' - called before the connection listeners are started. - * * 'onPostStart' - called after the connection listeners are started. - * * 'onPreStop' - called before the connection listeners are stopped. - * * 'onPostStop' - called after the connection listeners are stopped. - */ - type: ServerExtRequestType; - /** - * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: - * * server extension points: async function(server) where: - * * * server - the server object. - * * * this - the object provided via options.bind or the current active context set with server.bind(). - * * request extension points: a lifecycle method. - */ - method: Lifecycle.Method | Lifecycle.Method[]; - /** - * (optional) an object with the following: - * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. - * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. - * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. - * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. - */ - options?: ServerExtOptions; -} - -export interface ServerExtPointFunction { - (server: Server): void; -} - -/** - * An object with the following: - * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. - * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. - * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. - * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) - */ -export interface ServerExtOptions { - /** - * a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. - */ - before: string | string[]; - /** - * a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. - */ - after: string | string[]; - /** - * a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. - */ - bind: object; - /** - * if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. - */ - sandbox?: 'server' | 'plugin'; -} - diff --git a/types/hapi/definitions/server/server-info.d.ts b/types/hapi/definitions/server/server-info.d.ts deleted file mode 100644 index 399543e08e..0000000000 --- a/types/hapi/definitions/server/server-info.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) - * An object containing information about the server where: - */ -export interface ServerInfo { - - /** - * a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). - */ - id: string; - - /** - * server creation timestamp. - */ - created: number; - - /** - * server start timestamp (0 when stopped). - */ - started: number; - - /** - * the connection [port](https://github.com/hapijs/hapi/blob/master/API.md#server.options.port) based on the following rules: - * * before the server has been started: the configured port value. - * * after the server has been started: the actual port assigned when no port is configured or was set to 0. - */ - port: number | string; - - /** - * The [host](https://github.com/hapijs/hapi/blob/master/API.md#server.options.host) configuration value. - */ - host: string; - - /** - * the active IP address the connection was bound to after starting. Set to undefined until the server has been - * started or when using a non TCP port (e.g. UNIX domain socket). - */ - address: undefined | string; - - /** - * the protocol used: - * * 'http' - HTTP. - * * 'https' - HTTPS. - * * 'socket' - UNIX domain socket or Windows named pipe. - */ - protocol: 'http' | 'https' | 'socket'; - - /** - * a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains - * the uri value if set, otherwise constructed from the available settings. If no port is configured or is set - * to 0, the uri will not include a port component until the server is started. - */ - uri: string; - -} diff --git a/types/hapi/definitions/server/server-inject.d.ts b/types/hapi/definitions/server/server-inject.d.ts deleted file mode 100644 index 99789febfe..0000000000 --- a/types/hapi/definitions/server/server-inject.d.ts +++ /dev/null @@ -1,71 +0,0 @@ -import {AuthCredentials, PluginsStates, Request} from "hapi"; -import * as Shot from "shot"; - -/** - * An object with: - * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. - * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. - * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. - * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided. - * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials. - * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. - * * app - (optional) sets the initial value of request.app, defaults to {}. - * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. - * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. - * * remoteAddress - (optional) sets the remote address for the incoming connection. - * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: - * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. - * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. - * * end - if false, does not end the stream. Defaults to true. - * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. - * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested separately. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) - * For context [Shot module](https://github.com/hapijs/shot) - */ -export interface ServerInjectOptions extends Shot.RequestOptions { - /** - * an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials. - */ - credentials?: AuthCredentials; - /** - * (an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. - */ - artifacts?: object; - /** - * sets the initial value of request.app, defaults to {}. - */ - app?: any; - /** - * sets the initial value of request.plugins, defaults to {}. - */ - plugins?: PluginsStates; - /** - * allows access to routes with config.isInternal set to true. Defaults to false. - */ - allowInternals?: boolean; -} - -/** - * A response object with the following properties: - * * statusCode - the HTTP status code. - * * headers - an object containing the headers set. - * * payload - the response payload string. - * * rawPayload - the raw response payload buffer. - * * raw - an object with the injection request and response objects: - * * req - the simulated node request object. - * * res - the simulated node response object. - * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). - * * request - the request object. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) - * For context [Shot module](https://github.com/hapijs/shot) - */ -export interface ServerInjectResponse extends Shot.ResponseObject { - /** - * the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). - */ - result: object | undefined; - /** - * the request object. - */ - request: Request; -} diff --git a/types/hapi/definitions/server/server-method.d.ts b/types/hapi/definitions/server/server-method.d.ts deleted file mode 100644 index 920560086a..0000000000 --- a/types/hapi/definitions/server/server-method.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -import * as catbox from "catbox"; - -/** - * The method function with a signature async function(...args, [flags]) where: - * * ...args - the method function arguments (can be any number of arguments or none). - * * flags - when caching is enabled, an object used to set optional method result flags: - * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. - * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) - */ -export type ServerMethod = (...args: any[]) => Promise; - -/** - * The same cache configuration used in server.cache(). - * The generateTimeout option is required. - * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) - * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) - */ -export interface ServerMethodCache extends catbox.PolicyOptions { - generateTimeout: number | false; -} - -/** - * Configuration object: - * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow function. - * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. - * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). - * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) - */ -export interface ServerMethodOptions { - /** - * a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow function. - */ - bind?: object; - /** - * the same cache configuration used in server.cache(). The generateTimeout option is required. - */ - cache?: ServerMethodCache; - /** - * a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). - */ - generateKey?: Function; -} - -/** - * An object or an array of objects where each one contains: - * * name - the method name. - * * method - the method function. - * * options - (optional) settings. - * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) - */ -export interface ServerMethodConfigurationObject { - /** - * the method name. - */ - name: string; - /** - * the method function. - */ - method: ServerMethod; - /** - * (optional) settings. - */ - options?: ServerMethodOptions; -} diff --git a/types/hapi/definitions/server/server-options-cache.d.ts b/types/hapi/definitions/server/server-options-cache.d.ts deleted file mode 100644 index 1e75ebe857..0000000000 --- a/types/hapi/definitions/server/server-options-cache.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as Catbox from "catbox"; - -/** - * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, - * MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-cache) - */ -export interface ServerOptionsCache extends Catbox.PolicyOptions { - - /** a class, a prototype function, or a catbox engine object. */ - engine?: Catbox.EnginePrototypeOrObject; - - /** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisioned as well. */ - name?: string; - - /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ - shared?: boolean; - - /** (optional) string used to isolate cached data. Defaults to 'hapi-cache'. */ - partition?: string; - - /** other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). */ - [s: string]: any; - -} diff --git a/types/hapi/definitions/server/server-options.d.ts b/types/hapi/definitions/server/server-options.d.ts deleted file mode 100644 index 2f74c17bb4..0000000000 --- a/types/hapi/definitions/server/server-options.d.ts +++ /dev/null @@ -1,186 +0,0 @@ -import * as http from "http"; -import * as https from "https"; -import * as catbox from "catbox"; -import {MimosOptions} from "mimos"; -import {PluginSpecificConfiguration, RouteOptions, ServerOptionsCache} from "hapi"; - -export interface ServerOptionsCompression { - minBytes: number; -} - -/** - * The server options control the behavior of the server object. Note that the options object is deeply cloned - * (with the exception of listener which is shallowly copied) and should not contain any values that are unsafe to perform deep copy on. - * All options are optionals. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-server-options) - */ -export interface ServerOptions { - - /** - * Default value: '0.0.0.0' (all available network interfaces). - * Sets the hostname or IP address the server will listen on. If not configured, defaults to host if present, otherwise to all available network interfaces. Set to '127.0.0.1' or 'localhost' to restrict the server to only those coming from the same host. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsaddress) - */ - address?: string; - - /** - * Default value: {}. - * Provides application-specific configuration which can later be accessed via server.settings.app. The framework does not interact with this object. It is simply a reference made available anywhere a server reference is provided. - * Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsapp) - */ - app?: any; - - /** - * Default value: true. - * Used to disable the automatic initialization of the listener. When false, indicates that the listener will be started manually outside the framework. - * Cannot be set to true along with a port value. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsautolisten) - */ - autoListen?: boolean; - - /** - * Default value: { engine: require('catbox-memory' }. - * Sets up server-side caching providers. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. - * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. - * The server cache configuration only defines the storage container itself. The configuration can be assigned one or more (array): - * * a class or prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). A new catbox client will be created internally using this function. - * * a configuration object with the following: - * * * engine - a class, a prototype function, or a catbox engine object. - * * * name - an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisioned as well. - * * * shared - if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. - * * * partition - (optional) string used to isolate cached data. Defaults to 'hapi-cache'. - * * * other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionscache) - */ - cache?: catbox.EnginePrototype | ServerOptionsCache | ServerOptionsCache[]; - - /** - * Default value: { minBytes: 1024 }. - * Defines server handling of content encoding requests. If false, response content encoding is disabled and no compression is performed by the server. - */ - compression?: boolean | ServerOptionsCompression; - - /** - * Default value: { request: ['implementation'] }. - * Determines which logged events are sent to the console. This should only be used for development and does not affect which events are actually logged internally and recorded. Set to false to disable all console logging, or to an object with: - * * log - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. Defaults to no output. - * * request - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. To display all request logs, set it to '*'. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. - * For example, to display all errors, set the log or request to ['error']. To turn off all output set the log or request to false. To display all server logs, set the log or request to '*'. To disable all debug information, set debug to false. - */ - debug?: false | { - log?: string[] | false; - request?: string[] | false; - }; - - /** - * Default value: the operating system hostname and if not available, to 'localhost'. - * The public hostname or IP address. Used to set server.info.host and server.info.uri and as address is none provided. - */ - host?: string; - - /** - * Default value: none. - * An optional node HTTP (or HTTPS) http.Server object (or an object with a compatible interface). - * If the listener needs to be manually started, set autoListen to false. - * If the listener uses TLS, set tls to true. - */ - listener?: http.Server; - - /** - * Default value: { sampleInterval: 0 }. - * Server excessive load handling limits where: - * * sampleInterval - the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). - * * maxHeapUsedBytes - maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). - * * maxRssBytes - maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). - * * maxEventLoopDelay - maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). - */ - load?: { - /** the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). */ - sampleInterval?: number; - /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxHeapUsedBytes?: number; - /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).*/ - maxRssBytes?: number; - /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).*/ - maxEventLoopDelay?: number; - }; - - /** - * Default value: none. - * Options passed to the mimos module when generating the mime database used by the server (and accessed via server.mime): - * * override - an object hash that is merged into the built in mime information specified here. Each key value pair represents a single mime object. Each override value must contain: - * * key - the lower-cased mime-type string (e.g. 'application/javascript'). - * * value - an object following the specifications outlined here. Additional values include: - * * * type - specify the type value of result objects, defaults to key. - * * * predicate - method with signature function(mime) when this mime type is found in the database, this function will execute to allows customizations. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsmime) - */ - mime?: MimosOptions; - - /** - * Default value: {}. - * Plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. - */ - plugins?: PluginSpecificConfiguration; - - /** - * Default value: 0 (an ephemeral port). - * The TCP port the server will listen to. Defaults the next available port when the server is started (and assigned to server.info.port). - * If port is a string containing a '/' character, it is used as a UNIX domain socket path. If it starts with '\.\pipe', it is used as a Windows named pipe. - */ - port?: number | string; - - /** - * Default value: { isCaseSensitive: true, stripTrailingSlash: false }. - * Controls how incoming request URIs are matched against the routing table: - * * isCaseSensitive - determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. - * * stripTrailingSlash - removes trailing slashes on incoming paths. Defaults to false. - */ - router?: { - isCaseSensitive?: boolean; - stripTrailingSlash?: boolean; - }; - - /** - * Default value: none. - * A route options object used as the default configuration for every route. - */ - routes?: RouteOptions; - - /** - Default value: - { - strictHeader: true, - ignoreErrors: false, - isSecure: true, - isHttpOnly: true, - isSameSite: 'Strict', - encoding: 'none' - } - Sets the default configuration for every state (cookie) set explicitly via server.state() or implicitly (without definition) using the state configuration object. - */ - // TODO I am not sure if I need to use all the server.state() definition (like the default value) OR only the options below. The v16 use "any" here. - // state?: ServerStateCookieOptions; - state?: { - strictHeader?: boolean, - ignoreErrors?: boolean, - isSecure?: boolean, - isHttpOnly?: boolean, - isSameSite?: false | 'Strict' | 'Lax', - encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron' - }; - - /** - * Default value: none. - * Used to create an HTTPS connection. The tls object is passed unchanged to the node HTTPS server as described in the node HTTPS documentation. - */ - tls?: true | https.RequestOptions; - - /** - * Default value: constructed from runtime server information. - * The full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the server server.info.uri, otherwise constructed from the server settings. - */ - uri?: string; - -} diff --git a/types/hapi/definitions/server/server-realm.d.ts b/types/hapi/definitions/server/server-realm.d.ts deleted file mode 100644 index eb921a1699..0000000000 --- a/types/hapi/definitions/server/server-realm.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -import {PluginsStates} from "hapi"; - -/** - * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When registering a plugin or an authentication scheme, a server object reference is provided with a new server.realm container specific to that registration. It allows each plugin to maintain its own settings without leaking and affecting other plugins. - * For example, a plugin can set a default file path for local resources without breaking other plugins' configured paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). - * - * https://github.com/hapijs/hapi/blob/master/API.md#server.realm - */ -export interface ServerRealm { - /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: */ - modifiers: { - /** routes preferences: */ - route: { - /** the route path prefix used by any calls to server.route() from the server. Note that if a prefix is used and the route path is set to '/', the resulting path will not include the trailing slash. */ - prefix: string; - /** the route virtual host settings used by any calls to server.route() from the server. */ - vhost: string; - } - }; - /** the realm of the parent server object, or null for the root server. */ - parent: ServerRealm | null; - /** the active plugin name (empty string if at the server root). */ - plugin: string; - /** the plugin options object passed at registration. */ - pluginOptions: object; - /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ - plugins: PluginsStates; - /** settings overrides */ - settings: { - files: { - relativeTo: string; - }; - bind: object; - }; -} diff --git a/types/hapi/definitions/server/server-register.d.ts b/types/hapi/definitions/server/server-register.d.ts deleted file mode 100644 index 313a3c164e..0000000000 --- a/types/hapi/definitions/server/server-register.d.ts +++ /dev/null @@ -1,62 +0,0 @@ -import {Plugin} from "hapi"; - -/** - * Registration options (different from the options passed to the registration function): - * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second time a plugin is registered on the server. - * * routes - modifiers applied to each route added by the plugin: - * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. - * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. - * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) - */ -export interface ServerRegisterOptions { - /** - * if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second time a plugin is registered on the server. - */ - once?: boolean; - /** - * modifiers applied to each route added by the plugin: - */ - routes?: { - /** - * string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. - */ - prefix: string; - /** - * virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. - */ - vhost: string | string[]; - }; -} - -/** - * An object with the following: - * * plugin - a plugin object. - * * options - (optional) options passed to the plugin during registration. - * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second time a plugin is registered on the server. - * * routes - modifiers applied to each route added by the plugin: - * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. - * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. - * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) - * - * The type parameter T is the type of the plugin configuration options. - */ -export interface ServerRegisterPluginObject extends ServerRegisterOptions { - /** - * a plugin object. - */ - plugin: Plugin; - /** - * options passed to the plugin during registration. - */ - options?: T; -} - -export interface ServerRegisterPluginObjectArray extends Array | ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject | undefined> { - 0: ServerRegisterPluginObject; - 1?: ServerRegisterPluginObject; - 2?: ServerRegisterPluginObject; - 3?: ServerRegisterPluginObject; - 4?: ServerRegisterPluginObject; - 5?: ServerRegisterPluginObject; - 6?: ServerRegisterPluginObject; -} diff --git a/types/hapi/definitions/server/server-route.d.ts b/types/hapi/definitions/server/server-route.d.ts deleted file mode 100644 index 7c9087bddd..0000000000 --- a/types/hapi/definitions/server/server-route.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -import {Lifecycle, RouteOptions, Server, Util} from "hapi"; - -export interface ServerRouteConfig { -} - -/** - * A route configuration object or an array of configuration objects where each object contains: - * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. - * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. - * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. - * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. - * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. - * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) - */ -export interface ServerRoute { - - /** - * (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters) - */ - path: string; - - /** - * (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. - */ - method: Util.HTTP_METHODS_PARTIAL | Util.HTTP_METHODS_PARTIAL[] | string | string[]; - - /** - * (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. - */ - vhost?: string | string[]; - - /** - * (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. - */ - handler?: Lifecycle.Method | object; - - /** - * additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. - */ - options?: RouteOptions | ((server: Server) => RouteOptions); - - /** - * route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. - */ - rules?: object; - - /** - * Missing documentation. Exist only in examples and test files. - */ - config?: ServerRouteConfig; - -} diff --git a/types/hapi/definitions/server/server-state-options.d.ts b/types/hapi/definitions/server/server-state-options.d.ts deleted file mode 100644 index f95eb4b794..0000000000 --- a/types/hapi/definitions/server/server-state-options.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { Request } from "hapi"; -import { SealOptions, SealOptionsSub } from "iron"; - -/** - * Optional cookie settings - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) - */ -export interface ServerStateCookieOptions { - /** time-to-live in milliseconds. Defaults to null (session time-life - cookies are deleted when the browser is closed). */ - ttl?: number | null; - /** sets the 'Secure' flag. Defaults to true. */ - isSecure?: boolean; - /** sets the 'HttpOnly' flag. Defaults to true. */ - isHttpOnly?: boolean; - /** - * sets the 'SameSite' flag. The value must be one of: - * * false - no flag. - * * 'Strict' - sets the value to 'Strict' (this is the default value). - * * 'Lax' - sets the value to 'Lax'. - */ - isSameSite?: false | 'Strict' | 'Lax'; - /** the path scope. Defaults to null (no path). */ - path?: string | null; - /** the domain scope. Defaults to null (no domain). */ - domain?: string | null; - /** - * if present and the cookie was not received from the client or explicitly set by the route handler, the - * cookie is automatically added to the response with the provided value. The value can be - * a function with signature async function(request) where: - */ - autoValue?(request: Request): void; - /** - * encoding performs on the provided value before serialization. Options are: - * * 'none' - no encoding. When used, the cookie value must be a string. This is the default value. - * * 'base64' - string value is encoded using Base64. - * * 'base64json' - object value is JSON-stringified then encoded using Base64. - * * 'form' - object value is encoded using the x-www-form-urlencoded method. - * * 'iron' - Encrypts and sign the value using iron. - */ - encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron'; - /** - * an object used to calculate an HMAC for cookie integrity validation. This does not provide privacy, only a mean - * to verify that the cookie value was generated by the server. Redundant when 'iron' encoding is used. Options are: - * * integrity - algorithm options. Defaults to require('iron').defaults.integrity. - * * password - password used for HMAC key generation (must be at least 32 characters long). - */ - sign?: { - integrity?: SealOptionsSub; - password: string; - }; - /** password used for 'iron' encoding (must be at least 32 characters long). */ - password?: string; - /** options for 'iron' encoding. Defaults to require('iron').defaults. */ - iron?: SealOptions; - /** if true, errors are ignored and treated as missing cookies. */ - ignoreErrors?: boolean; - /** if true, automatically instruct the client to remove invalid cookies. Defaults to false. */ - clearInvalid?: boolean; - /** if false, allows any cookie value including values in violation of RFC 6265. Defaults to true. */ - strictHeader?: boolean; - /** used by proxy plugins (e.g. h2o2). */ - passThrough?: any; -} diff --git a/types/hapi/definitions/server/server-state.d.ts b/types/hapi/definitions/server/server-state.d.ts deleted file mode 100644 index 119e06073c..0000000000 --- a/types/hapi/definitions/server/server-state.d.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { ServerStateCookieOptions, Util } from "hapi"; - -/** - * A single object or an array of object where each contains: - * * name - the cookie name. - * * value - the cookie value. - * * options - cookie configuration to override the server settings. - */ -export interface ServerStateFormat { - name: string; - value: string; - options: ServerStateCookieOptions; -} - -/** - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsstate) - */ -export interface ServerState { - /** - * The server cookies manager. - * Access: read only and statehood public interface. - */ - readonly states: object; - - /** - * The server cookies manager settings. The settings are based on the values configured in [server.options.state](https://github.com/hapijs/hapi/blob/master/API.md#server.options.state). - */ - readonly settings: ServerStateCookieOptions; - - /** - * An object containing the configuration of each cookie added via [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()) where each key is the - * cookie name and value is the configuration object. - */ - readonly cookies: object; - - /** - * An array containing the names of all configued cookies. - */ - readonly names: string[]; - - /** - * Same as calling [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()). - */ - add(name: string, options?: ServerStateCookieOptions): void; - - /** - * Formats an HTTP 'Set-Cookie' header based on the server.options.state where: - * @param cookies - a single object or an array of object where each contains: - * * name - the cookie name. - * * value - the cookie value. - * * options - cookie configuration to override the server settings. - * @return Return value: a header string. - * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie formating (e.g. when headers are set manually). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesformatcookies) - */ - format(cookies: ServerStateFormat | ServerStateFormat[]): string; - - /** - * Parses an HTTP 'Cookies' header based on the server.options.state where: - * @param header - the HTTP header. - * @return Return value: an object where each key is a cookie name and value is the parsed cookie. - * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie parsing (e.g. when server parsing is disabled). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesparseheader) - */ - parse(header: string): Util.Dictionary; -} diff --git a/types/hapi/definitions/server/server.d.ts b/types/hapi/definitions/server/server.d.ts deleted file mode 100644 index 0133a35775..0000000000 --- a/types/hapi/definitions/server/server.d.ts +++ /dev/null @@ -1,563 +0,0 @@ -import * as http from "http"; -import * as zlib from "zlib"; -import * as Podium from "podium"; -import { - ApplicationState, - Lifecycle, - PayloadCompressionDecoderSettings, - Plugin, - PluginsListRegistered, - Request, - RequestRoute, - ResponseToolkit, - RouteCompressionEncoderSettings, - ServerAuth, - ServerCache, - ServerEvents, - ServerEventsApplication, - ServerExtEventsObject, - ServerExtEventsRequestObject, - ServerExtOptions, - ServerExtPointFunction, - ServerExtType, - ServerInfo, - ServerInjectOptions, - ServerInjectResponse, - ServerMethod, - ServerMethodConfigurationObject, - ServerMethodOptions, - ServerOptions, - ServerRealm, - ServerRegisterOptions, - ServerRegisterPluginObject, - ServerRegisterPluginObjectArray, - ServerRoute, - ServerState, - ServerStateCookieOptions, - Util, -} from "hapi"; - -/** - * The server object is the main application container. The server manages all incoming requests along with all - * the facilities provided by the framework. Each server supports a single connection (e.g. listen to port 80). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#server) - */ -export class Server extends Podium { - - /** - * Creates a new server object - * @constructor - */ - constructor(); - - /** - * Creates a new server object where: - * @constructor - * @param options server configuration object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptions) - */ - constructor(options: ServerOptions); - - /** - * Provides a safe place to store server-specific run-time application data without potential conflicts with - * the framework internals. The data can be accessed whenever the server is accessible. - * Initialized with an empty object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverapp) - */ - app?: ApplicationState; - - /** - * Server Auth: properties and methods - */ - auth: ServerAuth; - - /** - * Provides access to the decorations already applied to various framework interfaces. The object must not be - * modified directly, but only through server.decorate. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecorations) - */ - readonly decorations: { - /** - * decorations on the request object. - */ - request: string[], - /** - * decorations on the response toolkit. - */ - toolkit: string[], - /** - * decorations on the server object. - */ - server: string[] - }; - - /** - * Register custom application events where: - * @param events must be one of: - * * an event name string. - * * an event options object with the following optional keys (unless noted otherwise): - * * * name - the event name string (required). - * * * channels - a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). - * * * clone - if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). - * * * spread - if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). - * * * tags - if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false. - * * * shared - if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first configuration is used. Defaults to false (a duplicate registration will throw an error). - * * a podium emitter object. - * * an array containing any of the above. - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) - */ - event(events: ServerEventsApplication | ServerEventsApplication[]): void; - - /** - * Access: podium public interface. - * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. - * Use the following methods to interact with server.events: - * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. - * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. - * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to - * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) - */ - events: ServerEvents; - - /** - * An object containing information about the server where: - * * id - a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). - * * created - server creation timestamp. - * * started - server start timestamp (0 when stopped). - * * port - the connection port based on the following rules: - * * host - The host configuration value. - * * address - the active IP address the connection was bound to after starting. Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket). - * * protocol - the protocol used: - * * 'http' - HTTP. - * * 'https' - HTTPS. - * * 'socket' - UNIX domain socket or Windows named pipe. - * * uri - a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri value if set, otherwise constructed from the available settings. If no port is configured or is set to 0, the uri will not include a port component until the server is started. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) - */ - readonly info: ServerInfo; - - /** - * Access: read only and listener public interface. - * The node HTTP server object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener) - */ - listener: http.Server; - - /** - * An object containing the process load metrics (when load.sampleInterval is enabled): - * * eventLoopDelay - event loop delay milliseconds. - * * heapUsed - V8 heap usage. - * * rss - RSS memory usage. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverload) - */ - readonly load: { - /** - * event loop delay milliseconds. - */ - eventLoopDelay: number; - /** - * V8 heap usage. - */ - heapUsed: number; - /** - * RSS memory usage. - */ - rss: number; - }; - - /** - * Server methods are functions registered with the server and used throughout the application as a common utility. - * Their advantage is in the ability to configure them to use the built-in cache and share across multiple request - * handlers without having to create a common module. - * sever.methods is an object which provides access to the methods registered via server.method() where each - * server method name is an object property. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods - */ - readonly methods: Util.Dictionary; - - /** - * Provides access to the server MIME database used for setting content-type information. The object must not be - * modified directly but only through the [mime](https://github.com/hapijs/hapi/blob/master/API.md#server.options.mime) server setting. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermime) - */ - mime: any; - - /** - * An object containing the values exposed by each registered plugin where each key is a plugin name and the values - * are the exposed properties by each plugin using server.expose(). Plugins may set the value of - * the server.plugins[name] object directly or via the server.expose() method. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins) - */ - plugins: any; - - /** - * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When - * registering a plugin or an authentication scheme, a server object reference is provided with a new server.realm - * container specific to that registration. It allows each plugin to maintain its own settings without leaking - * and affecting other plugins. - * For example, a plugin can set a default file path for local resources without breaking other plugins' configured - * paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by - * routes and extensions added at the same level (server root or plugin). - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrealm) - */ - readonly realm: ServerRealm; - - /** - * An object of the currently registered plugins where each key is a registered plugin name and the value is - * an object containing: - * * version - the plugin version. - * * name - the plugin name. - * * options - (optional) options passed to the plugin during registration. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) - */ - readonly registrations: PluginsListRegistered; - - /** - * The server configuration object after defaults applied. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serversettings) - */ - readonly settings: ServerOptions; - - /** - * The server cookies manager. - * Access: read only and statehood public interface. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstates) - */ - readonly states: ServerState; - - /** - * A string indicating the listener type where: - * * 'socket' - UNIX domain socket or Windows named pipe. - * * 'tcp' - an HTTP listener. - */ - readonly type: 'socket' | 'tcp'; - - /** - * The hapi module version number. - */ - readonly version: string; - - /** - * Sets a global context used as the default bind object when adding a route or an extension where: - * @param context - the object used to bind this in lifecycle methods such as the route handler and extension methods. The context is also made available as h.context. - * @return Return value: none. - * When setting a context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. Ignored if the method being bound is an arrow function. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext) - */ - bind(context: object): void; - - /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) - */ - cache: ServerCache; - - /** - * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where: - * @param encoding - the decoder name string. - * @param decoder - a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the return value is an object compatible with the output of node's zlib.createGunzip(). - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder) - */ - decoder(encoding: string, decoder: ((options: PayloadCompressionDecoderSettings) => zlib.Gunzip)): void; - - /** - * Extends various framework interfaces with custom methods where: - * @param type - the interface being decorated. Supported types: - * 'handler' - adds a new handler type to be used in routes handlers. - * 'request' - adds methods to the Request object. - * 'server' - adds methods to the Server object. - * 'toolkit' - adds methods to the response toolkit. - * @param property - the object decoration key name. - * @param method - the extension function or other value. - * @param options - (optional) supports the following optional settings: - * apply - when the type is 'request', if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration. - * extend - if true, overrides an existing decoration. The method must be a function with the signature function(existing) where: - * existing - is the previously set decoration method value. - * must return the new decoration function or value. - * cannot be used to extend handler decorations. - * @return void; - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options) - */ - decorate(type: 'request', property: string, method: ((request: Request) => Function), options?: {apply: true; extend: false} ): void; - decorate(type: 'handler' | 'request' | 'server' | 'toolkit', property: string, method: Function, options?: {apply: boolean; extend: boolean} ): void; - - /** - * Used within a plugin to declare a required dependency on other plugins where: - * @param dependencies - a single string or an array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is initialized or started. - * @param after - (optional) a function that is called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is initialized or started. The function signature is async function(server) where: - * server - the server the dependency() method was called on. - * @return Return value: none. - * The after method is identical to setting a server extension point on 'onPreStart'. - * If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). - * The method does not provide version dependency which should be implemented using npm peer dependencies. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) - */ - dependency(dependencies: string | string[], after?: ((server: Server) => void)): void; - - /** - * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where: - * @param encoding - the encoder name string. - * @param encoder - a function using the signature function(options) where options are the encoding specific options configured in the route compression option, and the return value is an object compatible with the output of node's zlib.createGzip(). - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) - */ - encoder(encoding: string, encoder: ((options: RouteCompressionEncoderSettings) => zlib.Gzip)): void; - - /** - * Used within a plugin to expose a property via server.plugins[name] where: - * @param key - the key assigned (server.plugins[name][key]). - * @param value - the value assigned. - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) - */ - expose(key: string, value: any): void; - - /** - * Merges an object into to the existing content of server.plugins[name] where: - * @param obj - the object merged into the exposed properties container. - * @return Return value: none. - * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method - * for exposing large objects that may be expensive to clone or singleton objects such as database client - * objects. Instead favor server.expose(key, value), which only copies a reference to value. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) - */ - expose(obj: object): void; - - /** - * Registers an extension function in one of the request lifecycle extension points where: - * @param events - an object or array of objects with the following: - * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: - * * * 'onPreStart' - called before the connection listeners are started. - * * * 'onPostStart' - called after the connection listeners are started. - * * * 'onPreStop' - called before the connection listeners are stopped. - * * * 'onPostStop' - called after the connection listeners are stopped. - * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: - * * * server extension points: async function(server) where: - * * * * server - the server object. - * * * * this - the object provided via options.bind or the current active context set with server.bind(). - * * * request extension points: a lifecycle method. - * * options - (optional) an object with the following: - * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. - * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. - * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. - * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. - * @return void - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) - */ - ext(events: ServerExtEventsObject | ServerExtEventsObject[]): void; - ext(events: ServerExtEventsRequestObject | ServerExtEventsRequestObject[]): void; - - /** - * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments. - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options) - */ - ext(event: ServerExtType, method: ServerExtPointFunction | Lifecycle.Method | Function, options?: ServerExtOptions): void; - - /** - * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port. - * @return Return value: none. - * Note that if the method fails and throws an error, the server is considered to be in an undefined state and - * should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and - * other event listeners will get confused by repeated attempts to start the server or make assumptions about the - * healthy state of the environment. It is recommended to abort the process when the server fails to start properly. - * If you must try to resume after an error, call server.stop() first to reset the server state. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinitialize) - */ - initialize(): Promise; - - /** - * Injects a request into the server simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead and limitations of the network stack. - * The method utilizes the shot module for performing injections, with some additional options and response properties: - * @param options - can be assigned a string with the requested URI, or an object with: - * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. - * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. - * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. - * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided. - * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials. - * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. - * * app - (optional) sets the initial value of request.app, defaults to {}. - * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. - * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. - * * remoteAddress - (optional) sets the remote address for the incoming connection. - * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: - * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. - * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. - * * end - if false, does not end the stream. Defaults to true. - * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. - * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested separately. - * @return Return value: a response object with the following properties: - * * statusCode - the HTTP status code. - * * headers - an object containing the headers set. - * * payload - the response payload string. - * * rawPayload - the raw response payload buffer. - * * raw - an object with the injection request and response objects: - * * req - the simulated node request object. - * * res - the simulated node response object. - * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). - * * request - the request object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) - */ - inject(options: string | ServerInjectOptions): Promise; - - /** - * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: - * @param tags - (required) a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. - * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. - * @param timestamp - (optional) an timestamp expressed in milliseconds. Defaults to Date.now() (now). - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlogtags-data-timestamp) - */ - log(tags: string | string[], data?: string | object | (() => any), timestamp?: number): void; - - /** - * Looks up a route configuration where: - * @param id - the route identifier. - * @return Return value: the route information if found, otherwise null. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid) - */ - lookup(id: string): RequestRoute | null; - - /** - * Looks up a route configuration where: - * @param method - the HTTP method (e.g. 'GET', 'POST'). - * @param path - the requested path (must begin with '/'). - * @param host - (optional) hostname (to match against routes with vhost). - * @return Return value: the route information if found, otherwise null. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host) - */ - match(method: Util.HTTP_METHODS, path: string, host?: string): RequestRoute | null; - - /** - * Registers a server method where: - * @param name - a unique method name used to invoke the method via server.methods[name]. - * @param method - the method function with a signature async function(...args, [flags]) where: - * * ...args - the method function arguments (can be any number of arguments or none). - * * flags - when caching is enabled, an object used to set optional method result flags: - * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. - * @param options - (optional) configuration object: - * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow function. - * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. - * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). - * @return Return value: none. - * Method names can be nested (e.g. utils.users.get) which will automatically create the full path under server.methods (e.g. accessed via server.methods.utils.users.get). - * When configured with caching enabled, server.methods[name].cache is assigned an object with the following properties and methods: - await drop(...args) - a function that can be used to clear the cache for a given key. - stats - an object with cache statistics, see catbox for stats documentation. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) - */ - method(name: string, method: ServerMethod, options?: ServerMethodOptions): void; - - /** - * Registers a server method function as described in server.method() using a configuration object where: - * @param methods - an object or an array of objects where each one contains: - * * name - the method name. - * * method - the method function. - * * options - (optional) settings. - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) - */ - method(methods: ServerMethodConfigurationObject | ServerMethodConfigurationObject[]): void; - - /** - * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: - * @param relativeTo - the path prefix added to any relative file path starting with '.'. - * @return Return value: none. - * Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the server default route configuration files.relativeTo settings is used. The path only applies to routes added after it has been set. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto) - */ - path(relativeTo: string): void; - - /** - * Registers a plugin where: - * @param plugins - one or an array of: - * * a plugin object. - * * an object with the following: - * * * plugin - a plugin object. - * * * options - (optional) options passed to the plugin during registration. - * * * once, routes - (optional) plugin-specific registration options as defined below. - * @param options - (optional) registration options (different from the options passed to the registration function): - * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second time a plugin is registered on the server. - * * routes - modifiers applied to each route added by the plugin: - * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. - * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) - */ - register(plugins: Plugin | Plugin[], options?: ServerRegisterOptions): Promise; - register(plugins: ServerRegisterPluginObject | ServerRegisterPluginObjectArray, options?: ServerRegisterOptions): Promise; - - /** - * Adds a route where: - * @param route - a route configuration object or an array of configuration objects where each object contains: - * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. - * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. - * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. - * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. - * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. - * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. - * @return Return value: none. - * Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) - */ - route(route: ServerRoute | ServerRoute[]): void; - - /** - * Defines a route rules processor for converting route rules object into route configuration where: - * @param processor - a function using the signature function(rules, info) where: - * * rules - - * * info - an object with the following properties: - * * * method - the route method. - * * * path - the route path. - * * * vhost - the route virtual host (if any defined). - * * returns a route config object. - * @param options - optional settings: - * * validate - rules object validation: - * * * schema - joi schema. - * * * options - optional joi validation options. Defaults to { allowUnknown: true }. - * Note that the root server and each plugin server instance can only register one rules processor. If a route is added after the rules are configured, it will not include the rules config. Routes added by plugins apply the rules to each of the parent realms' rules from the root to the route's realm. This means the processor defined by the plugin override the config generated by the root processor if they overlap. The route config overrides the rules config if the overlap. - * @return void - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrulesprocessor-options) - */ - rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => object, options?: {validate: object}): void; // TODO needs implementation - - /** - * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false). - * @return Return value: none. - * Note that if the method fails and throws an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is recommended to abort the process when the server fails to start properly. If you must try to resume after an error, call server.stop() first to reset the server state. - * If a started server is started again, the second call to server.start() is ignored. No events will be emitted and no extension points invoked. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart) - */ - start(): Promise; - - /** - * HTTP state management uses client cookies to persist a state across multiple requests. - * @param name - the cookie name string. - * @param options - are the optional cookie settings - * @return Return value: none. - * State defaults can be modified via the server default state configuration option. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) - */ - state(name: string, options?: ServerStateCookieOptions): void; - - /** - * Stops the server's listener by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: - * @param options - (optional) object with: - * * timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions) - */ - stop(options?: {timeout: number}): Promise; - - /** - * Returns a copy of the routing table where: - * @param host - (optional) host to filter routes matching a specific virtual host. Defaults to all virtual hosts. - * @return Return value: an array of routes where each route contains: - * * settings - the route config with defaults applied. - * * method - the HTTP method in lower case. - * * path - the route path. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost) - */ - table(host?: string): {settings: ServerRoute; method: Util.HTTP_METHODS_PARTIAL_LOWERCASE, path: string}[]; // TODO I am not sure if the ServerRoute is the object expected here - -} diff --git a/types/hapi/definitions/util/common.d.ts b/types/hapi/definitions/util/common.d.ts deleted file mode 100644 index 3873cc6900..0000000000 --- a/types/hapi/definitions/util/common.d.ts +++ /dev/null @@ -1,8 +0,0 @@ - -/** - * User-extensible type for application specific state. - */ -export interface ApplicationState { -} - -export type PeekListener = (chunk: string, encoding: string) => void; \ No newline at end of file diff --git a/types/hapi/definitions/util/json.d.ts b/types/hapi/definitions/util/json.d.ts deleted file mode 100644 index 116f6bdf9a..0000000000 --- a/types/hapi/definitions/util/json.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -export namespace Json { - - /** - * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} - */ - export type StringifyReplacer = ((key: string, value: any) => any) | (string | number)[] | undefined; - - /** - * Any value greater than 10 is truncated. - */ - export type StringifySpace = number | string; - - /** - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) - */ - export interface StringifyArguments { - /** the replacer function or array. Defaults to no action. */ - replacer?: StringifyReplacer; - /** number of spaces to indent nested object keys. Defaults to no indentation. */ - space?: StringifySpace; - /** tring suffix added after conversion to JSON string. Defaults to no suffix. **/ - suffix?: string; - /** calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. **/ - escape?: boolean; - } - -} diff --git a/types/hapi/definitions/util/lifecycle.d.ts b/types/hapi/definitions/util/lifecycle.d.ts deleted file mode 100644 index 35f347dcd5..0000000000 --- a/types/hapi/definitions/util/lifecycle.d.ts +++ /dev/null @@ -1,59 +0,0 @@ -import * as Boom from "boom"; -import * as stream from "stream"; -import {Request, ResponseToolkit} from "hapi"; - -export namespace Lifecycle { - - /** - * Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps: - * extensions, authentication, handlers, pre-handler methods, and failAction function values are lifecyle methods - * provided by the developer and executed by the framework. - * Each lifecycle method is a function with the signature await function(request, h, [err]) where: - * * request - the request object. - * * h - the response toolkit the handler must call to set a response and return control back to the framework. - * * err - an error object availble only when the method is used as a failAction value. - */ - export interface Method { - (request: Request, h: ResponseToolkit): ReturnValue; - (request: Request, h: ResponseToolkit, err: Error): ReturnValue; - } - - /** - * Each lifecycle method must return a value or a promise that resolves into a value. If a lifecycle method returns - * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent. - * The return value must be one of: - * * Plain value: null, string, number, boolean - * * Buffer object - * * Error object: plain Error OR a Boom object. - * * Stream object - * * any object or array - * * a toolkit signal: - * * a toolkit method response: - * * a promise object that resolve to any of the above values - * For more info please [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) - */ - export type ReturnValue = ReturnValueTypes | (Promise); - export type ReturnValueTypes = - (null | string | number | boolean) | - (Buffer) | - (Error | Boom.BoomError) | - (stream.Stream) | - (object | object[]) | - Object | - ResponseToolkit; - - /** - * Various configuration options allows defining how errors are handled. For example, when invalid payload is received or malformed cookie, instead of returning an error, the framework can be configured to perform another action. When supported the failAction option supports the following values: - * * 'error' - return the error object as the response. - * * 'log' - report the error but continue processing the request. - * * 'ignore' - take no action and continue processing the request. - * * a lifecycle method with the signature async function(request, h, err) where: - * * * request - the request object. - * * * h - the response toolkit. - * * * err - the error object. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-failaction-configuration) - */ - export type FailAction = 'error' | 'log' | 'ignore' | Method; - -} - diff --git a/types/hapi/definitions/util/util.d.ts b/types/hapi/definitions/util/util.d.ts deleted file mode 100644 index fc9bc97a7c..0000000000 --- a/types/hapi/definitions/util/util.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export namespace Util { - interface Dictionary { - [key: string]: T; - } - type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; - type HTTP_METHODS_PARTIAL = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | HTTP_METHODS_PARTIAL_LOWERCASE; - type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; -} diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 46d4d07ca3..f65cee14d4 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -18,54 +18,3869 @@ /// -/** PLUGIN */ -export * from './definitions/plugin/plugin'; -export * from './definitions/plugin/plugin-registered'; +import * as Boom from "boom"; +import * as catbox from "catbox"; +import * as http from "http"; +import * as https from "https"; +import * as Shot from "shot"; +import * as stream from "stream"; +import * as url from "url"; +import * as zlib from "zlib"; -/** REQUEST */ -export * from './definitions/request/request'; -export * from './definitions/request/request-auth'; -export * from './definitions/request/request-events'; -export * from './definitions/request/request-info'; -export * from './definitions/request/request-route'; +import { MimosOptions } from "mimos"; +import { SealOptions, SealOptionsSub } from "iron"; +import { AnySchema, ValidationOptions } from "joi"; +import Podium = require("podium"); -/** RESPONSE */ -export * from './definitions/response/response-events'; -export * from './definitions/response/response-object'; -export * from './definitions/response/response-settings'; -export * from './definitions/response/response-toolkit'; +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Plugin + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ -/** ROUTE */ -export * from './definitions/route/route-options'; -export * from './definitions/route/route-options-access'; -export * from './definitions/route/route-options-cache'; -export * from './definitions/route/route-options-cors'; -export * from './definitions/route/route-options-payload'; -export * from './definitions/route/route-options-pre'; -export * from './definitions/route/route-options-response'; -export * from './definitions/route/route-options-secure'; -export * from './definitions/route/route-options-validate'; +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ -/** SERVER */ -export * from './definitions/server/server'; -export * from './definitions/server/server-auth'; -export * from './definitions/server/server-auth-scheme'; -export * from './definitions/server/server-cache'; -export * from './definitions/server/server-events'; -export * from './definitions/server/server-ext'; -export * from './definitions/server/server-info'; -export * from './definitions/server/server-inject'; -export * from './definitions/server/server-method'; -export * from './definitions/server/server-options'; -export * from './definitions/server/server-options-cache'; -export * from './definitions/server/server-realm'; -export * from './definitions/server/server-register'; -export * from './definitions/server/server-route'; -export * from './definitions/server/server-state'; -export * from './definitions/server/server-state-options'; +/* tslint:disable-next-line:no-empty-interface */ +export interface PluginsListRegistered { +} -/** UTIL */ -export * from './definitions/util/common'; -export * from './definitions/util/json'; -export * from './definitions/util/lifecycle'; -export * from './definitions/util/util'; +/** + * An object of the currently registered plugins where each key is a registered plugin name and the value is an + * object containing: + * * version - the plugin version. + * * name - the plugin name. + * * options - (optional) options passed to the plugin during registration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ +export interface PluginRegistered { + /** + * the plugin version. + */ + version: string; + + /** + * the plugin name. + */ + name: string; + + /** + * options used to register the plugin. + */ + options: object; +} + +/* tslint:disable-next-line:no-empty-interface */ +export interface PluginsStates { +} + +/* tslint:disable-next-line:no-empty-interface */ +export interface PluginSpecificConfiguration { +} + +export interface PluginNameVersion { + /** + * (required) the plugin name string. The name is used as a unique key. Published plugins (e.g. published in the npm + * registry) should use the same name as the name field in their 'package.json' file. Names must be + * unique within each application. + */ + name: string; + + /** + * optional plugin version. The version is only used informatively to enable other plugins to find out the versions loaded. The version should be the same as the one specified in the plugin's + * 'package.json' file. + */ + version?: string; +} + +export interface PluginPackage { + /** + * Alternatively, the name and version can be included via the pkg property containing the 'package.json' file for the module which already has the name and version included + */ + pkg: any; +} + +/** + * Plugins provide a way to organize application code by splitting the server logic into smaller components. Each + * plugin can manipulate the server through the standard server interface, but with the added ability to sandbox + * certain properties. For example, setting a file path in one plugin doesn't affect the file path set + * in another plugin. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#plugins) + * + * The type T is the type of the plugin options. + */ +export interface PluginBase { + /** + * (required) the registration function with the signature async function(server, options) where: + * * server - the server object with a plugin-specific server.realm. + * * options - any options passed to the plugin during registration via server.register(). + */ + register: (server: Server, options: T) => Promise; + + /** (optional) if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */ + multiple?: boolean; + + /** (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via server.dependency(). */ + dependencies?: string | string[]; + + /** once - (optional) if true, will only register the plugin once per server. If set, overrides the once option passed to server.register(). Defaults to no override. */ + once?: boolean; +} + +export type Plugin = PluginBase & (PluginNameVersion | PluginPackage); + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Request + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * User-extensible type for request.auth credentials. + */ + +/* tslint:disable-next-line:no-empty-interface */ +export interface AuthCredentials { +} + +/** + * Authentication information: + * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. + * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. + * * error - the authentication error is failed and mode set to 'try'. + * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. + * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed + * authorization, set to false. + * * mode - the route authentication mode. + * * strategy - the name of the strategy used. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) + */ +export interface RequestAuth { + /** an artifact object received from the authentication strategy and used in authentication-related actions. */ + artifacts: object; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ + credentials: AuthCredentials; + /** the authentication error is failed and mode set to 'try'. */ + error: Error; + /** true if the request has been successfully authenticated, otherwise false. */ + isAuthenticated: boolean; + /** + * true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization, + * set to false. + */ + isAuthorized: boolean; + /** the route authentication mode. */ + mode: string; + /** the name of the strategy used. */ + strategy: string; +} + +/** + * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ +export type RequestEventType = "peek" | "finish" | "disconnect"; + +/** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ +export interface RequestEvents extends Podium { + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + on(criteria: "peek", listener: PeekListener): void; + + on(criteria: "finish" | "disconnect", listener: (data: undefined) => void): void; + + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + once(criteria: "peek", listener: PeekListener): void; + + once(criteria: "finish" | "disconnect", listener: (data: undefined) => void): void; +} + +/** + * Request information: + * * acceptEncoding - the request preferred encoding. + * * cors - if CORS is enabled for the route, contains the following: + * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only + * available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). + * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). + * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). + * * received - request reception timestamp. + * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. + * * remoteAddress - remote client IP address. + * * remotePort - remote client port. + * * responded - request response timestamp (0 is not responded yet). + * Note that the request.info object is not meant to be modified. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) + */ +export interface RequestInfo { + /** the request preferred encoding. */ + acceptEncoding: string; + /** if CORS is enabled for the route, contains the following: */ + cors: { + /** + * true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after + * the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + */ + isOriginMatch?: boolean; + }; + /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ + host: string; + /** the hostname part of the 'Host' header (e.g. 'example.com'). */ + hostname: string; + /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}') */ + id: string; + /** request reception timestamp. */ + received: number; + /** content of the HTTP 'Referrer' (or 'Referer') header. */ + referrer: string; + /** remote client IP address. */ + remoteAddress: string; + /** remote client port. */ + remotePort: string; + /** request response timestamp (0 is not responded yet). */ + responded: number; +} + +/** + * The request route information object, where: + * * method - the route HTTP method. + * * path - the route path. + * * vhost - the route vhost option if configured. + * * realm - the active realm associated with the route. + * * settings - the route options object with all defaults applied. + * * fingerprint - the route internal normalized string representing the normalized path. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) + */ +export interface RequestRoute { + /** the route HTTP method. */ + method: Util.HTTP_METHODS_PARTIAL; + + /** the route path. */ + path: string; + + /** the route vhost option if configured. */ + vhost?: string | string[]; + + /** the active realm associated with the route. */ + realm: ServerRealm; + + /** the route options object with all defaults applied. */ + settings: RouteOptions; + + /** the route internal normalized string representing the normalized path. */ + fingerprint: string; + + auth: { + /** + * Validates a request against the route's authentication access configuration, where: + * @param request - the request object. + * @return Return value: true if the request would have passed the route's access requirements. + * Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access + * configuration. If the route uses dynamic scopes, the scopes are constructed against the request.query, request.params, request.payload, and request.auth.credentials which may or may + * not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or not at all), it will return false if the route + * requires any authentication. + * [See docs](https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest) + */ + access(request: Request): boolean; + }; +} + +/** + * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestorig) + */ +export interface RequestOrig { + params: object; + query: object; + payload: object; +} + +export interface RequestLog { + request: string; + timestamp: number; + tags: string[]; + data: string | object; + channel: string; +} + +/** + * The request object is created internally for each incoming request. It is not the same object received from the node + * HTTP server callback (which is available via [request.raw.req](https://github.com/hapijs/hapi/blob/master/API.md#request.raw)). The request properties change throughout + * the request [lifecycle](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle). + */ +export interface Request extends Podium { + /** + * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestapp) + */ + app: ApplicationState; + + /** + * Authentication information: + * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. + * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. + * * error - the authentication error is failed and mode set to 'try'. + * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. + * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed + * authorization, set to false. + * * mode - the route authentication mode. + * * strategy - the name of the strategy used. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) + */ + readonly auth: RequestAuth; + + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + events: RequestEvents; + + /** + * The raw request headers (references request.raw.req.headers). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders) + */ + readonly headers: Util.Dictionary; + + /** + * Request information: + * * acceptEncoding - the request preferred encoding. + * * cors - if CORS is enabled for the route, contains the following: + * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only + * available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). + * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). + * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). + * * received - request reception timestamp. + * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. + * * remoteAddress - remote client IP address. + * * remotePort - remote client port. + * * responded - request response timestamp (0 is not responded yet). + * Note that the request.info object is not meant to be modified. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) + */ + readonly info: RequestInfo; + + /** + * An array containing the logged request events. + * Note that this array will be empty if route log.collect is set to false. + */ + readonly logs: RequestLog[]; + + /** + * The request method in lower case (e.g. 'get', 'post'). + */ + readonly method: Util.HTTP_METHODS_PARTIAL_LOWERCASE; + + /** + * The parsed content-type header. Only available when payload parsing enabled and no payload error occurred. + */ + readonly mime: string; + + /** + * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. + */ + readonly orig: RequestOrig; + + /** + * An object where each key is a path parameter name with matching value as described in [Path parameters](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters). + */ + readonly params: Util.Dictionary; + + /** + * An array containing all the path params values in the order they appeared in the path. + */ + readonly paramsArray: string[]; + + /** + * The request URI's pathname component. + */ + readonly path: string; + + /** + * The request payload based on the route payload.output and payload.parse settings. + * TODO check this typing and add references / links. + */ + readonly payload: stream.Readable | Buffer | string | object; + + /** + * Plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. + */ + plugins: PluginsStates; + + /** + * An object where each key is the name assigned by a route pre-handler methods function. The values are the raw values provided to the continuation function as argument. For the wrapped response + * object, use responses. + */ + readonly pre: Util.Dictionary; + + /** + * Access: read / write (see limitations below). + * The response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to + * override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects). + */ + response: ResponseObject | Boom.BoomError | null; + + /** + * Same as pre but represented as the response object created by the pre method. + */ + readonly preResponses: Util.Dictionary; + + /** + * By default the object outputted from node's URL parse() method. Might also be set indirectly via request.setUrl in which case it may be a string (if url is set to an object with the query + * attribute as an unparsed string). + */ + readonly query: any; + + /** + * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended. + * * req - the node request object. + * * res - the node response object. + */ + readonly raw: { + req: http.IncomingMessage; + res: http.ServerResponse; + }; + + /** + * The request route information object and method + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestrouteauthaccessrequest) + */ + readonly route: RequestRoute; + + /** + * Access: read only and the public server interface. + * The server object. + */ + server: Server; + + /** + * An object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. + */ + readonly state: Util.Dictionary; + + /** + * The parsed request URI. + */ + readonly url: url.Url; + + /** + * Returns a response which you can pass into the reply interface where: + * @param source - the value to set as the source of the reply interface, optional. + * @param options - options for the method, optional. + * @return ResponseObject + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestgenerateresponsesource-options) + */ + /* tslint:disable-next-line:max-line-length */ + generateResponse(source: string | object | null, options?: { variety?: string; prepare?: (response: ResponseObject) => Promise; marshal?: (response: ResponseObject) => Promise; close?: (response: ResponseObject) => void; }): ResponseObject; + + /** + * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: + * @param tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism + * for describing and filtering events. + * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return + * value) the actual data emitted to the listeners. Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag + * set to true. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data) + */ + log(tags: string | string[], data?: string | object | (() => string | object)): void; + + /** + * Changes the request method before the router begins processing the request where: + * @param method - is the request HTTP method (e.g. 'GET'). + * @return void + * Can only be called from an 'onRequest' extension method. + * [See docs](https://hapijs.com/api/17.0.1#-requestsetmethodmethod) + */ + setMethod(method: Util.HTTP_METHODS_PARTIAL): void; + + /** + * Changes the request URI before the router begins processing the request where: + * Can only be called from an 'onRequest' extension method. + * @param url - the new request URI. If url is a string, it is parsed with node's URL parse() method with parseQueryString set to true. url can also be set to an object compatible with node's URL + * parse() method output. + * @param stripTrailingSlash - if true, strip the trailing slash from the path. Defaults to false. + * @return void + * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) + */ + setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Response + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * Access: read only and the public podium interface. + * The response.events object supports the following events: + * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + * [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ +export interface ResponseEvents extends Podium { + /** + * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + */ + on(criteria: 'peek', listener: PeekListener): void; + + on(criteria: 'finish', listener: (data: undefined) => void): void; + + /** + * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + */ + once(criteria: 'peek', listener: PeekListener): void; + + once(criteria: 'finish', listener: (data: undefined) => void): void; +} + +/** + * Object where: + * * append - if true, the value is appended to any existing header value using separator. Defaults to false. + * * separator - string used as separator when appending to an existing value. Defaults to ','. + * * override - if false, the header value is not set if an existing value present. Defaults to true. + * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) + */ +export interface ResponseObjectHeaderOptions { + append?: boolean; + separator?: string; + override?: boolean; + duplicate?: boolean; +} + +/** + * The response object contains the request response value along with various HTTP headers and flags. When a lifecycle + * method returns a value, the value is wrapped in a response object along with some default flags (e.g. 200 status + * code). In order to customize a response before it is returned, the h.response() method is provided. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) + * TODO, check extending from Podium is correct. Extending because of "The response object supports the following events" [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ +export interface ResponseObject extends Podium { + /** + * Default value: {}. + * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseapp) + */ + app: ApplicationState; + + /** + * Access: read only and the public podium interface. + * The response.events object supports the following events: + * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + * [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ + readonly events: ResponseEvents; + + /** + * Default value: {}. + * An object containing the response headers where each key is a header field name and the value is the string header value or array of string. + * Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders) + */ + readonly headers: Util.Dictionary; + + /** + * Default value: {}. + * Plugin-specific state. Provides a place to store and pass request-level plugin data. plugins is an object where each key is a plugin name and the value is the state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseplugins) + */ + plugins: PluginsStates; + + /** + * Object containing the response handling flags. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) + */ + readonly settings: ResponseSettings; + + /** + * The raw value returned by the lifecycle method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesource) + */ + readonly source: Lifecycle.ReturnValue; + + /** + * Default value: 200. + * The HTTP response status code. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatuscode) + */ + readonly statusCode: number; + + /** + * A string indicating the type of source with available values: + * * 'plain' - a plain response such as string, number, null, or simple object. + * * 'buffer' - a Buffer. + * * 'stream' - a Stream. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevariety) + */ + readonly variety: 'plain' | 'buffer' | 'stream'; + + /** + * Sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: + * @param length - the header value. Must match the actual payload size. + * @return Return value: the current response object. + * [See docs](https://hapijs.com/api/17.0.1#-responsebyteslength) + */ + bytes(length: number): ResponseObject; + + /** + * Sets the 'Content-Type' HTTP header 'charset' property where: + * @param charset - the charset property value. + * @return Return value: the current response object. + * [See docs](https://hapijs.com/api/17.0.1#-responsecharsetcharset) + */ + charset(charset: string): ResponseObject; + + /** + * Sets the 'Content-Type' HTTP header 'charset' property where: + * $param charset - the charset property value. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecodestatuscode) + */ + code(statusCode: number): ResponseObject; + + /** + * Sets the HTTP status message where: + * @param httpMessage - the HTTP status message (e.g. 'Ok' for status code 200). + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsemessagehttpmessage) + */ + message(httpMessage: string): ResponseObject; + + /** + * Sets the HTTP status code to Created (201) and the HTTP 'Location' header where: + * @param uri - an absolute or relative URI used as the 'Location' header value. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecreateduri) + */ + created(uri: string): ResponseObject; + + /** + * Sets the string encoding scheme used to serial data into the HTTP payload where: + * @param encoding the encoding property value (see node Buffer encoding [See docs](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)). + * * 'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set. + * * 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. + * * 'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported. + * * 'ucs2' - Alias of 'utf16le'. + * * 'base64' - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5. + * * 'latin1' - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes). + * * 'binary' - Alias for 'latin1'. + * * 'hex' - Encode each byte as two hexadecimal characters. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseencodingencoding) + */ + encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): ResponseObject; + + /** + * Sets the representation entity tag where: + * @param tag - the entity tag string without the double-quote. + * @param options - (optional) settings where: + * * weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. + * * vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by + * a '-' character). Ignored when weak is true. Defaults to true. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseetagtag-options) + */ + etag(tag: string, options?: {weak: boolean, vary: boolean}): ResponseObject; + + /** + * Sets an HTTP header where: + * @param name - the header name. + * @param value - the header value. + * @param options - (optional) object where: + * * append - if true, the value is appended to any existing header value using separator. Defaults to false. + * * separator - string used as separator when appending to an existing value. Defaults to ','. + * * override - if false, the header value is not set if an existing value present. Defaults to true. + * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) + */ + header(name: string, value: string, options?: ResponseObjectHeaderOptions): ResponseObject; + + /** + * Sets the HTTP 'Location' header where: + * @param uri - an absolute or relative URI used as the 'Location' header value. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responselocationuri) + */ + location(uri: string): ResponseObject; + + /** + * Sets an HTTP redirection response (302) and decorates the response with additional methods, where: + * @param uri - an absolute or relative URI used to redirect the client to another resource. + * @return Return value: the current response object. + * Decorates the response object with the response.temporary(), response.permanent(), and response.rewritable() methods to easily change the default redirection code (302). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseredirecturi) + */ + redirect(uri: string): ResponseObject; + + /** + * Sets the JSON.stringify() replacer argument where: + * @param method - the replacer function or array. Defaults to none. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsereplacermethod) + */ + replacer(method: Json.StringifyReplacer): ResponseObject; + + /** + * Sets the JSON.stringify() space argument where: + * @param count - the number of spaces to indent nested object keys. Defaults to no indentation. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsespacescount) + */ + spaces(count: number): ResponseObject; + + /** + * Sets an HTTP cookie where: + * @param name - the cookie name. + * @param value - the cookie value. If no options.encoding is defined, must be a string. See server.state() for supported encoding values. + * @param options - (optional) configuration. If the state was previously registered with the server using server.state(), the specified keys in options are merged with the default server + * definition. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options) + */ + state(name: string, value: object | string, options?: ServerStateCookieOptions): ResponseObject; + + /** + * Sets a string suffix when the response is process via JSON.stringify() where: + * @param suffix - the string suffix. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesuffixsuffix) + */ + suffix(suffix: string): ResponseObject; + + /** + * Overrides the default route cache expiration rule for this response instance where: + * @param msec - the time-to-live value in milliseconds. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsettlmsec) + */ + ttl(msec: number): ResponseObject; + + /** + * Sets the HTTP 'Content-Type' header where: + * @param mimeType - is the mime type. + * @return Return value: the current response object. + * Should only be used to override the built-in default for each response type. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetypemimetype) + */ + type(mimeType: string): ResponseObject; + + /** + * Clears the HTTP cookie by setting an expired value where: + * @param name - the cookie name. + * @param options - (optional) configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified options are merged with the server + * definition. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseunstatename-options) + */ + unstate(name: string, options?: ServerStateCookieOptions): ResponseObject; + + /** + * Adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: + * @param header - the HTTP request header name. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevaryheader) + */ + vary(header: string): ResponseObject; + + /** + * Marks the response object as a takeover response. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetakeover) + */ + takeover(): ResponseObject; + + /** + * Sets the status code to 302 or 307 (based on the response.rewritable() setting) where: + * @param isTemporary - if false, sets status to permanent. Defaults to true. + * @return Return value: the current response object. + * Only available after calling the response.redirect() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetemporaryistemporary) + */ + temporary(isTemporary: boolean): ResponseObject; + + /** + * Sets the status code to 301 or 308 (based on the response.rewritable() setting) where: + * @param isPermanent - if false, sets status to temporary. Defaults to true. + * @return Return value: the current response object. + * Only available after calling the response.redirect() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsepermanentispermanent) + */ + permanent(isPermanent: boolean): ResponseObject; + + /** + * Sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' + * to 'GET'). Exact code based on the response.temporary() or response.permanent() setting. Arguments: + * @param isRewritable - if false, sets to non-rewritable. Defaults to true. + * @return Return value: the current response object. + * Only available after calling the response.redirect() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responserewritableisrewritable) + */ + rewritable(isRewritable: boolean): ResponseObject; +} + +/** + * Object containing the response handling flags. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) + */ +export interface ResponseSettings { + /** + * Defaults value: true. + * If true and source is a Stream, copies the statusCode and headers properties of the stream object to the outbound response. + */ + readonly passThrough: boolean; + + /** + * Default value: null (use route defaults). + * Override the route json options used when source value requires stringification. + */ + readonly stringify: Json.StringifyArguments; + + /** + * Default value: null (use route defaults). + * If set, overrides the route cache with an expiration value in milliseconds. + */ + readonly ttl: number; + + /** + * Default value: false. + * If true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present. + */ + varyEtag: boolean; +} + +/** + * See more about Lifecycle + * https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle + * + */ + +export type ResponseValue = string | object; + +export interface AuthenticationData { + credentials: object; + artifacts?: object; +} + +/** + * The response toolkit is a collection of properties and utilities passed to every [lifecycle method](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) + * It is somewhat hard to define as it provides both utilities for manipulating responses as well as other information. Since the + * toolkit is passed as a function argument, developers can name it whatever they want. For the purpose of this + * document the h notation is used. It is named in the spirit of the RethinkDB r method, with h for hapi. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit) + */ +export interface ResponseToolkit { + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step + * without further interaction with the node response stream. It is the developer's responsibility to write + * and end the response directly via [request.raw.res](https://github.com/hapijs/hapi/blob/master/API.md#request.raw). + */ + readonly abandon: symbol; + + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step after + * calling request.raw.res.end()) to close the the node response stream. + */ + readonly close: symbol; + + /** + * A response symbol. Provides access to the route or server context set via the route [bind](https://github.com/hapijs/hapi/blob/master/API.md#route.options.bind) + * option or [server.bind()](https://github.com/hapijs/hapi/blob/master/API.md#server.bind()). + */ + readonly context: any; + + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle continues without changing the response. + */ + readonly continue: symbol; + + /** + * The [server realm](https://github.com/hapijs/hapi/blob/master/API.md#server.realm) associated with the matching + * route. Defaults to the root server realm in the onRequest step. + */ + readonly realm: ServerRealm; + + /** + * Access: read only and public request interface. + * The [request] object. This is a duplication of the request lifecycle method argument used by + * [toolkit decorations](https://github.com/hapijs/hapi/blob/master/API.md#server.decorate()) to access the current request. + */ + readonly request: Readonly; + + /** + * Used by the [authentication] method to pass back valid credentials where: + * @param data - an object with: + * * credentials - (required) object representing the authenticated entity. + * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. + * @return Return value: an internal authentication object. + */ + authenticated(data: AuthenticationData): object; + + /** + * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if + * the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request + * conditions, h.entity() returns a response object for the lifecycle method to return as its value which will + * set a 304 response. Otherwise, it sets the provided entity headers and returns undefined. + * The method argumetns are: + * @param options - a required configuration object with: + * * etag - the ETag string. Required if modified is not present. Defaults to no header. + * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header. + * * vary - same as the response.etag() option. Defaults to true. + * @return Return value: - a response object if the response is unmodified. - undefined if the response has changed. + * If undefined is returned, the developer must return a valid lifecycle method value. If a response is returned, + * it should be used as the return value (but may be customize using the response methods). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hentityoptions) + */ + entity(options?: {etag?: string, modified?: string, vary?: boolean}): ResponseObject | undefined; + + /** + * Redirects the client to the specified uri. Same as calling h.response().redirect(uri). + * @param url + * @return Returns a response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi) + */ + redirect(uri?: string): ResponseObject; + + /** + * Wraps the provided value and returns a response object which allows customizing the response + * (e.g. setting the HTTP status code, custom headers, etc.), where: + * @param value - (optional) return value. Defaults to null. + * @return Returns a response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue) + */ + response(value?: ResponseValue): ResponseObject; + + /** + * Sets a response cookie using the same arguments as response.state(). + * @param name of the cookie + * @param value of the cookie + * @param (optional) ServerStateCookieOptions object. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hstatename-value-options) + */ + state(name: string, value: string, options?: ServerStateCookieOptions): void; + + /** + * Used by the [authentication] method to indicate authentication failed and pass back the credentials received where: + * @param error - (required) the authentication error. + * @param data - (optional) an object with: + * * credentials - (required) object representing the authenticated entity. + * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. + * @return void. + * The method is used to pass both the authentication error and the credentials. For example, if a request included + * expired credentials, it allows the method to pass back the user information (combined with a 'try' + * authentication mode) for error customization. + * There is no difference between throwing the error or passing it with the h.unauthenticated() method is no credentials are passed, but it might still be helpful for code clarity. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunauthenticatederror-data) + */ + unauthenticated(error: Error, data?: AuthenticationData): void; + + /** + * Clears a response cookie using the same arguments as + * @param name of the cookie + * @param options (optional) ServerStateCookieOptions object. + * @return void. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunstatename-options) + */ + unstate(name: string, options?: ServerStateCookieOptions): void; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Route + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +export type RouteOptionsAccessScope = false | string | string[]; + +export type RouteOptionsAccessEntity = 'any' | 'user' | 'app'; + +export interface RouteOptionsAccessScopeObject { + scope: RouteOptionsAccessScope; +} + +export interface RouteOptionsAccessEntityObject { + entity: RouteOptionsAccessEntity; +} + +export type RouteOptionsAccessObject = + RouteOptionsAccessScopeObject + | RouteOptionsAccessEntityObject + | (RouteOptionsAccessScopeObject & RouteOptionsAccessEntityObject); + +/** + * Route Authentication Options + */ +export interface RouteOptionsAccess { + /** + * Default value: none. + * An object or array of objects specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one of the rules matches. Each rule object + * must include at least one of scope or entity. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccess) + */ + access?: RouteOptionsAccessObject | RouteOptionsAccessObject[]; + + /** + * Default value: false (no scope requirements). + * The application scope required to access the route. Value can be a scope string or an array of scope strings. When authenticated, the credentials object scope property must contain at least + * one of the scopes defined to access the route. If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, that scope is forbidden. For + * example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' scope must not include 'a', must include 'b', and must include one of 'c' or 'd'. You may also access + * properties on the request object (query, params, payload, and credentials) to populate a dynamic scope by using the '{' and '}' characters around the property name, such as 'user-{params.id}'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope) + */ + scope?: RouteOptionsAccessScope; + + /** + * Default value: 'any'. + * The required authenticated entity type. If set, must match the entity value of the request authenticated credentials. Available values: + * * 'any' - the authentication can be on behalf of a user or application. + * * 'user' - the authentication must be on behalf of a user which is identified by the presence of a 'user' attribute in the credentials object returned by the authentication strategy. + * * 'app' - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication + * strategy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessentity) + */ + entity?: RouteOptionsAccessEntity; + + /** + * Default value: 'required'. + * The authentication mode. Available values: + * * 'required' - authentication is required. + * * 'optional' - authentication is optional - the request must include valid credentials or no credentials at all. + * * 'try' - similar to 'optional', any request credentials are attempted authentication, but if the credentials are invalid, the request proceeds regardless of the authentication error. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthmode) + */ + mode?: 'required' | 'optional' | 'try'; + + /** + * Default value: false, unless the scheme requires payload authentication. + * If set, the incoming request payload is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. Hawk). Cannot be set to a value other than 'required' + * when the scheme sets the authentication options.payload to true. Available values: + * * false - no payload authentication. + * * 'required' - payload authentication required. + * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthpayload) + */ + payload?: false | 'required' | 'optional'; + + /** + * Default value: the default strategy set via server.auth.default(). + * An array of string strategy names in the order they should be attempted. Cannot be used together with strategy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategies) + */ + strategies?: string[]; + + /** + * Default value: the default strategy set via server.auth.default(). + * A string strategy names. Cannot be used together with strategies. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategy) + */ + strategy?: string; +} + +/** + * Values are: + * * * 'default' - no privacy flag. + * * * 'public' - mark the response as suitable for public caching. + * * * 'private' - mark the response as suitable only for private caching. + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. + * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. + * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) + */ +export type RouteOptionsCache = { + privacy?: 'default' | 'public' | 'privacy'; + statuses?: number[]; + otherwise?: string; +} & ( + { + expiresIn?: number; + expiresAt?: undefined; + } | { + expiresIn?: undefined; + expiresAt?: string; +} | { + expiresIn?: undefined; + expiresAt?: undefined; +} + ); + +/** + * Default value: false (no CORS headers). + * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain + * than the API server. To enable, set cors to true, or to an object with the following options: + * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a + * wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. + * Defaults to any origin ['*']. + * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. + * Defaults to 86400 (one day). + * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. + * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) + */ +export interface RouteOptionsCors { + /** + * an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' + * character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any + * origin ['*']. + */ + origin?: string[] | '*' | 'ignore'; + /** + * number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. + * Defaults to 86400 (one day). + */ + maxAge?: number; + /** + * a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + */ + headers?: string[]; + /** + * a strings array of additional headers to headers. Use this to keep the default headers in place. + */ + additionalHeaders?: string[]; + /** + * a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + */ + exposedHeaders?: string[]; + /** + * a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + */ + additionalExposedHeaders?: string[]; + /** + * if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + */ + credentials?: boolean; +} + +/** + * The value must be one of: + * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw + * Buffer is returned. + * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are + * provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart + * payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the + * multipart payload in the handler using a streaming parser (e.g. pez). + * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are + * presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of + * which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. For context [See + * docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) + */ +export type PayloadOutput = 'data' | 'stream' | 'file'; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) + */ +export type PayloadCompressionDecoderSettings = object; + +/** + * Determines how the request payload is processed. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) + */ +export interface RouteOptionsPayload { + /** + * Default value: allows parsing of the following mime types: + * * application/json + * * application/*+json + * * application/octet-stream + * * application/x-www-form-urlencoded + * * multipart/form-data + * * text/* + * A string or an array of strings with the allowed mime types for the endpoint. Use this settings to limit the set of allowed mime types. Note that allowing additional mime types not listed + * above will not enable them to be parsed, and if parse is true, the request will result in an error response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadallow) + */ + allow?: string | string[]; + + /** + * Default value: none. + * An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) + */ + compression?: Util.Dictionary; + + /** + * Default value: 'application/json'. + * The default content type if the 'Content-Type' request header is missing. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaddefaultcontenttype) + */ + defaultContentType?: string; + + /** + * Default value: 'error' (return a Bad Request (400) error response). + * A failAction value which determines how to handle payload parsing errors. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadfailaction) + */ + failAction?: Lifecycle.FailAction; + + /** + * Default value: 1048576 (1MB). + * Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmaxbytes) + */ + maxBytes?: number; + + /** + * Default value: none. + * Overrides payload processing for multipart requests. Value can be one of: + * * false - disable multipart processing. + * an object with the following required options: + * * output - same as the output option with an additional value option: + * * * annotated - wraps each multipart part in an object with the following keys: // TODO type this? + * * * * headers - the part headers. + * * * * filename - the part file name. + * * * * payload - the processed part payload. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmultipart) + */ + multipart?: false | { + output: PayloadOutput | 'annotated'; + }; + + /** + * Default value: 'data'. + * The processed payload format. The value must be one of: + * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw + * Buffer is returned. + * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files + * are provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart + * payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the + * multipart payload in the handler using a streaming parser (e.g. pez). + * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are + * presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track + * of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) + */ + output?: PayloadOutput; + + /** + * Default value: none. + * A mime type string overriding the 'Content-Type' header value received. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoverride) + */ + override?: string; + + /** + * Default value: true. + * Determines if the incoming payload is processed or presented raw. Available values: + * * true - if the request 'Content-Type' matches the allowed mime types set by allow (for the whole payload as well as parts), the payload is converted into an object when possible. If the + * format is unknown, a Bad Request (400) error response is sent. Any known content encoding is decoded. + * * false - the raw payload is returned unmodified. + * * 'gunzip' - the raw payload is returned unmodified after any known content encoding is decoded. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadparse) + */ + parse?: boolean | 'gunzip'; + + /** + * Default value: to 10000 (10 seconds). + * Payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) + * error response. Set to false to disable. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadtimeout) + */ + timeout?: false | number; + + /** + * Default value: os.tmpdir(). + * The directory used for writing file uploads. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaduploads) + */ + uploads?: string; +} + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export type RouteOptionsPreArray = RouteOptionsPreAllOptions[]; + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export type RouteOptionsPreAllOptions = RouteOptionsPreObject | RouteOptionsPreObject[] | Lifecycle.Method; + +/** + * An object with: + * * method - a lifecycle method. + * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. + * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export interface RouteOptionsPreObject { + /** + * a lifecycle method. + */ + method: Lifecycle.Method; + /** + * key name used to assign the response of the method to in request.pre and request.preResponses. + */ + assign: string; + /** + * A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. + */ + failAction?: Lifecycle.FailAction; +} + +export interface ValidationObject { + [key: string]: AnySchema; +} + +export type RouteOptionsResponseSchema = + boolean + | ValidationObject + | ((value: object | Buffer | string, options: ValidationOptions) => Promise); + +/** + * Processing rules for the outgoing response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) + */ +export interface RouteOptionsResponse { + /** + * Default value: 200. + * The default HTTP status code when the payload is considered empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time of response transmission (the + * response status code will remain 200 throughout the request lifecycle unless manually set). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseemptystatuscode) + */ + emptyStatusCode?: 200 | 204; + + /** + * Default value: 'error' (return an Internal Server Error (500) error response). + * A failAction value which defines what to do when a response fails payload validation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsefailaction) + */ + failAction?: Lifecycle.FailAction; + + /** + * Default value: false. + * If true, applies the validation rule changes to the response payload. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsemodify) + */ + modify?: boolean; + + /** + * Default value: none. + * [joi](http://github.com/hapijs/joi) options object pass to the validation function. Useful to set global options such as stripUnknown or abortEarly (the complete list is available here). If a + * custom validation function is defined via schema or status then options can an arbitrary object that will be passed to this function as the second argument. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseoptions) + */ + options?: ValidationOptions; // TODO needs validation + + /** + * Default value: true. + * If false, payload range support is disabled. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseranges) + */ + ranges?: boolean; + + /** + * Default value: 100 (all responses). + * The percent of response payloads validated (0 - 100). Set to 0 to disable all validation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsesample) + */ + sample?: number; + + /** + * Default value: true (no validation). + * The default response payload validation rules (for all non-error responses) expressed as one of: + * * true - any payload allowed (no validation). + * * false - no payload allowed. + * * a joi validation object. The options along with the request context ({ headers, params, query, payload, app, auth }) are passed to the validation function. + * * a validation function using the signature async function(value, options) where: + * * * value - the pending response payload. + * * * options - The options along with the request context ({ headers, params, query, payload, app, auth }). + * * * if the function returns a value and modify is true, the value is used as the new response. If the original response is an error, the return value is used to override the original error + * output.payload. If an error is thrown, the error is processed according to failAction. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseschema) + */ + schema?: RouteOptionsResponseSchema; + + /** + * Default value: none. + * Validation schemas for specific HTTP status codes. Responses (excluding errors) not matching the listed status codes are validated using the default schema. + * status is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus) + */ + status?: Util.Dictionary; +} + +/** + * Default value: false (security headers disabled). + * Sets common security headers. To enable, set security to true or to an object with the following options: + * * hsts - controls the 'Strict-Transport-Security' header, where: + * * * true - the header will be set to max-age=15768000. This is the default value. + * * * a number - the maxAge parameter will be set to the provided value. + * * * an object with the following fields: + * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000. + * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header. + * * * * preload - a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. + * * xframe - controls the 'X-Frame-Options' header, where: + * * * true - the header will be set to 'DENY'. This is the default value. + * * * 'deny' - the headers will be set to 'DENY'. + * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'. + * * * an object for specifying the 'allow-from' rule, where: + * * * * rule - one of: + * * * * * 'deny' + * * * * * 'sameorigin' + * * * * * 'allow-from' + * * * * source - when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically + * changed to 'sameorigin'. + * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. + * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively + * support old versions of IE, it may be wise to explicitly set this flag to false. + * * noOpen - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. + * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) + */ +export interface RouteOptionsSecureObject { + /** + * hsts - controls the 'Strict-Transport-Security' header + */ + hsts?: boolean | number | { + /** + * the max-age portion of the header, as a number. Default is 15768000. + */ + maxAge: number; + /** + * a boolean specifying whether to add the includeSubDomains flag to the header. + */ + includeSubdomains: boolean; + /** + * a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. + */ + preload: boolean; + }; + /** + * controls the 'X-Frame-Options' header + */ + xframe?: true | 'deny' | 'sameorigin' | { + /** + * an object for specifying the 'allow-from' rule, + */ + rule: 'deny' | 'sameorigin' | 'allow-from'; + /** + * when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed + * to 'sameorigin'. + */ + source: string; + }; + /** + * boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. + * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively + * support old versions of IE, it may be wise to explicitly set this flag to false. + */ + xss: boolean; + /** + * boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. + */ + noOpen?: boolean; + /** + * boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. + */ + noSniff?: boolean; +} + +export type RouteOptionsSecure = boolean | RouteOptionsSecureObject; + +/** + * Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. + * Request input validation rules for various request components. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) + */ +export interface RouteOptionsValidate { + /** + * Default value: none. + * An optional object with error fields copied into every validation error response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateerrorfields) + */ + errorFields?: object; + + /** + * Default value: 'error' (return a Bad Request (400) error response). + * A failAction value which determines how to handle failed validations. When set to a function, the err argument includes the type of validation error under err.output.payload.validation.source. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatefailaction) + */ + failAction?: Lifecycle.FailAction; + + /** + * Default value: true (no validation). + * Validation rules for incoming request headers: + * * true - any headers allowed (no validation performed). + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.headers object containing the request headers. + * * * options - options. + * * * if a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error + * is thrown, the error is handled according to failAction. Note that all header field names must be in lowercase to match the headers normalized by node. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateheaders) + */ + headers?: RouteOptionsResponseSchema; + + /** + * Default value: none. + * An options object passed to the joi rules or the custom validation methods. Used for setting global options such as stripUnknown or abortEarly (the complete list is available here). + * If a custom validation function (see headers, params, query, or payload above) is defined then options can an arbitrary object that will be passed to this function as the second parameter. + * The values of the other inputs (i.e. headers, query, params, payload, app, and auth) are added to the options object under the validation context (accessible in rules as + * Joi.ref('$query.key')). + * Note that validation is performed in order (i.e. headers, params, query, and payload) and if type casting is used (e.g. converting a string to a number), the value of inputs not yet validated + * will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the server routes level and at the route level, the + * individual route settings override the routes defaults (the rules are not merged). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) + */ + options?: ValidationOptions | object; + + /** + * Default value: true (no validation). + * Validation rules for incoming request path parameters, after matching the path against the route, extracting any parameters, and storing them in request.params, where: + * * true - any path parameter value allowed (no validation performed). + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.params object containing the request path parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.params value and the original value is stored in request.orig.params. Otherwise, the path parameters are left unchanged. If an + * error is thrown, the error is handled according to failAction. Note that failing to match the validation rules to the route path parameters definition will cause all requests to fail. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) + */ + params?: RouteOptionsResponseSchema; + + /** + * Default value: true (no validation). + * Validation rules for incoming request payload (request body), where: + * * true - any payload allowed (no validation performed). false - no payload allowed. + * * a joi validation object. Note that empty payloads are represented by a null value. If a validation schema is provided and empty payload are allowed, the schema must be explicitly defined by + * setting the rule to a joi schema with null allowed (e.g. Joi.object({ keys here }).allow(null)). + * * a validation function using the signature async function(value, options) where: + * * * value - the request.query object containing the request query parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.payload value and the original value is stored in request.orig.payload. Otherwise, the payload is left unchanged. If an error is + * thrown, the error is handled according to failAction. Note that validating large payloads and modifying them will cause memory duplication of the payload (since the original is kept), as well + * as the significant performance cost of validating large amounts of data. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatepayload) + */ + payload?: RouteOptionsResponseSchema; + + /** + * Default value: true (no validation). + * Validation rules for incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs, decoded, and stored in + * request.query prior to validation. Where: + * * true - any query parameter value allowed (no validation performed). false - no query parameter value allowed. + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.query object containing the request query parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.query value and the original value is stored in request.orig.query. Otherwise, the query parameters are left unchanged. If an error + * is thrown, the error is handled according to failAction. Note that changes to the query parameters will not be reflected in request.url. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatequery) + */ + query?: RouteOptionsResponseSchema; +} + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) + */ +export type RouteCompressionEncoderSettings = object; + +/** + * Each route can be customized to change the default behavior of the request lifecycle. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#route-options) + */ +export interface RouteOptions { + /** + * Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) + */ + app?: any; + + /** + * Route authentication configuration. Value can be: + * false to disable authentication if a default strategy is set. + * a string with the name of an authentication strategy registered with server.auth.strategy(). The strategy will be set to 'required' mode. + * an authentication configuration object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) + */ + auth?: false | string | RouteOptionsAccess; + + /** + * Default value: null. + * An object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsbind) + */ + bind?: object | null; + + /** + * Default value: { privacy: 'default', statuses: [200], otherwise: 'no-cache' }. + * If the route method is 'GET', the route can be configured to include HTTP caching directives in the response. Caching can be customized using an object with the following options: + * privacy - determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are: + * * * 'default' - no privacy flag. + * * * 'public' - mark the response as suitable for public caching. + * * * 'private' - mark the response as suitable only for private caching. + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. + * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. + * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. + * The default Cache-Control: no-cache header can be disabled by setting cache to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) + */ + cache?: false | RouteOptionsCache; + + /** + * An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) + */ + compression?: Util.Dictionary; + + /** + * Default value: false (no CORS headers). + * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different + * domain than the API server. To enable, set cors to true, or to an object with the following options: + * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a + * wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. + * Defaults to any origin ['*']. + * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in + * policy. Defaults to 86400 (one day). + * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. + * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) + */ + cors?: false | RouteOptionsCors; + + /** + * Default value: none. + * Route description used for generating documentation (string). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsdescription) + */ + description?: string; + + /** + * Default value: none. + * Route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the + * server.ext(events) event argument. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsext) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) + */ + ext?: { + onPreAuth?: Lifecycle.Method; + onCredentials?: Lifecycle.Method; + onPostAuth?: Lifecycle.Method; + onPreHandler?: Lifecycle.Method; + onPostHandler?: Lifecycle.Method; + onPreResponse?: Lifecycle.Method; + }; + + /** + * Default value: { relativeTo: '.' }. + * Defines the behavior for accessing files: + * * relativeTo - determines the folder relative paths are resolved against. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsfiles) + */ + files?: { + relativeTo: string; + }; + + /** + * Default value: none. + * The route handler function performs the main business logic of the route and sets the response. handler can be assigned: + * * a lifecycle method. + * * an object with a single property using the name of a handler type registred with the server.handler() method. The matching property value is passed as options to the registered handler + * generator. Note: handlers using a fat arrow style function cannot be bound to any bind property. Instead, the bound context is available under h.context. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionshandler) + */ + handler?: Lifecycle.Method | object; + + /** + * Default value: none. + * An optional unique identifier used to look up the route using server.lookup(). Cannot be assigned to routes added with an array of methods. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsid) + */ + id?: string; + + /** + * Default value: false. + * If true, the route cannot be accessed through the HTTP listener but only through the server.inject() interface with the allowInternals option set to true. Used for internal routes that should + * not be accessible to the outside world. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsisinternal) + */ + isInternal?: boolean; + + /** + * Default value: none. + * Optional arguments passed to JSON.stringify() when converting an object or error response to a string payload or escaping it after stringification. Supports the following: + * * replacer - the replacer function or array. Defaults to no action. + * * space - number of spaces to indent nested object keys. Defaults to no indentation. + * * suffix - string suffix added after conversion to JSON string. Defaults to no suffix. + * * escape - calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) + */ + json?: Json.StringifyArguments; + + /** + * Default value: none. + * Enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload. + * For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'. Cannot be used with stream + * responses. The 'Content-Type' response header is set to 'text/javascript' and the 'X-Content-Type-Options' response header is set to 'nosniff', and will override those headers even if + * explicitly set by response.type(). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjsonp) + */ + jsonp?: string; + + /** + * Default value: { collect: false }. + * Request logging options: + * collect - if true, request-level logs (both internal and application) are collected and accessible via request.logs. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionslog) + */ + log?: { + collect: boolean; + }; + + /** + * Default value: none. + * Route notes used for generating documentation (string or array of strings). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsnotes) + */ + notes?: string | string[]; + + /** + * Determines how the request payload is processed. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) + */ + payload?: RouteOptionsPayload; + + /** + * Default value: {}. + * Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsplugins) + */ + plugins?: PluginSpecificConfiguration; + + /** + * Default value: none. + * The pre option allows defining methods for performing actions before the handler is called. These methods allow breaking the handler logic into smaller, reusable components that can be shared + * ascross routes, as well as provide a cleaner error handling of prerequisite operations (e.g. load required reference data from a database). pre is assigned an ordered array of methods which + * are called serially in order. If the pre array contains another array of methods as one of its elements, those methods are called in parallel. Note that during parallel execution, if any of + * the methods error, return a takeover response, or abort signal, the other parallel methods will continue to execute but will be ignored once completed. pre can be assigned a mixed array of: + * * an array containing the elements listed below, which are executed in parallel. + * * an object with: + * * * method - a lifecycle method. + * * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. + * * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be + * assigned. + * * a method function - same as including an object with a single method key. + * Note that pre-handler methods do not behave the same way other lifecycle methods do when a value is returned. Instead of the return value becoming the new response payload, the value is used + * to assign the corresponding request.pre and request.preResponses properties. Otherwise, the handling of errors, takeover response response, or abort signal behave the same as any other + * lifecycle methods. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ + pre?: RouteOptionsPreArray; + + /** + * Processing rules for the outgoing response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) + */ + response?: RouteOptionsResponse; + + /** + * Default value: false (security headers disabled). + * Sets common security headers. To enable, set security to true or to an object with the following options: + * * hsts - controls the 'Strict-Transport-Security' header, where: + * * * true - the header will be set to max-age=15768000. This is the default value. + * * * a number - the maxAge parameter will be set to the provided value. + * * * an object with the following fields: + * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000. + * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header. + * * * * preload - a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. + * * xframe - controls the 'X-Frame-Options' header, where: + * * * true - the header will be set to 'DENY'. This is the default value. + * * * 'deny' - the headers will be set to 'DENY'. + * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'. + * * * an object for specifying the 'allow-from' rule, where: + * * * * rule - one of: + * * * * * 'deny' + * * * * * 'sameorigin' + * * * * * 'allow-from' + * * * * source - when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be + * automatically changed to 'sameorigin'. + * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. + * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you + * actively support old versions of IE, it may be wise to explicitly set this flag to false. + * * noOpen - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. + * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) + */ + security?: RouteOptionsSecure; + + /** + * Default value: { parse: true, failAction: 'error' }. + * HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265). state supports the following + * options: parse - determines if incoming 'Cookie' headers are parsed and stored in the request.state object. failAction - A failAction value which determines how to handle cookie parsing + * errors. Defaults to 'error' (return a Bad Request (400) error response). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsstate) + */ + state?: { + parse?: boolean; + failAction?: Lifecycle.FailAction; + }; + + /** + * Default value: none. + * Route tags used for generating documentation (array of strings). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstags) + */ + tags?: string[]; + + /** + * Default value: { server: false }. + * Timeouts for processing durations. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstimeout) + */ + timeout?: { + /** + * Response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming request before giving up and responding with a Service Unavailable (503) error + * response. + */ + server?: boolean | number; + + /** + * Default value: none (use node default of 2 minutes). + * By default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Set to false to disable socket timeouts. + */ + socket?: boolean | number; + }; + + /** + * Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. + * Request input validation rules for various request components. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) + */ + validate?: RouteOptionsValidate; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Server + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * The scheme options argument passed to server.auth.strategy() when instantiation a strategy. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + */ +export type ServerAuthSchemeOptions = object; + +/** + * the method implementing the scheme with signature function(server, options) where: + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + * @param server - a reference to the server object the scheme is added to. + * @param options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. + */ +export type ServerAuthScheme = (server: Server, options?: ServerAuthSchemeOptions) => ServerAuthSchemeObject; + +/* tslint:disable-next-line:no-empty-interface */ +export interface ServerAuthSchemeObjectApi { +} + +/** + * The scheme method must return an object with the following + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#authentication-scheme) + */ +export interface ServerAuthSchemeObject { + /** + * optional object which is exposed via the [server.auth.api](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.api) object. + */ + api?: ServerAuthSchemeObjectApi; + + /** + * A lifecycle method function called for each incoming request configured with the authentication scheme. The + * method is provided with two special toolkit methods for returning an authenticated or an unauthenticate result: + * * h.authenticated() - indicate request authenticated successfully. + * * h.unauthenticated() - indicate request failed to authenticate. + * @param request the request object. + * @param h the ResponseToolkit + * @return the Lifecycle.ReturnValue + */ + authenticate(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + + /** + * A lifecycle method to authenticate the request payload. + * 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'. + * @param request the request object. + * @param h the ResponseToolkit + * @return the Lifecycle.ReturnValue + */ + payload?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + + /** + * A lifecycle method to decorate the response with authentication headers before the response headers or payload is written. + * @param request the request object. + * @param h the ResponseToolkit + * @return the Lifecycle.ReturnValue + */ + response?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + + /** + * An object with the following keys: + * * payload + */ + options?: { + /** + * if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false. + */ + payload?: boolean; + }; +} + +/** + * An authentication configuration object using the same format as the route auth handler options. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) + */ +/* tslint:disable-next-line:no-empty-interface */ +export interface ServerAuthConfig extends RouteOptionsAccess { +} + +export interface ServerAuth { + /** + * An object where each key is an authentication strategy name and the value is the exposed strategy API. + * Available only when the authentication scheme exposes an API by returning an api key in the object + * returned from its implementation function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi) + */ + api: Util.Dictionary; + + /** + * Contains the default authentication configuration is a default strategy was set via + * [server.auth.default()](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.default()). + */ + readonly settings: { + default: ServerAuthConfig; + }; + + /** + * Sets a default strategy which is applied to every route where: + * @param options - one of: + * * a string with the default strategy name + * * an authentication configuration object using the same format as the route auth handler options. + * @return void. + * The default does not apply when a route config specifies auth as false, or has an authentication strategy + * configured (contains the strategy or strategies authentication settings). Otherwise, the route authentication + * config is applied to the defaults. + * Note that if the route has authentication configured, the default only applies at the time of adding the route, + * not at runtime. This means that calling server.auth.default() after adding a route with some authentication + * config will have no impact on the routes added prior. However, the default will apply to routes added + * before server.auth.default() is called if those routes lack any authentication config. + * The default auth strategy configuration can be accessed via server.auth.settings.default. To obtain the active + * authentication configuration of a route, use server.auth.lookup(request.route). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) + */ + default(options: string | ServerAuthConfig): void; + + /** + * Registers an authentication scheme where: + * @param name the scheme name. + * @param scheme - the method implementing the scheme with signature function(server, options) where: + * * server - a reference to the server object the scheme is added to. + * * options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. + * @return void. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + */ + scheme(name: string, scheme: ServerAuthScheme): void; + + /** + * Registers an authentication strategy where: + * @param name - the strategy name. + * @param scheme - the scheme name (must be previously registered using server.auth.scheme()). + * @param options - scheme options based on the scheme requirements. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthstrategyname-scheme-options) + */ + strategy(name: string, scheme: string, options?: object): void; + + /** + * Tests a request against an authentication strategy where: + * @param strategy - the strategy name registered with server.auth.strategy(). + * @param request - the request object. + * @return Return value: the authentication credentials object if authentication was successful, otherwise throws an error. + * Note that the test() method does not take into account the route authentication configuration. It also does not + * perform payload authentication. It is limited to the basic strategy authentication execution. It does not + * include verifying scope, entity, or other route properties. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) + */ + test(strategy: string, request: Request): Promise; +} + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ +export interface ServerCache { + /** + * Provisions a cache segment within the server cache facility where: + * @param options - [catbox policy](https://github.com/hapijs/catbox#policy) configuration where: + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. + * * generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is async function(id, flags) where: + * - `id` - the `id` string or object provided to the `get()` method. + * - `flags` - an object used to pass back additional flags to the cache where: + * - `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy. + * * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. + * * staleTimeout - number of milliseconds to wait before checking if an item is stale. + * * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it + * is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. + * * generateOnReadError - if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. + * * generateIgnoreWriteError - if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. + * * dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. + * * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of + * concurrent generateFunc calls beyond staleTimeout). + * * cache - the cache name configured in server.cache. Defaults to the default cache. + * * segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a + * server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. + * * shared - if true, allows multiple cache provisions to share the same segment. Default to false. + * @return Catbox Policy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ + (options: ServerOptionsCache): catbox.Policy; + + /** + * Provisions a server cache as described in server.cache where: + * @param options - same as the server cache configuration options. + * @return Return value: none. + * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions) + */ + provision(options: ServerOptionsCache): Promise; +} + +/** + * an event name string. + * an event options object. + * a podium emitter object. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) + */ +export type ServerEventsApplication = string | ServerEventsApplicationObject | Podium; + +/** + * Object that it will be used in Event + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) + */ +export interface ServerEventsApplicationObject { + /** the event name string (required). */ + name: string; + /** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */ + channels?: string | string[]; + /** + * if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). + */ + clone?: boolean; + /** + * if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified + * by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). + */ + spread?: boolean; + /** + * if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to + * the arguments list at the end. A configuration override can be set by each listener. Defaults to false. + */ + tags?: boolean; + /** + * if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first + * configuration is used. Defaults to false (a duplicate registration will throw an error). + */ + shared?: boolean; +} + +/** + * A criteria object with the following optional keys (unless noted otherwise): + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + * + * The type parameter T is the type of the name of the event. + */ +export interface ServerEventCriteria { + /** (required) the event name string. */ + name: T; + /** + * a string or array of strings specifying the event channels to subscribe to. If the event registration specified a list of allowed channels, the channels array must match the allowed + * channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter. + */ + channels?: string | string[]; + /** if true, the data object passed to server.event.emit() is cloned before it is passed to the listener method. Defaults to the event registration option (which defaults to false). */ + clone?: boolean; + /** + * a positive integer indicating the number of times the listener can be called after which the subscription is automatically removed. A count of 1 is the same as calling server.events.once(). + * Defaults to no limit. + */ + count?: number; + /** + * filter - the event tags (if present) to subscribe to which can be one of: + * * a tag string. + * * an array of tag strings. + * * an object with the following: + * * * tags - a tag string or array of tag strings. + * * * all - if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag). + */ + filter?: string | string[] | {tags: string | string[], all?: boolean}; + /** + * if true, and the data object passed to server.event.emit() is an array, the listener method is called with each array element passed as a separate argument. This should only be used + * when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false). + */ + spread?: boolean; + /** + * if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended + * to the arguments list at the end. Defaults to the event registration option (which defaults to false). + */ + tags?: boolean; +} + +export interface LogEvent { + /** the event timestamp. */ + timestamp: string; + /** an array of tags identifying the event (e.g. ['error', 'http']) */ + tags: string[]; + /** set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log() */ + channel: "internal" | "app"; + /** the request identifier. */ + request: string; + /** event-specific information. Available when event data was provided and is not an error. Errors are passed via error. */ + data: object; + /** the error object related to the event if applicable. Cannot appear together with data */ + error: object; +} + +export interface RequestEvent { + /** the event timestamp. */ + timestamp: string; + /** an array of tags identifying the event (e.g. ['error', 'http']) */ + tags: string[]; + /** set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log() */ + channel: "internal" | "app" | "error"; + /** event-specific information. Available when event data was provided and is not an error. Errors are passed via error. */ + data: object; + /** the error object related to the event if applicable. Cannot appear together with data */ + error: object; +} + +export type LogEventHandler = (event: LogEvent, tags: object) => void; +export type RequestEventHandler = (request: Request, event: RequestEvent, tags: object) => void; +export type ResponseEventHandler = (request: Request) => void; +export type RouteEventHandler = (route: ServerRoute) => void; +export type StartEventHandler = () => void; +export type StopEventHandler = () => void; + +export interface PodiumEvent { + emit(criteria: K, listener: (value: T) => void): void; + + on(criteria: K, listener: (value: T) => void): void; + + once(criteria: K, listener: (value: T) => void): void; + + once(criteria: K): Promise; + + removeListener(criteria: K, listener: Podium.Listener): this; + + removeAllListeners(criteria: K): this; + + hasListeners(criteria: K): this; +} + +/** + * Access: podium public interface. + * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. + * Use the following methods to interact with server.events: + * [server.event(events)](https://github.com/hapijs/hapi/blob/master/API.md#server.event()) - register application events. + * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. + * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. + * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to + * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ +export interface ServerEvents extends Podium { + /** + * Subscribe to an event where: + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + * See ['log' event](https://github.com/hapijs/hapi/blob/master/API.md#-log-event) + * See ['request' event](https://github.com/hapijs/hapi/blob/master/API.md#-request-event) + * See ['response' event](https://github.com/hapijs/hapi/blob/master/API.md#-response-event) + * See ['route' event](https://github.com/hapijs/hapi/blob/master/API.md#-route-event) + * See ['start' event](https://github.com/hapijs/hapi/blob/master/API.md#-start-event) + * See ['stop' event](https://github.com/hapijs/hapi/blob/master/API.md#-stop-event) + */ + on(criteria: "log" | ServerEventCriteria<"log">, listener: LogEventHandler): void; + + on(criteria: "request" | ServerEventCriteria<"request">, listener: RequestEventHandler): void; + + on(criteria: "response" | ServerEventCriteria<"response">, listener: ResponseEventHandler): void; + + on(criteria: "route" | ServerEventCriteria<"route">, listener: RouteEventHandler): void; + + on(criteria: "start" | ServerEventCriteria<"start">, listener: StartEventHandler): void; + + on(criteria: "stop" | ServerEventCriteria<"stop">, listener: StopEventHandler): void; + + /** + * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) + */ + once(criteria: "log" | ServerEventCriteria<"log">, listener: LogEventHandler): void; + + once(criteria: "request" | ServerEventCriteria<"request">, listener: RequestEventHandler): void; + + once(criteria: "response" | ServerEventCriteria<"response">, listener: ResponseEventHandler): void; + + once(criteria: "route" | ServerEventCriteria<"route">, listener: RouteEventHandler): void; + + once(criteria: "start" | ServerEventCriteria<"start">, listener: StartEventHandler): void; + + once(criteria: "stop" | ServerEventCriteria<"stop">, listener: StopEventHandler): void; + + /** + * Same as calling server.events.on() with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @return Return value: a promise that resolves when the event is emitted. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) + */ + once(criteria: string | ServerEventCriteria): Promise; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + removeListener(name: string, listener: Podium.Listener): Podium; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovealllistenersname) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + removeAllListeners(name: string): Podium; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumhaslistenersname) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + hasListeners(name: string): boolean; +} + +/** + * The extension point event name. The available extension points include the request extension points as well as the following server extension points: + * 'onPreStart' - called before the connection listeners are started. + * 'onPostStart' - called after the connection listeners are started. + * 'onPreStop' - called before the connection listeners are stopped. + * 'onPostStop' - called after the connection listeners are stopped. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) + */ +export type ServerExtType = 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop'; +export type ServerRequestExtType = + 'onRequest' + | 'onPreAuth' + | 'onCredentials' + | 'onPostAuth' + | 'onPreHandler' + | 'onPostHandler' + | 'onPreResponse'; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or + * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + */ +export interface ServerExtEventsObject { + /** + * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * 'onPreStart' - called before the connection listeners are started. + * * 'onPostStart' - called after the connection listeners are started. + * * 'onPreStop' - called before the connection listeners are stopped. + */ + type: ServerExtType; + /** + * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * server extension points: async function(server) where: + * * * server - the server object. + * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * request extension points: a lifecycle method. + */ + method: ServerExtPointFunction | ServerExtPointFunction[]; + /** + * options - (optional) an object with the following: + * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, + * or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + */ + options?: ServerExtOptions; +} + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or + * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + */ +export interface ServerExtEventsRequestObject { + /** + * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * 'onPreStart' - called before the connection listeners are started. + * * 'onPostStart' - called after the connection listeners are started. + * * 'onPreStop' - called before the connection listeners are stopped. + * * 'onPostStop' - called after the connection listeners are stopped. + */ + type: ServerRequestExtType; + /** + * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * server extension points: async function(server) where: + * * * server - the server object. + * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * request extension points: a lifecycle method. + */ + method: Lifecycle.Method | Lifecycle.Method[]; + /** + * (optional) an object with the following: + * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, + * or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + */ + options?: ServerExtOptions; +} + +export type ServerExtPointFunction = (server: Server) => void; + +/** + * An object with the following: + * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or + * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. For context [See + * docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + */ +export interface ServerExtOptions { + /** + * a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + */ + before: string | string[]; + /** + * a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + */ + after: string | string[]; + /** + * a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + */ + bind: object; + /** + * if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when + * adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + */ + sandbox?: 'server' | 'plugin'; +} + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) + * An object containing information about the server where: + */ +export interface ServerInfo { + /** + * a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). + */ + id: string; + + /** + * server creation timestamp. + */ + created: number; + + /** + * server start timestamp (0 when stopped). + */ + started: number; + + /** + * the connection [port](https://github.com/hapijs/hapi/blob/master/API.md#server.options.port) based on the following rules: + * * before the server has been started: the configured port value. + * * after the server has been started: the actual port assigned when no port is configured or was set to 0. + */ + port: number | string; + + /** + * The [host](https://github.com/hapijs/hapi/blob/master/API.md#server.options.host) configuration value. + */ + host: string; + + /** + * the active IP address the connection was bound to after starting. Set to undefined until the server has been + * started or when using a non TCP port (e.g. UNIX domain socket). + */ + address: undefined | string; + + /** + * the protocol used: + * * 'http' - HTTP. + * * 'https' - HTTPS. + * * 'socket' - UNIX domain socket or Windows named pipe. + */ + protocol: 'http' | 'https' | 'socket'; + + /** + * a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains + * the uri value if set, otherwise constructed from the available settings. If no port is configured or is set + * to 0, the uri will not include a port component until the server is started. + */ + uri: string; +} + +/** + * An object with: + * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. + * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. + * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. + * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload + * processing defaults to 'application/json' if no 'Content-Type' header provided. + * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if + * they were received via an authentication scheme. Defaults to no credentials. + * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as + * if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + * * app - (optional) sets the initial value of request.app, defaults to {}. + * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. + * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. + * * remoteAddress - (optional) sets the remote address for the incoming connection. + * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: + * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + * * end - if false, does not end the stream. Defaults to true. + * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. + * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested + * separately. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + * For context [Shot module](https://github.com/hapijs/shot) + */ +export interface ServerInjectOptions extends Shot.RequestOptions { + /** + * an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via + * an authentication scheme. Defaults to no credentials. + */ + credentials?: AuthCredentials; + /** + * (an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received + * via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + */ + artifacts?: object; + /** + * sets the initial value of request.app, defaults to {}. + */ + app?: any; + /** + * sets the initial value of request.plugins, defaults to {}. + */ + plugins?: PluginsStates; + /** + * allows access to routes with config.isInternal set to true. Defaults to false. + */ + allowInternals?: boolean; +} + +/** + * A response object with the following properties: + * * statusCode - the HTTP status code. + * * headers - an object containing the headers set. + * * payload - the response payload string. + * * rawPayload - the raw response payload buffer. + * * raw - an object with the injection request and response objects: + * * req - the simulated node request object. + * * res - the simulated node response object. + * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of + * the internal objects returned (instead of parsing the response string). + * * request - the request object. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + * For context [Shot module](https://github.com/hapijs/shot) + */ +export interface ServerInjectResponse extends Shot.ResponseObject { + /** + * the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the + * internal objects returned (instead of parsing the response string). + */ + result: object | undefined; + /** + * the request object. + */ + request: Request; +} + +/** + * The method function with a signature async function(...args, [flags]) where: + * * ...args - the method function arguments (can be any number of arguments or none). + * * flags - when caching is enabled, an object used to set optional method result flags: + * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ +export type ServerMethod = (...args: any[]) => Promise; + +/** + * The same cache configuration used in server.cache(). + * The generateTimeout option is required. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ +export interface ServerMethodCache extends catbox.PolicyOptions { + generateTimeout: number | false; +} + +/** + * Configuration object: + * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an + * arrow function. + * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. + * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically + * generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided + * which takes the same arguments as the function and returns a unique string (or null if no key can be generated). For reference [See + * docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ +export interface ServerMethodOptions { + /** + * a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow + * function. + */ + bind?: object; + /** + * the same cache configuration used in server.cache(). The generateTimeout option is required. + */ + cache?: ServerMethodCache; + /** + * a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a + * unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which + * takes the same arguments as the function and returns a unique string (or null if no key can be generated). + */ + generateKey?: (...args: any[]) => any; +} + +/** + * An object or an array of objects where each one contains: + * * name - the method name. + * * method - the method function. + * * options - (optional) settings. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) + */ +export interface ServerMethodConfigurationObject { + /** + * the method name. + */ + name: string; + /** + * the method function. + */ + method: ServerMethod; + /** + * (optional) settings. + */ + options?: ServerMethodOptions; +} + +/** + * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, + * MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-cache) + */ +export interface ServerOptionsCache extends catbox.PolicyOptions { + /** a class, a prototype function, or a catbox engine object. */ + engine?: catbox.EnginePrototypeOrObject; + + /** + * an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines + * the default cache. If every cache includes a name, a default memory cache is provisioned as well. + */ + name?: string; + + /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ + shared?: boolean; + + /** (optional) string used to isolate cached data. Defaults to 'hapi-cache'. */ + partition?: string; + + /** other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). */ + [s: string]: any; +} + +export interface ServerOptionsCompression { + minBytes: number; +} + +/** + * The server options control the behavior of the server object. Note that the options object is deeply cloned + * (with the exception of listener which is shallowly copied) and should not contain any values that are unsafe to perform deep copy on. + * All options are optionals. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-server-options) + */ +export interface ServerOptions { + /** + * Default value: '0.0.0.0' (all available network interfaces). + * Sets the hostname or IP address the server will listen on. If not configured, defaults to host if present, otherwise to all available network interfaces. Set to '127.0.0.1' or 'localhost' to + * restrict the server to only those coming from the same host. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsaddress) + */ + address?: string; + + /** + * Default value: {}. + * Provides application-specific configuration which can later be accessed via server.settings.app. The framework does not interact with this object. It is simply a reference made available + * anywhere a server reference is provided. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time + * state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsapp) + */ + app?: any; + + /** + * Default value: true. + * Used to disable the automatic initialization of the listener. When false, indicates that the listener will be started manually outside the framework. + * Cannot be set to true along with a port value. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsautolisten) + */ + autoListen?: boolean; + + /** + * Default value: { engine: require('catbox-memory' }. + * Sets up server-side caching providers. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and + * capabilities. hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized + * if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. The configuration can be assigned one or more + * (array): + * * a class or prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). A new catbox client will be created internally using this + * function. + * * a configuration object with the following: + * * * engine - a class, a prototype function, or a catbox engine object. + * * * name - an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines + * the default cache. If every cache includes a name, a default memory cache is provisioned as well. + * * * shared - if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. + * * * partition - (optional) string used to isolate cached data. Defaults to 'hapi-cache'. + * * * other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionscache) + */ + cache?: catbox.EnginePrototype | ServerOptionsCache | ServerOptionsCache[]; + + /** + * Default value: { minBytes: 1024 }. + * Defines server handling of content encoding requests. If false, response content encoding is disabled and no compression is performed by the server. + */ + compression?: boolean | ServerOptionsCompression; + + /** + * Default value: { request: ['implementation'] }. + * Determines which logged events are sent to the console. This should only be used for development and does not affect which events are actually logged internally and recorded. Set to false to + * disable all console logging, or to an object with: + * * log - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. Defaults to no output. + * * request - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to + * display all errors, set the option to ['error']. To turn off all console debug messages set it to false. To display all request logs, set it to '*'. Defaults to uncaught errors thrown in + * external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. For example, to display all errors, set the log + * or request to ['error']. To turn off all output set the log or request to false. To display all server logs, set the log or request to '*'. To disable all debug information, set debug to + * false. + */ + debug?: false | { + log?: string[] | false; + request?: string[] | false; + }; + + /** + * Default value: the operating system hostname and if not available, to 'localhost'. + * The public hostname or IP address. Used to set server.info.host and server.info.uri and as address is none provided. + */ + host?: string; + + /** + * Default value: none. + * An optional node HTTP (or HTTPS) http.Server object (or an object with a compatible interface). + * If the listener needs to be manually started, set autoListen to false. + * If the listener uses TLS, set tls to true. + */ + listener?: http.Server; + + /** + * Default value: { sampleInterval: 0 }. + * Server excessive load handling limits where: + * * sampleInterval - the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). + * * maxHeapUsedBytes - maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + * * maxRssBytes - maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + * * maxEventLoopDelay - maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + */ + load?: { + /** the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). */ + sampleInterval?: number; + /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxHeapUsedBytes?: number; + /** + * maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + */ + maxRssBytes?: number; + /** + * maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. + * Defaults to 0 (no limit). + */ + maxEventLoopDelay?: number; + }; + + /** + * Default value: none. + * Options passed to the mimos module when generating the mime database used by the server (and accessed via server.mime): + * * override - an object hash that is merged into the built in mime information specified here. Each key value pair represents a single mime object. Each override value must contain: + * * key - the lower-cased mime-type string (e.g. 'application/javascript'). + * * value - an object following the specifications outlined here. Additional values include: + * * * type - specify the type value of result objects, defaults to key. + * * * predicate - method with signature function(mime) when this mime type is found in the database, this function will execute to allows customizations. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsmime) + */ + mime?: MimosOptions; + + /** + * Default value: {}. + * Plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the + * difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. + */ + plugins?: PluginSpecificConfiguration; + + /** + * Default value: 0 (an ephemeral port). + * The TCP port the server will listen to. Defaults the next available port when the server is started (and assigned to server.info.port). + * If port is a string containing a '/' character, it is used as a UNIX domain socket path. If it starts with '\.\pipe', it is used as a Windows named pipe. + */ + port?: number | string; + + /** + * Default value: { isCaseSensitive: true, stripTrailingSlash: false }. + * Controls how incoming request URIs are matched against the routing table: + * * isCaseSensitive - determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. + * * stripTrailingSlash - removes trailing slashes on incoming paths. Defaults to false. + */ + router?: { + isCaseSensitive?: boolean; + stripTrailingSlash?: boolean; + }; + + /** + * Default value: none. + * A route options object used as the default configuration for every route. + */ + routes?: RouteOptions; + + /** + * Default value: + * { + * strictHeader: true, + * ignoreErrors: false, + * isSecure: true, + * isHttpOnly: true, + * isSameSite: 'Strict', + * encoding: 'none' + * } + * Sets the default configuration for every state (cookie) set explicitly via server.state() or implicitly (without definition) using the state configuration object. + */ + // TODO I am not sure if I need to use all the server.state() definition (like the default value) OR only the options below. The v16 use "any" here. + // state?: ServerStateCookieOptions; + state?: { + strictHeader?: boolean, + ignoreErrors?: boolean, + isSecure?: boolean, + isHttpOnly?: boolean, + isSameSite?: false | 'Strict' | 'Lax', + encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron' + }; + + /** + * Default value: none. + * Used to create an HTTPS connection. The tls object is passed unchanged to the node HTTPS server as described in the node HTTPS documentation. + */ + tls?: true | https.RequestOptions; + + /** + * Default value: constructed from runtime server information. + * The full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the server server.info.uri, otherwise constructed from the server settings. + */ + uri?: string; +} + +/** + * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When registering a plugin or an authentication scheme, a server object reference is provided + * with a new server.realm container specific to that registration. It allows each plugin to maintain its own settings without leaking and affecting other plugins. For example, a plugin can set a + * default file path for local resources without breaking other plugins' configured paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by routes + * and extensions added at the same level (server root or plugin). + * + * https://github.com/hapijs/hapi/blob/master/API.md#server.realm + */ +export interface ServerRealm { + /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: */ + modifiers: { + /** routes preferences: */ + route: { + /** + * the route path prefix used by any calls to server.route() from the server. Note that if a prefix is used and the route path is set to '/', the resulting path will not include + * the trailing slash. + */ + prefix: string; + /** the route virtual host settings used by any calls to server.route() from the server. */ + vhost: string; + } + }; + /** the realm of the parent server object, or null for the root server. */ + parent: ServerRealm | null; + /** the active plugin name (empty string if at the server root). */ + plugin: string; + /** the plugin options object passed at registration. */ + pluginOptions: object; + /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ + plugins: PluginsStates; + /** settings overrides */ + settings: { + files: { + relativeTo: string; + }; + bind: object; + }; +} + +/** + * Registration options (different from the options passed to the registration function): + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the + * second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific + * prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + */ +export interface ServerRegisterOptions { + /** + * if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second + * time a plugin is registered on the server. + */ + once?: boolean; + /** + * modifiers applied to each route added by the plugin: + */ + routes?: { + /** + * string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + */ + prefix: string; + /** + * virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + */ + vhost?: string | string[]; + }; +} + +/** + * An object with the following: + * * plugin - a plugin object. + * * options - (optional) options passed to the plugin during registration. + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the + * second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific + * prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + * + * The type parameter T is the type of the plugin configuration options. + */ +export interface ServerRegisterPluginObject extends ServerRegisterOptions { + /** + * a plugin object. + */ + plugin: Plugin; + /** + * options passed to the plugin during registration. + */ + options?: T; +} + +export interface ServerRegisterPluginObjectArray extends Array + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | undefined> { + 0: ServerRegisterPluginObject; + 1?: ServerRegisterPluginObject; + 2?: ServerRegisterPluginObject; + 3?: ServerRegisterPluginObject; + 4?: ServerRegisterPluginObject; + 5?: ServerRegisterPluginObject; + 6?: ServerRegisterPluginObject; +} + +/* tslint:disable-next-line:no-empty-interface */ +export interface HandlerDecorations { +} + +/** + * A route configuration object or an array of configuration objects where each object contains: + * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The + * path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. + * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP + * method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same + * result as adding the same route with different methods manually. + * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the + * header only (excluding the port). Defaults to all hosts. + * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being + * added to and this is bound to the current realm's bind option. + * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) + */ +export interface ServerRoute { + /** + * (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path + * can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. For context [See + * docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters) + */ + path: string; + + /** + * (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method + * (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same + * result as adding the same route with different methods manually. + */ + method: Util.HTTP_METHODS_PARTIAL | Util.HTTP_METHODS_PARTIAL[] | string | string[]; + + /** + * (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header + * only (excluding the port). Defaults to all hosts. + */ + vhost?: string | string[]; + + /** + * (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + */ + handler?: Lifecycle.Method | HandlerDecorations; + + /** + * additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to + * and this is bound to the current realm's bind option. + */ + options?: RouteOptions | ((server: Server) => RouteOptions); + + /** + * route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + */ + rules?: object; +} + +/** + * Optional cookie settings + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + */ +export interface ServerStateCookieOptions { + /** time-to-live in milliseconds. Defaults to null (session time-life - cookies are deleted when the browser is closed). */ + ttl?: number | null; + /** sets the 'Secure' flag. Defaults to true. */ + isSecure?: boolean; + /** sets the 'HttpOnly' flag. Defaults to true. */ + isHttpOnly?: boolean; + /** + * sets the 'SameSite' flag. The value must be one of: + * * false - no flag. + * * 'Strict' - sets the value to 'Strict' (this is the default value). + * * 'Lax' - sets the value to 'Lax'. + */ + isSameSite?: false | 'Strict' | 'Lax'; + /** the path scope. Defaults to null (no path). */ + path?: string | null; + /** the domain scope. Defaults to null (no domain). */ + domain?: string | null; + + /** + * if present and the cookie was not received from the client or explicitly set by the route handler, the + * cookie is automatically added to the response with the provided value. The value can be + * a function with signature async function(request) where: + */ + autoValue?(request: Request): void; + + /** + * encoding performs on the provided value before serialization. Options are: + * * 'none' - no encoding. When used, the cookie value must be a string. This is the default value. + * * 'base64' - string value is encoded using Base64. + * * 'base64json' - object value is JSON-stringified then encoded using Base64. + * * 'form' - object value is encoded using the x-www-form-urlencoded method. + * * 'iron' - Encrypts and sign the value using iron. + */ + encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron'; + /** + * an object used to calculate an HMAC for cookie integrity validation. This does not provide privacy, only a mean + * to verify that the cookie value was generated by the server. Redundant when 'iron' encoding is used. Options are: + * * integrity - algorithm options. Defaults to require('iron').defaults.integrity. + * * password - password used for HMAC key generation (must be at least 32 characters long). + */ + sign?: { + integrity?: SealOptionsSub; + password: string; + }; + /** password used for 'iron' encoding (must be at least 32 characters long). */ + password?: string; + /** options for 'iron' encoding. Defaults to require('iron').defaults. */ + iron?: SealOptions; + /** if true, errors are ignored and treated as missing cookies. */ + ignoreErrors?: boolean; + /** if true, automatically instruct the client to remove invalid cookies. Defaults to false. */ + clearInvalid?: boolean; + /** if false, allows any cookie value including values in violation of RFC 6265. Defaults to true. */ + strictHeader?: boolean; + /** used by proxy plugins (e.g. h2o2). */ + passThrough?: any; +} + +/** + * A single object or an array of object where each contains: + * * name - the cookie name. + * * value - the cookie value. + * * options - cookie configuration to override the server settings. + */ +export interface ServerStateFormat { + name: string; + value: string; + options: ServerStateCookieOptions; +} + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsstate) + */ +export interface ServerState { + /** + * The server cookies manager. + * Access: read only and statehood public interface. + */ + readonly states: object; + + /** + * The server cookies manager settings. The settings are based on the values configured in [server.options.state](https://github.com/hapijs/hapi/blob/master/API.md#server.options.state). + */ + readonly settings: ServerStateCookieOptions; + + /** + * An object containing the configuration of each cookie added via [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()) where each key is the + * cookie name and value is the configuration object. + */ + readonly cookies: object; + + /** + * An array containing the names of all configued cookies. + */ + readonly names: string[]; + + /** + * Same as calling [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()). + */ + add(name: string, options?: ServerStateCookieOptions): void; + + /** + * Formats an HTTP 'Set-Cookie' header based on the server.options.state where: + * @param cookies - a single object or an array of object where each contains: + * * name - the cookie name. + * * value - the cookie value. + * * options - cookie configuration to override the server settings. + * @return Return value: a header string. + * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie formating (e.g. when headers are set manually). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesformatcookies) + */ + format(cookies: ServerStateFormat | ServerStateFormat[]): string; + + /** + * Parses an HTTP 'Cookies' header based on the server.options.state where: + * @param header - the HTTP header. + * @return Return value: an object where each key is a cookie name and value is the parsed cookie. + * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie parsing (e.g. when server parsing is disabled). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesparseheader) + */ + parse(header: string): Util.Dictionary; +} + +/** + * The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. + * If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. + */ +export interface HandlerDecorationMethod { + (route: RouteOptions, options: any): Lifecycle.Method; + defaults?: RouteOptions | ((method: any) => RouteOptions); +} + +/** + * The general case for decorators added via server.decorate. + */ +export type DecorationMethod = (this: T, ...args: any[]) => any; + +/** + * The server object is the main application container. The server manages all incoming requests along with all + * the facilities provided by the framework. Each server supports a single connection (e.g. listen to port 80). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#server) + */ +export class Server extends Podium { + /** + * Creates a new server object + * @param options server configuration object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptions) + */ + constructor(options?: ServerOptions); + + /** + * Provides a safe place to store server-specific run-time application data without potential conflicts with + * the framework internals. The data can be accessed whenever the server is accessible. + * Initialized with an empty object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverapp) + */ + app?: ApplicationState; + + /** + * Server Auth: properties and methods + */ + auth: ServerAuth; + + /** + * Provides access to the decorations already applied to various framework interfaces. The object must not be + * modified directly, but only through server.decorate. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecorations) + */ + readonly decorations: { + /** + * decorations on the request object. + */ + request: string[], + /** + * decorations on the response toolkit. + */ + toolkit: string[], + /** + * decorations on the server object. + */ + server: string[] + }; + + /** + * Register custom application events where: + * @param events must be one of: + * * an event name string. + * * an event options object with the following optional keys (unless noted otherwise): + * * * name - the event name string (required). + * * * channels - a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). + * * * clone - if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is + * passed as-is). + * * * spread - if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override + * specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its + * type). + * * * tags - if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is + * appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false. + * * * shared - if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only + * the first configuration is used. Defaults to false (a duplicate registration will throw an error). + * * a podium emitter object. + * * an array containing any of the above. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + event(events: ServerEventsApplication | ServerEventsApplication[]): void; + + /** + * Access: podium public interface. + * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. + * Use the following methods to interact with server.events: + * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. + * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. + * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to + * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + events: ServerEvents; + + /** + * An object containing information about the server where: + * * id - a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). + * * created - server creation timestamp. + * * started - server start timestamp (0 when stopped). + * * port - the connection port based on the following rules: + * * host - The host configuration value. + * * address - the active IP address the connection was bound to after starting. Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket). + * * protocol - the protocol used: + * * 'http' - HTTP. + * * 'https' - HTTPS. + * * 'socket' - UNIX domain socket or Windows named pipe. + * * uri - a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri value if set, otherwise constructed from the available + * settings. If no port is configured or is set to 0, the uri will not include a port component until the server is started. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) + */ + readonly info: ServerInfo; + + /** + * Access: read only and listener public interface. + * The node HTTP server object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener) + */ + listener: http.Server; + + /** + * An object containing the process load metrics (when load.sampleInterval is enabled): + * * eventLoopDelay - event loop delay milliseconds. + * * heapUsed - V8 heap usage. + * * rss - RSS memory usage. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverload) + */ + readonly load: { + /** + * event loop delay milliseconds. + */ + eventLoopDelay: number; + /** + * V8 heap usage. + */ + heapUsed: number; + /** + * RSS memory usage. + */ + rss: number; + }; + + /** + * Server methods are functions registered with the server and used throughout the application as a common utility. + * Their advantage is in the ability to configure them to use the built-in cache and share across multiple request + * handlers without having to create a common module. + * sever.methods is an object which provides access to the methods registered via server.method() where each + * server method name is an object property. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods + */ + readonly methods: Util.Dictionary; + + /** + * Provides access to the server MIME database used for setting content-type information. The object must not be + * modified directly but only through the [mime](https://github.com/hapijs/hapi/blob/master/API.md#server.options.mime) server setting. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermime) + */ + mime: any; + + /** + * An object containing the values exposed by each registered plugin where each key is a plugin name and the values + * are the exposed properties by each plugin using server.expose(). Plugins may set the value of + * the server.plugins[name] object directly or via the server.expose() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins) + */ + plugins: any; + + /** + * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When + * registering a plugin or an authentication scheme, a server object reference is provided with a new server.realm + * container specific to that registration. It allows each plugin to maintain its own settings without leaking + * and affecting other plugins. + * For example, a plugin can set a default file path for local resources without breaking other plugins' configured + * paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by + * routes and extensions added at the same level (server root or plugin). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrealm) + */ + readonly realm: ServerRealm; + + /** + * An object of the currently registered plugins where each key is a registered plugin name and the value is + * an object containing: + * * version - the plugin version. + * * name - the plugin name. + * * options - (optional) options passed to the plugin during registration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ + readonly registrations: PluginsListRegistered; + + /** + * The server configuration object after defaults applied. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serversettings) + */ + readonly settings: ServerOptions; + + /** + * The server cookies manager. + * Access: read only and statehood public interface. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstates) + */ + readonly states: ServerState; + + /** + * A string indicating the listener type where: + * * 'socket' - UNIX domain socket or Windows named pipe. + * * 'tcp' - an HTTP listener. + */ + readonly type: 'socket' | 'tcp'; + + /** + * The hapi module version number. + */ + readonly version: string; + + /** + * Sets a global context used as the default bind object when adding a route or an extension where: + * @param context - the object used to bind this in lifecycle methods such as the route handler and extension methods. The context is also made available as h.context. + * @return Return value: none. + * When setting a context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. + * Ignored if the method being bound is an arrow function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext) + */ + bind(context: object): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ + cache: ServerCache; + + /** + * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where: + * @param encoding - the decoder name string. + * @param decoder - a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the + * return value is an object compatible with the output of node's zlib.createGunzip(). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder) + */ + decoder(encoding: string, decoder: ((options: PayloadCompressionDecoderSettings) => zlib.Gunzip)): void; + + /** + * Extends various framework interfaces with custom methods where: + * @param type - the interface being decorated. Supported types: + * 'handler' - adds a new handler type to be used in routes handlers. + * 'request' - adds methods to the Request object. + * 'server' - adds methods to the Server object. + * 'toolkit' - adds methods to the response toolkit. + * @param property - the object decoration key name. + * @param method - the extension function or other value. + * @param options - (optional) supports the following optional settings: + * apply - when the type is 'request', if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned + * as the decoration. extend - if true, overrides an existing decoration. The method must be a function with the signature function(existing) where: existing - is the previously set + * decoration method value. must return the new decoration function or value. cannot be used to extend handler decorations. + * @return void; + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options) + */ + decorate(type: 'handler', property: string, method: HandlerDecorationMethod, options?: {apply?: boolean, extend?: boolean}): void; + decorate(type: 'request', property: string, method: (existing: ((...args: any[]) => any)) => (request: Request) => DecorationMethod, options: {apply: true, extend: true}): void; + decorate(type: 'request', property: string, method: (request: Request) => DecorationMethod, options: {apply: true, extend?: boolean}): void; + decorate(type: 'request', property: string, method: DecorationMethod, options?: {apply?: boolean, extend?: boolean}): void; + decorate(type: 'toolkit', property: string, method: (existing: ((...args: any[]) => any)) => DecorationMethod, options: {apply?: boolean, extend: true}): void; + decorate(type: 'toolkit', property: string, method: DecorationMethod, options?: {apply?: boolean, extend?: boolean}): void; + decorate(type: 'server', property: string, method: (existing: ((...args: any[]) => any)) => DecorationMethod, options: {apply?: boolean, extend: true}): void; + decorate(type: 'server', property: string, method: DecorationMethod, options?: {apply?: boolean, extend?: boolean}): void; + + /** + * Used within a plugin to declare a required dependency on other plugins where: + * @param dependencies - a single string or an array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is + * initialized or started. + * @param after - (optional) a function that is called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is + * initialized or started. The function signature is async function(server) where: server - the server the dependency() method was called on. + * @return Return value: none. + * The after method is identical to setting a server extension point on 'onPreStart'. + * If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). + * The method does not provide version dependency which should be implemented using npm peer dependencies. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) + */ + dependency(dependencies: string | string[], after?: ((server: Server) => Promise)): void; + + /** + * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where: + * @param encoding - the encoder name string. + * @param encoder - a function using the signature function(options) where options are the encoding specific options configured in the route compression option, and the return value is an object + * compatible with the output of node's zlib.createGzip(). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) + */ + encoder(encoding: string, encoder: ((options: RouteCompressionEncoderSettings) => zlib.Gzip)): void; + + /** + * Used within a plugin to expose a property via server.plugins[name] where: + * @param key - the key assigned (server.plugins[name][key]). + * @param value - the value assigned. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) + */ + expose(key: string, value: any): void; + + /** + * Merges an object into to the existing content of server.plugins[name] where: + * @param obj - the object merged into the exposed properties container. + * @return Return value: none. + * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method + * for exposing large objects that may be expensive to clone or singleton objects such as database client + * objects. Instead favor server.expose(key, value), which only copies a reference to value. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) + */ + expose(obj: object): void; + + /** + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level + * extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + */ + ext(events: ServerExtEventsObject | ServerExtEventsObject[] | ServerExtEventsRequestObject | ServerExtEventsRequestObject[]): void; + + /** + * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options) + */ + ext(event: ServerExtType, method: ServerExtPointFunction, options?: ServerExtOptions): void; + ext(event: ServerRequestExtType, method: Lifecycle.Method, options?: ServerExtOptions): void; + + /** + * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port. + * @return Return value: none. + * Note that if the method fails and throws an error, the server is considered to be in an undefined state and + * should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and + * other event listeners will get confused by repeated attempts to start the server or make assumptions about the + * healthy state of the environment. It is recommended to abort the process when the server fails to start properly. + * If you must try to resume after an error, call server.stop() first to reset the server state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinitialize) + */ + initialize(): Promise; + + /** + * Injects a request into the server simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic + * internally without the overhead and limitations of the network stack. The method utilizes the shot module for performing injections, with some additional options and response properties: + * @param options - can be assigned a string with the requested URI, or an object with: + * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. + * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. + * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. + * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload + * processing defaults to 'application/json' if no 'Content-Type' header provided. + * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as + * if they were received via an authentication scheme. Defaults to no credentials. + * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly + * as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + * * app - (optional) sets the initial value of request.app, defaults to {}. + * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. + * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. + * * remoteAddress - (optional) sets the remote address for the incoming connection. + * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: + * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + * * end - if false, does not end the stream. Defaults to true. + * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. + * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested + * separately. + * @return Return value: a response object with the following properties: + * * statusCode - the HTTP status code. + * * headers - an object containing the headers set. + * * payload - the response payload string. + * * rawPayload - the raw response payload buffer. + * * raw - an object with the injection request and response objects: + * * req - the simulated node request object. + * * res - the simulated node response object. + * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse + * of the internal objects returned (instead of parsing the response string). + * * request - the request object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + */ + inject(options: string | ServerInjectOptions): Promise; + + /** + * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or + * output to the console. The arguments are: + * @param tags - (required) a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive + * mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. + * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return + * value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @param timestamp - (optional) an timestamp expressed in milliseconds. Defaults to Date.now() (now). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlogtags-data-timestamp) + */ + log(tags: string | string[], data?: string | object | (() => any), timestamp?: number): void; + + /** + * Looks up a route configuration where: + * @param id - the route identifier. + * @return Return value: the route information if found, otherwise null. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid) + */ + lookup(id: string): RequestRoute | null; + + /** + * Looks up a route configuration where: + * @param method - the HTTP method (e.g. 'GET', 'POST'). + * @param path - the requested path (must begin with '/'). + * @param host - (optional) hostname (to match against routes with vhost). + * @return Return value: the route information if found, otherwise null. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host) + */ + match(method: Util.HTTP_METHODS, path: string, host?: string): RequestRoute | null; + + /** + * Registers a server method where: + * @param name - a unique method name used to invoke the method via server.methods[name]. + * @param method - the method function with a signature async function(...args, [flags]) where: + * * ...args - the method function arguments (can be any number of arguments or none). + * * flags - when caching is enabled, an object used to set optional method result flags: + * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + * @param options - (optional) configuration object: + * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is + * an arrow function. + * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. + * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will + * automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation + * function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). + * @return Return value: none. + * Method names can be nested (e.g. utils.users.get) which will automatically create the full path under server.methods (e.g. accessed via server.methods.utils.users.get). + * When configured with caching enabled, server.methods[name].cache is assigned an object with the following properties and methods: - await drop(...args) - a function that can be used to clear + * the cache for a given key. - stats - an object with cache statistics, see catbox for stats documentation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ + method(name: string, method: ServerMethod, options?: ServerMethodOptions): void; + + /** + * Registers a server method function as described in server.method() using a configuration object where: + * @param methods - an object or an array of objects where each one contains: + * * name - the method name. + * * method - the method function. + * * options - (optional) settings. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) + */ + method(methods: ServerMethodConfigurationObject | ServerMethodConfigurationObject[]): void; + + /** + * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: + * @param relativeTo - the path prefix added to any relative file path starting with '.'. + * @return Return value: none. + * Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the server default route configuration files.relativeTo settings is used. The + * path only applies to routes added after it has been set. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto) + */ + path(relativeTo: string): void; + + /** + * Registers a plugin where: + * @param plugins - one or an array of: + * * a plugin object. + * * an object with the following: + * * * plugin - a plugin object. + * * * options - (optional) options passed to the plugin during registration. + * * * once, routes - (optional) plugin-specific registration options as defined below. + * @param options - (optional) registration options (different from the options passed to the registration function): + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the + * second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the + * child-specific prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + */ + /* tslint:disable-next-line:no-unnecessary-generics */ + register(plugin: ServerRegisterPluginObject, options?: ServerRegisterOptions): Promise; + /* tslint:disable-next-line:no-unnecessary-generics */ + register(plugins: ServerRegisterPluginObjectArray, options?: ServerRegisterOptions): Promise; + register(plugins: Array>, options?: ServerRegisterOptions): Promise; + /* tslint:disable-next-line:unified-signatures */ + register(plugins: Plugin | Array>, options?: ServerRegisterOptions): Promise; + + /** + * Adds a route where: + * @param route - a route configuration object or an array of configuration objects where each object contains: + * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. + * The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. + * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP + * method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has + * the same result as adding the same route with different methods manually. + * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the + * header only (excluding the port). Defaults to all hosts. + * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being + * added to and this is bound to the current realm's bind option. + * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + * @return Return value: none. + * Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) + */ + route(route: ServerRoute | ServerRoute[]): void; + + /** + * Defines a route rules processor for converting route rules object into route configuration where: + * @param processor - a function using the signature function(rules, info) where: + * * rules - + * * info - an object with the following properties: + * * * method - the route method. + * * * path - the route path. + * * * vhost - the route virtual host (if any defined). + * * returns a route config object. + * @param options - optional settings: + * * validate - rules object validation: + * * * schema - joi schema. + * * * options - optional joi validation options. Defaults to { allowUnknown: true }. + * Note that the root server and each plugin server instance can only register one rules processor. If a route is added after the rules are configured, it will not include the rules config. + * Routes added by plugins apply the rules to each of the parent realms' rules from the root to the route's realm. This means the processor defined by the plugin override the config generated + * by the root processor if they overlap. The route config overrides the rules config if the overlap. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrulesprocessor-options) + */ + rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => object, options?: {validate: object}): void; // TODO needs implementation + + /** + * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false). + * @return Return value: none. + * Note that if the method fails and throws an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the + * various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is + * recommended to abort the process when the server fails to start properly. If you must try to resume after an error, call server.stop() first to reset the server state. If a started server + * is started again, the second call to server.start() is ignored. No events will be emitted and no extension points invoked. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart) + */ + start(): Promise; + + /** + * HTTP state management uses client cookies to persist a state across multiple requests. + * @param name - the cookie name string. + * @param options - are the optional cookie settings + * @return Return value: none. + * State defaults can be modified via the server default state configuration option. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + */ + state(name: string, options?: ServerStateCookieOptions): void; + + /** + * Stops the server's listener by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: + * @param options - (optional) object with: + * * timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions) + */ + stop(options?: {timeout: number}): Promise; + + /** + * Returns a copy of the routing table where: + * @param host - (optional) host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + * @return Return value: an array of routes where each route contains: + * * settings - the route config with defaults applied. + * * method - the HTTP method in lower case. + * * path - the route path. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost) + */ + table(host?: string): Array<{settings: ServerRoute; method: Util.HTTP_METHODS_PARTIAL_LOWERCASE, path: string}>; // TODO I am not sure if the ServerRoute is the object expected here +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Utils + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * User-extensible type for application specific state. + */ + /* tslint:disable-next-line:no-empty-interface */ +export interface ApplicationState { +} + +export type PeekListener = (chunk: string, encoding: string) => void; + +export namespace Json { + /** + * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} + */ + type StringifyReplacer = ((key: string, value: any) => any) | Array<(string | number)> | undefined; + + /** + * Any value greater than 10 is truncated. + */ + type StringifySpace = number | string; + + /** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) + */ + interface StringifyArguments { + /** the replacer function or array. Defaults to no action. */ + replacer?: StringifyReplacer; + /** number of spaces to indent nested object keys. Defaults to no indentation. */ + space?: StringifySpace; + /* string suffix added after conversion to JSON string. Defaults to no suffix. */ + suffix?: string; + /* calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. */ + escape?: boolean; + } +} + +export namespace Lifecycle { + /** + * Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps: + * extensions, authentication, handlers, pre-handler methods, and failAction function values are lifecyle methods + * provided by the developer and executed by the framework. + * Each lifecycle method is a function with the signature await function(request, h, [err]) where: + * * request - the request object. + * * h - the response toolkit the handler must call to set a response and return control back to the framework. + * * err - an error object availble only when the method is used as a failAction value. + */ + type Method = (request: Request, h: ResponseToolkit, err?: Error) => ReturnValue; + + /** + * Each lifecycle method must return a value or a promise that resolves into a value. If a lifecycle method returns + * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent. + * The return value must be one of: + * - Plain value: null, string, number, boolean + * - Buffer object + * - Error object: plain Error OR a Boom object. + * - Stream object + * - any object or array + * - a toolkit signal: + * - a toolkit method response: + * - a promise object that resolve to any of the above values + * For more info please [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) + */ + type ReturnValue = ReturnValueTypes | (Promise); + type ReturnValueTypes = + (null | string | number | boolean) | + (Buffer) | + (Error | Boom.BoomError) | + (stream.Stream) | + (object | object[]) | + symbol | + ResponseToolkit; + + /** + * Various configuration options allows defining how errors are handled. For example, when invalid payload is received or malformed cookie, instead of returning an error, the framework can be + * configured to perform another action. When supported the failAction option supports the following values: + * * 'error' - return the error object as the response. + * * 'log' - report the error but continue processing the request. + * * 'ignore' - take no action and continue processing the request. + * * a lifecycle method with the signature async function(request, h, err) where: + * * * request - the request object. + * * * h - the response toolkit. + * * * err - the error object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-failaction-configuration) + */ + type FailAction = 'error' | 'log' | 'ignore' | Method; +} + +export namespace Util { + interface Dictionary { + [key: string]: T; + } + + type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; + type HTTP_METHODS_PARTIAL = + 'GET' + | 'POST' + | 'PUT' + | 'PATCH' + | 'DELETE' + | 'OPTIONS' + | HTTP_METHODS_PARTIAL_LOWERCASE; + type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; +} diff --git a/types/hapi/test/request/catch-all.ts b/types/hapi/test/request/catch-all.ts index 55db8a548b..3ee4e74c42 100644 --- a/types/hapi/test/request/catch-all.ts +++ b/types/hapi/test/request/catch-all.ts @@ -6,10 +6,9 @@ const options: ServerOptions = { }; const server = new Server(options); -const handler = (request: Request, h: ResponseToolkit) => { +server.route({ method: '*', path: '/{p*}', handler(request, h) { return h.response('The page was not found').code(404); -}; -server.route({ method: '*', path: '/{p*}', handler }); +}}); server.start(); console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/request/event-types.ts b/types/hapi/test/request/event-types.ts index b963340bb5..386b93e19d 100644 --- a/types/hapi/test/request/event-types.ts +++ b/types/hapi/test/request/event-types.ts @@ -10,12 +10,12 @@ const options: ServerOptions = { const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return 'ok: ' + request.path; } }; -const onRequest: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { +const onRequest: Lifecycle.Method = (request, h) => { /* * Server events */ @@ -29,11 +29,11 @@ const onRequest: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { console.log('Response sent for request: ' + request.path); }); - request.server.events.on('start', (route: RouteOptions) => { + request.server.events.on('start', () => { console.log('Server started'); }); - request.server.events.once('stop', (route: RouteOptions) => { + request.server.events.once('stop', () => { console.log('Server stoped'); }); @@ -42,7 +42,7 @@ const onRequest: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { */ const hash = Crypto.createHash('sha1'); - request.events.on("peek", (chunk: any) => { + request.events.on("peek", (chunk, encoding) => { hash.update(chunk); }); diff --git a/types/hapi/test/request/get-log.ts b/types/hapi/test/request/get-log.ts index 731e8ea35c..3ba2658136 100644 --- a/types/hapi/test/request/get-log.ts +++ b/types/hapi/test/request/get-log.ts @@ -5,7 +5,7 @@ const options: ServerOptions = { port: 8000, }; -const handlerFn: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { +const handlerFn: Lifecycle.Method = (request, h) => { request.log(['test', 'error'], 'Test event'); return 'path: ' + request.path; }; diff --git a/types/hapi/test/request/parameters.ts b/types/hapi/test/request/parameters.ts index 1dadbcc1eb..3f19a02d45 100644 --- a/types/hapi/test/request/parameters.ts +++ b/types/hapi/test/request/parameters.ts @@ -7,7 +7,7 @@ const options: ServerOptions = { // Example 1 // http://localhost:8000/album-name/song-optional -const getAlbum: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { +const getAlbum: Lifecycle.Method = (request, h) => { console.log(request.params); return 'ok: ' + request.path; }; @@ -19,7 +19,7 @@ const serverRoute1: ServerRoute = { // Example 2 // http://localhost:8000/person/rafael/fijalkowski -const getPerson: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { +const getPerson: Lifecycle.Method = (request, h) => { const nameParts = request.params.name.split('/'); return { first: nameParts[0], last: nameParts[1] }; }; diff --git a/types/hapi/test/request/query.ts b/types/hapi/test/request/query.ts index 1f8ea89c1b..c67381f1b9 100644 --- a/types/hapi/test/request/query.ts +++ b/types/hapi/test/request/query.ts @@ -5,7 +5,7 @@ const options: ServerOptions = { port: 8000, }; -const handlerFn: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { +const handlerFn: Lifecycle.Method = (request, h) => { const query = request.query as GetThingQuery; // http://localhost:8000/?name=test return `You asked for ${query.name}`; diff --git a/types/hapi/test/response/continue.ts b/types/hapi/test/response/continue.ts index 00bdbc9ff2..15a0f5e35b 100644 --- a/types/hapi/test/response/continue.ts +++ b/types/hapi/test/response/continue.ts @@ -8,7 +8,7 @@ const options: ServerOptions = { const serverRoute: ServerRoute = { path: '/test', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return 'ok: ' + request.path; } }; @@ -16,7 +16,7 @@ const serverRoute: ServerRoute = { const server = new Server(options); server.route(serverRoute); -server.ext("onRequest", (request: Request, h: ResponseToolkit) => { +server.ext("onRequest", (request, h) => { request.setUrl('/test'); return h.continue; }); diff --git a/types/hapi/test/response/error.ts b/types/hapi/test/response/error.ts index 52937eaa4a..513f5fbbe5 100644 --- a/types/hapi/test/response/error.ts +++ b/types/hapi/test/response/error.ts @@ -10,14 +10,14 @@ const serverRoutes: ServerRoute[] = [ { path: '/badRequest', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { throw Boom.badRequest('Unsupported parameter'); } }, { path: '/internal', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { throw new Error('unexpect error'); } }, diff --git a/types/hapi/test/response/redirect.ts b/types/hapi/test/response/redirect.ts index d7503fd5f9..dc1b904ce3 100644 --- a/types/hapi/test/response/redirect.ts +++ b/types/hapi/test/response/redirect.ts @@ -8,7 +8,7 @@ const options: ServerOptions = { const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return h.redirect('http://example.com'); } }; diff --git a/types/hapi/test/response/response-events.ts b/types/hapi/test/response/response-events.ts index 0680f7f7f8..ec1b070b18 100644 --- a/types/hapi/test/response/response-events.ts +++ b/types/hapi/test/response/response-events.ts @@ -1,13 +1,13 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-responseevents -import { Request, ResponseObject, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; +import { Lifecycle, Request, ResponseObject, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; import * as Crypto from "crypto"; -const preResponse = (request: Request, h: ResponseToolkit) => { +const preResponse: Lifecycle.Method = (request, h) => { // In onPreResponse, the response object will be defined. - const response: ResponseObject = request.response!; + const response = request.response!; const hash = Crypto.createHash('sha1'); - response.events.on('peek', (chunk: any) => { + response.events.on('peek', (chunk, encoding) => { hash.update(chunk); }); diff --git a/types/hapi/test/response/response.ts b/types/hapi/test/response/response.ts index 593eddb0fb..368b6fa80b 100644 --- a/types/hapi/test/response/response.ts +++ b/types/hapi/test/response/response.ts @@ -10,7 +10,7 @@ const serverRoutes: ServerRoute[] = [ { path: '/test1', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { const response = h.response('success'); response.type('text/plain'); response.header('X-Custom', 'some-value'); @@ -21,7 +21,7 @@ const serverRoutes: ServerRoute[] = [ { path: '/test2', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return h.response('success') .type('text/plain') .header('X-Custom', 'some-value'); diff --git a/types/hapi/test/route/adding-routes.ts b/types/hapi/test/route/adding-routes.ts index 55c58d1437..ac4c895842 100644 --- a/types/hapi/test/route/adding-routes.ts +++ b/types/hapi/test/route/adding-routes.ts @@ -8,7 +8,7 @@ const options: ServerOptions = { const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return 'ok: ' + request.path; } }; @@ -17,14 +17,14 @@ const serverRoutes: ServerRoute[] = [ { path: '/test1', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return 'ok: ' + request.path; } }, { path: '/test2', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return 'ok: ' + request.path; } }, diff --git a/types/hapi/test/route/config.ts b/types/hapi/test/route/config.ts index 8272e767f1..8cebaec269 100644 --- a/types/hapi/test/route/config.ts +++ b/types/hapi/test/route/config.ts @@ -23,14 +23,14 @@ const routeConfigTest2: ServerRoute = { const routeConfigTest3: ServerRoute = { path: '/signin', method: 'PUT', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return 'ok'; } }; const routeConfigTest4: ServerRoute = { path: '/signin', method: 'PUT', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return 'ok'; } }; @@ -41,7 +41,7 @@ server.route(routeConfig); // Handler in config const user: RouteOptions = { cache: { expiresIn: 5000 }, - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return { name: 'John' }; } }; diff --git a/types/hapi/test/route/ext.ts b/types/hapi/test/route/ext.ts new file mode 100644 index 0000000000..0a2ac25a4b --- /dev/null +++ b/types/hapi/test/route/ext.ts @@ -0,0 +1,15 @@ +import { Server } from "hapi"; + +const server = new Server(); + +server.route({ + method: 'get', + path: "/test", + options: { + ext: { + onPreResponse(request, h) { + return h.continue; + }, + } + } +}); diff --git a/types/hapi/test/route/handler.ts b/types/hapi/test/route/handler.ts index b9354f00d8..6fced10078 100644 --- a/types/hapi/test/route/handler.ts +++ b/types/hapi/test/route/handler.ts @@ -1,9 +1,9 @@ import { Lifecycle, Request, ResponseToolkit } from "hapi"; -const handler: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { +const handler: Lifecycle.Method = (request, h) => { return 'success'; }; -const strictHandler: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { +const strictHandler: Lifecycle.Method = (request, h) => { return 123; }; diff --git a/types/hapi/test/route/route-options-pre.ts b/types/hapi/test/route/route-options-pre.ts index 139e93a0f8..897f4a8ef5 100644 --- a/types/hapi/test/route/route-options-pre.ts +++ b/types/hapi/test/route/route-options-pre.ts @@ -1,26 +1,26 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre -import { Request, ResponseToolkit, Server } from "hapi"; +import { Lifecycle, Request, ResponseToolkit, Server } from "hapi"; const server = new Server({ port: 8000, }); -const pre1 = (request: Request, h: ResponseToolkit) => { +const pre1: Lifecycle.Method = (request, h) => { return 'Hello'; }; -const pre2 = (request: Request, h: ResponseToolkit) => { +const pre2: Lifecycle.Method = (request, h) => { return 'World'; }; -const pre3 = (request: Request, h: ResponseToolkit) => { +const pre3: Lifecycle.Method = (request, h) => { return `request.pre.m1 request.pre.m2`; }; server.route({ method: 'GET', path: '/', - config: { + options: { pre: [ [ // m1 and m2 executed in parallel @@ -29,7 +29,7 @@ server.route({ ], { method: pre3, assign: 'm3' }, ], - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return request.pre.m3 + '!\n'; } } diff --git a/types/hapi/test/route/route-options.ts b/types/hapi/test/route/route-options.ts index b5a9f87ce1..96237debd8 100644 --- a/types/hapi/test/route/route-options.ts +++ b/types/hapi/test/route/route-options.ts @@ -1,5 +1,6 @@ // https://github.com/hapijs/hapi/blob/master/API.md#route-options import { + Lifecycle, Request, ResponseToolkit, RouteOptions, @@ -46,7 +47,7 @@ const payloadOptions: RouteOptionsPayload = { } }, defaultContentType: 'application/json', - failAction: (request: Request, h: ResponseToolkit) => { + failAction(request, h) { return 'ok: ' + request.path; }, maxBytes: 1048576, @@ -60,21 +61,21 @@ const payloadOptions: RouteOptionsPayload = { uploads: 'dir/' }; -const pre1 = (request: Request, h: ResponseToolkit) => { +const pre1: Lifecycle.Method = (request, h) => { return 'Hello'; }; -const pre2 = (request: Request, h: ResponseToolkit) => { +const pre2: Lifecycle.Method = (request, h) => { return 'World'; }; -const pre3 = (request: Request, h: ResponseToolkit) => { +const pre3: Lifecycle.Method = (request, h) => { return `request.pre.m1 request.pre.m2`; }; const routeOptionsResponse: RouteOptionsResponse = { emptyStatusCode: 200, - failAction: (request: Request, h: ResponseToolkit) => { + failAction(request, h) { return 'ok: ' + request.path; }, modify: false, @@ -91,7 +92,7 @@ const routeOptionsResponse: RouteOptionsResponse = { const routeOptionsValidate: RouteOptionsValidate = { errorFields: {}, - failAction: (request: Request, h: ResponseToolkit) => { + failAction(request, h) { return 'ok: ' + request.path; }, headers: false, @@ -119,7 +120,7 @@ const routeOptions: RouteOptions = { description: 'description here', ext: undefined, files: { relativeTo: '.' }, - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return 'ok: ' + request.path; }, id: 'test', @@ -145,7 +146,7 @@ const routeOptions: RouteOptions = { security: false, state: { parse: true, - failAction: (request: Request, h: ResponseToolkit) => { + failAction(request, h) { return 'ok: ' + request.path; }, }, diff --git a/types/hapi/test/route/validation.ts b/types/hapi/test/route/validation.ts index 5296183e87..58190a2584 100644 --- a/types/hapi/test/route/validation.ts +++ b/types/hapi/test/route/validation.ts @@ -1,12 +1,12 @@ // from https://hapijs.com/tutorials/validation?lang=en_US -import { ServerRouteConfig, Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; +import { Request, ResponseToolkit, RouteOptions, Server, ServerOptions, ServerRoute } from "hapi"; import * as Joi from "joi"; const options: ServerOptions = { port: 8000, }; -const configObject: ServerRouteConfig = { +const routeOptions: RouteOptions = { validate: { params: { name: Joi.string().min(3).max(10) @@ -17,10 +17,10 @@ const configObject: ServerRouteConfig = { const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return 'ok: ' + request.path; }, - config: configObject + options: routeOptions }; const server = new Server(options); diff --git a/types/hapi/test/server/server-app.ts b/types/hapi/test/server/server-app.ts index 57298a4672..f51ad7ca12 100644 --- a/types/hapi/test/server/server-app.ts +++ b/types/hapi/test/server/server-app.ts @@ -18,7 +18,7 @@ server.app!.key = 'value2'; const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return 'key: ' + request.server.app!.key; } }; diff --git a/types/hapi/test/server/server-auth-api.ts b/types/hapi/test/server/server-auth-api.ts index 3b80dc7e47..3656b25f28 100644 --- a/types/hapi/test/server/server-auth-api.ts +++ b/types/hapi/test/server/server-auth-api.ts @@ -9,14 +9,14 @@ import { } from "hapi"; import * as Boom from "boom"; -const scheme: ServerAuthScheme = (server: Server, options: ServerAuthSchemeOptions): ServerAuthSchemeObject => { +const scheme: ServerAuthScheme = (server, options) => { return { api: { settings: { x: 5 } }, - authenticate: (request: Request, h: ResponseToolkit) => { + authenticate(request, h) { const authorization = request.headers.authorization; if (!authorization) { throw Boom.unauthorized(null, 'Custom'); diff --git a/types/hapi/test/server/server-auth-default.ts b/types/hapi/test/server/server-auth-default.ts index 3ec9919150..0ecec802d8 100644 --- a/types/hapi/test/server/server-auth-default.ts +++ b/types/hapi/test/server/server-auth-default.ts @@ -3,13 +3,19 @@ import { Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions } from "hapi"; import * as Boom from "boom"; +declare module 'hapi' { + interface AuthCredentials { + user?: string; + } +} + const server = new Server({ port: 8000, }); -const scheme: ServerAuthScheme = (server: Server, options: ServerAuthSchemeOptions) => { +const scheme: ServerAuthScheme = (server, options) => { return { - authenticate: (request: Request, h: ResponseToolkit) => { + authenticate(request, h) { const req = request.raw.req; const authorization = req.headers.authorization; if (!authorization) { @@ -27,8 +33,8 @@ server.auth.default('default'); server.route({ method: 'GET', path: '/', - handler: (request: Request, h: ResponseToolkit) => { - return request.auth.credentials.user; + handler(request, h) { + return request.auth.credentials.user || 'not authed'; } }); diff --git a/types/hapi/test/server/server-auth-test.ts b/types/hapi/test/server/server-auth-test.ts index ae77089ddf..bf84be2543 100644 --- a/types/hapi/test/server/server-auth-test.ts +++ b/types/hapi/test/server/server-auth-test.ts @@ -7,9 +7,9 @@ const server = new Server({ port: 8000, }); -const scheme: ServerAuthScheme = (server: Server, options: ServerAuthSchemeOptions) => { +const scheme: ServerAuthScheme = (server, options) => { return { - authenticate: (request: Request, h: ResponseToolkit) => { + authenticate(request, h) { const req = request.raw.req; const authorization = req.headers.authorization; if (!authorization) { diff --git a/types/hapi/test/server/server-bind.ts b/types/hapi/test/server/server-bind.ts index 9bec0ec5f9..1fbd37c4c2 100644 --- a/types/hapi/test/server/server-bind.ts +++ b/types/hapi/test/server/server-bind.ts @@ -1,16 +1,16 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext -import { Plugin, Request, ResponseToolkit, Server, ServerRegisterOptions } from "hapi"; +import { Lifecycle, Plugin, Request, ResponseToolkit, Server, ServerRegisterOptions } from "hapi"; const server = new Server({ port: 8000, }); -const handler = (request: Request, h: ResponseToolkit) => { +const handler: Lifecycle.Method = (request, h) => { return h.context.message; // Or h.context.message }; const plugin: Plugin = { name: 'example', - register: async (server: Server, options: ServerRegisterOptions) => { + register: async (server, options) => { const bind = { message: 'hello' }; diff --git a/types/hapi/test/server/server-decorations.ts b/types/hapi/test/server/server-decorations.ts index 8ee7dfaaa3..c0ab94cc0e 100644 --- a/types/hapi/test/server/server-decorations.ts +++ b/types/hapi/test/server/server-decorations.ts @@ -1,15 +1,109 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options -import { ResponseToolkit, Server } from "hapi"; +import { Request, ResponseToolkit, Server } from "hapi"; + +declare module 'hapi' { + interface HandlerDecorations { + test?: { + test: number; + }; + } +} + +// Test basic types. const server = new Server({ port: 8000, }); -const success = (h: ResponseToolkit) => { - return h.response({ status: 'ok' }); -}; - server.start(); -server.decorate('toolkit', 'success', success); +server.decorate('toolkit', 'success', function() { + return this.response({ status: 'ok' }); +}); +server.decorate('handler', 'test', (route, options) => (req, h) => 123); +server.route({ + method: 'GET', + path: '/', + handler: { + test: { + test: 123, + }, + asd: 1, + } +}); console.log(server.decorations.toolkit); + +// Test decorators with additional arguments + +declare module 'hapi' { + interface Server { + withParams(x: number, y: string): string; + } + + interface ResponseToolkit { + withParams(x: number, y: string): string; + } +} + +function decorateServerWithParams(this: Server, x: number, y: string) { + return `${x} ${y}`; +} + +server.decorate('server', 'withParams', decorateServerWithParams); +server.withParams(1, "one"); + +function decorateToolkitWithParams(this: ResponseToolkit, x: number, y: string) { + return `${x} ${y}`; +} + +server.decorate('toolkit', 'withParams', decorateToolkitWithParams); + +server.route({ + method: 'GET', + path: '/toolkitWithParams', + handler: (r, h) => { + return h.withParams(1, "one"); + } +}); + +// Test request + apply option types + +declare module 'hapi' { + interface Request { + withApply(x: string, y: number): string; + } +} + +function decorateRequestWithApply(request: Request) { + return (x: string, y: number) => { + return `${x} ${y}`; + }; +} + +server.decorate('request', 'withApply', decorateRequestWithApply, {apply: true}); + +server.route({ + method: 'GET', + path: '/requestWithApply', + handler: (r, h) => { + return r.withApply("one", 1); + } +}); + +// Test extend option type + +declare module 'hapi' { + interface Server { + withExtend(x: string, y: number): string; + } +} + +const decorateServerWithExtend = (existing: () => void) => { + return (x: string, y: number) => { + existing(); + return `${x} ${y}`; + }; +}; + +server.decorate('server', 'withExtend', decorateServerWithExtend, {extend: true}); +server.withExtend("one", 1); diff --git a/types/hapi/test/server/server-events-once.ts b/types/hapi/test/server/server-events-once.ts index 06261e8aae..a4903ee6dc 100644 --- a/types/hapi/test/server/server-events-once.ts +++ b/types/hapi/test/server/server-events-once.ts @@ -4,19 +4,26 @@ import { Request, ResponseToolkit, Server, ServerRoute } from "hapi"; const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return 'oks: ' + request.path; } }; +declare module 'hapi' { + interface ServerEvents { + once(event: 'test1', listener: (update: string) => void): this; + once(event: 'test2', listener: (...updates: string[]) => void): this; + } +} + const server = new Server({ port: 8000, }); server.route(serverRoute); server.event('test1'); server.event('test2'); -server.events.once('test1', (update: any) => { console.log(update); }); -server.events.once('test2', (...args: any[]) => { console.log(args); }); +server.events.once('test1', update => { console.log(update); }); +server.events.once('test2', (...args) => { console.log(args); }); server.events.emit('test1', 'hello-1'); server.events.emit('test2', 'hello-2'); // Ignored diff --git a/types/hapi/test/server/server-events.ts b/types/hapi/test/server/server-events.ts index d17af569ae..2334915f05 100644 --- a/types/hapi/test/server/server-events.ts +++ b/types/hapi/test/server/server-events.ts @@ -1,9 +1,22 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents -import { Server } from "hapi"; +import { Server, ServerEvents } from "hapi"; +import Podium = require('podium'); +import 'hapi/definitions/server/server'; + +declare module 'hapi' { + interface ServerEvents { + on(event: 'test', listener: (update: string) => void): this; + } +} const server = new Server({ port: 8000, }); + +server.events.on('route', route => { + console.log(route.path, route.method); +}); + server.event('test'); server.events.on('test', (update: any) => console.log(update)); server.events.emit('test', 'hello'); diff --git a/types/hapi/test/server/server-expose.ts b/types/hapi/test/server/server-expose.ts index 2f1424b2ba..c1a698b6c7 100644 --- a/types/hapi/test/server/server-expose.ts +++ b/types/hapi/test/server/server-expose.ts @@ -3,14 +3,14 @@ import { Plugin, Server, ServerRegisterOptions } from "hapi"; const plugin1: Plugin = { name: 'example1', - register: async (server: Server, options: ServerRegisterOptions) => { + async register(server: Server, options: ServerRegisterOptions) { server.expose('util', () => console.log('something')); } }; const plugin2: Plugin = { name: 'example2', - register: async (server: Server, options: ServerRegisterOptions) => { + async register(server: Server, options: ServerRegisterOptions) { server.expose('util', () => console.log('something')); } }; diff --git a/types/hapi/test/server/server-inject.ts b/types/hapi/test/server/server-inject.ts index 477a3b2ec4..5c7942c16a 100644 --- a/types/hapi/test/server/server-inject.ts +++ b/types/hapi/test/server/server-inject.ts @@ -8,7 +8,7 @@ const server = new Server({ const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return 'Success!'; } }; diff --git a/types/hapi/test/server/server-lookup.ts b/types/hapi/test/server/server-lookup.ts index 651ba0cd8b..2bbaf5713b 100644 --- a/types/hapi/test/server/server-lookup.ts +++ b/types/hapi/test/server/server-lookup.ts @@ -8,7 +8,7 @@ const server = new Server({ server.route({ path: '/', method: 'GET', - config: { + options: { id: 'root', handler: () => 'ok' } diff --git a/types/hapi/test/server/server-match.ts b/types/hapi/test/server/server-match.ts index 27f59991b5..5fc8605ad4 100644 --- a/types/hapi/test/server/server-match.ts +++ b/types/hapi/test/server/server-match.ts @@ -8,7 +8,7 @@ const server = new Server({ server.route({ path: '/', method: 'GET', - config: { + options: { id: 'root', handler: () => 'ok' } diff --git a/types/hapi/test/server/server-path.ts b/types/hapi/test/server/server-path.ts index 36f346cb10..8a2ebf85dc 100644 --- a/types/hapi/test/server/server-path.ts +++ b/types/hapi/test/server/server-path.ts @@ -5,6 +5,13 @@ const server = new Server({ port: 8000, }); +// Definition for INERT +declare module 'hapi' { + interface HandlerDecorations { + file?: string; + } +} + const serverRouteOption: ServerRoute = { path: '/file', method: 'GET', diff --git a/types/hapi/test/server/server-state.ts b/types/hapi/test/server/server-state.ts index 9c51ee4748..97cf5997f0 100644 --- a/types/hapi/test/server/server-state.ts +++ b/types/hapi/test/server/server-state.ts @@ -8,7 +8,7 @@ const options: ServerOptions = { const serverRoute: ServerRoute = { path: '/say-hello', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return h.response('Hello').state('data', { firstVisit: false }); } }; diff --git a/types/hapi/test/server/server-table.ts b/types/hapi/test/server/server-table.ts index 02f83e90fd..9237a2be28 100644 --- a/types/hapi/test/server/server-table.ts +++ b/types/hapi/test/server/server-table.ts @@ -11,7 +11,7 @@ server.app!.key = 'value2'; server.route({ path: '/', method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { + handler(request, h) { return h.response("Hello World"); } }); diff --git a/types/hapi/tsconfig.json b/types/hapi/tsconfig.json index 54ac999c95..f8db3fc828 100644 --- a/types/hapi/tsconfig.json +++ b/types/hapi/tsconfig.json @@ -36,6 +36,7 @@ "test/route/adding-routes.ts", "test/route/config.ts", "test/route/handler.ts", + "test/route/ext.ts", "test/route/route-options.ts", "test/route/route-options-pre.ts", "test/route/validation.ts", @@ -71,4 +72,4 @@ "test/server/server-table.ts", "test/server/server-version.ts" ] -} \ No newline at end of file +} diff --git a/types/hapi/v16/test/response/error-representation.ts b/types/hapi/v16/test/response/error-representation.ts index 7eacfdfaf3..88c170eae1 100644 --- a/types/hapi/v16/test/response/error-representation.ts +++ b/types/hapi/v16/test/response/error-representation.ts @@ -2,15 +2,7 @@ // From https://hapijs.com/api/16.1.1#error-transformation import * as Hapi from '../../'; -import Vision from '../../../../vision'; const server = new Hapi.Server(); -server.register(Vision, {}, (err) => { - server.views({ - engines: { - html: require('../../../../handlebars') - } - }); -}); server.connection({ port: 80 }); const preResponse: Hapi.ServerExtRequestHandler = function (request, reply) { @@ -26,8 +18,6 @@ const preResponse: Hapi.ServerExtRequestHandler = function (request, reply) { const ctx = { message: (error.output!.statusCode === 404 ? 'page not found' : 'something went wrong') }; - - return reply.view('error', ctx); }; server.ext('onPreResponse', preResponse); diff --git a/types/hapi/v16/tsconfig.json b/types/hapi/v16/tsconfig.json index 12b95c134d..d3d30f97dc 100644 --- a/types/hapi/v16/tsconfig.json +++ b/types/hapi/v16/tsconfig.json @@ -102,4 +102,4 @@ "test/server/table.ts", "test/server/version.ts" ] -} \ No newline at end of file +} diff --git a/types/nes/index.d.ts b/types/nes/index.d.ts index 27b9d84dd1..7c48cb84b0 100644 --- a/types/nes/index.d.ts +++ b/types/nes/index.d.ts @@ -26,7 +26,7 @@ import { Plugin } from 'hapi'; import NesClient = require('nes/client'); -declare module 'hapi/definitions/server/server' { +declare module 'hapi' { interface Server { broadcast(message: any, options?: nes.ServerBroadcastOptions): void; subscription(path: string, options?: nes.ServerSubscriptionOptions): void; @@ -35,7 +35,7 @@ declare module 'hapi/definitions/server/server' { } } -declare module 'hapi/definitions/request/request' { +declare module 'hapi' { interface Request { socket: nes.Socket; } diff --git a/types/nes/test/nes-tests.ts b/types/nes/test/nes-tests.ts index b5557adfb9..0226a08070 100644 --- a/types/nes/test/nes-tests.ts +++ b/types/nes/test/nes-tests.ts @@ -11,10 +11,8 @@ server.register(Nes).then(() => { wsServer.route({ method: 'GET', path: '/test', - config: { - handler: (request: Request, h: ResponseToolkit) => { - return {test: 'passes ' + request.socket.id}; - } + handler: (request: Request, h: ResponseToolkit) => { + return {test: 'passes ' + request.socket.id}; } }); wsServer.start().then(() => { diff --git a/types/nes/test/route-authentication-server.ts b/types/nes/test/route-authentication-server.ts index 6aab8cf53e..becba06557 100644 --- a/types/nes/test/route-authentication-server.ts +++ b/types/nes/test/route-authentication-server.ts @@ -7,7 +7,7 @@ import Nes = require('nes'); const server = new Server(); -declare module 'hapi/definitions/request/request-auth' { +declare module 'hapi' { interface AuthCredentials { id: string; name: string; @@ -54,7 +54,7 @@ server.register([Basic, Nes]).then(() => { server.route({ method: 'GET', path: '/h', - config: { + options: { id: 'hello', handler: function (request: Request, h: ResponseToolkit) { diff --git a/types/nes/test/route-invocation-server.ts b/types/nes/test/route-invocation-server.ts index eb0ec4bf87..d422a897f7 100644 --- a/types/nes/test/route-invocation-server.ts +++ b/types/nes/test/route-invocation-server.ts @@ -10,7 +10,7 @@ server.register(Nes).then(() => { server.route({ method: 'GET', path: '/h', - config: { + options: { id: 'hello', handler: (request: Request, h: ResponseToolkit) => { diff --git a/types/vision/index.d.ts b/types/vision/index.d.ts index 012bc36d48..757d2a5383 100644 --- a/types/vision/index.d.ts +++ b/types/vision/index.d.ts @@ -13,11 +13,7 @@ import { } from 'hapi'; declare namespace vision { - /** - * Options for initialising server views manager - * @see {@link https://github.com/hapijs/vision/blob/master/API.md#serverviewsoptions} - */ - interface ServerViewsConfiguration extends ServerViewsAdditionalOptions { + interface EnginesConfiguration { /** * Required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates. * Alternatively, the extension can be mapped to an object @@ -30,14 +26,14 @@ declare namespace vision { /** * Includes `module` and any of the views options listed below (@see ServerViewsAdditionalOptions) (except defaultExtension) to override the defaults for a specific engine. */ - interface ServerViewsEnginesOptions extends ServerViewsAdditionalOptions { + interface ServerViewsEnginesOptions extends ServerViewsConfiguration { /** * The npm module used for rendering the templates. The module object must contain the compile() function * @see {@link https://github.com/hapijs/vision/blob/master/API.md#serverviewsoptions} > options > engines > module */ module: NpmModule; } - interface ServerViewsAdditionalOptions extends ViewHandlerOrReplyOptions { + interface ServerViewsConfiguration extends ViewHandlerOrReplyOptions, EnginesConfiguration { /** * The root file path, or array of file paths, where partials are located. * Partials are small segments of template code that can be nested and reused throughout other templates. @@ -171,7 +167,7 @@ declare namespace vision { * @param context - optional object used by the template to render context-specific result. Defaults to no context ({}). * @param options - optional object used to override the views manager configuration. */ - type RenderMethod = (template: string, context?: any, options?: ServerViewsAdditionalOptions) => Promise; + type RenderMethod = (template: string, context?: any, options?: ServerViewsConfiguration) => Promise; /** * View Manager @@ -195,11 +191,11 @@ declare namespace vision { } } -declare const vision: Plugin; +declare const vision: Plugin; export = vision; -declare module 'hapi/definitions/server/server' { +declare module 'hapi' { interface Server { /** * Initializes the server views manager @@ -214,7 +210,7 @@ declare module 'hapi/definitions/server/server' { } } -declare module 'hapi/definitions/request/request' { +declare module 'hapi' { interface Request { /** * request.render() works the same way as server.render() but is for use inside of request handlers. @@ -229,7 +225,7 @@ declare module 'hapi/definitions/request/request' { } } -declare module 'hapi/definitions/response/response-toolkit' { +declare module 'hapi' { interface ResponseToolkit { /** * Concludes the handler activity by returning control over to the router with a templatized view response @@ -245,7 +241,7 @@ declare module 'hapi/definitions/response/response-toolkit' { } } -declare module 'hapi/definitions/route/route-options' { +declare module 'hapi' { interface RouteOptions { /** * The view handler can be used with routes registered in the same realm as the view manager. diff --git a/types/yar/index.d.ts b/types/yar/index.d.ts index 678d3e49a9..8f78544c9d 100644 --- a/types/yar/index.d.ts +++ b/types/yar/index.d.ts @@ -161,7 +161,7 @@ declare namespace yar { declare const yar: Plugin; export = yar; -declare module 'hapi/definitions/request/request' { +declare module 'hapi' { interface Request { yar: yar.Yar; } From b11c5e098a5004225df32cf57c9300206c911b71 Mon Sep 17 00:00:00 2001 From: Lucas Riondel Date: Thu, 22 Feb 2018 17:26:50 +0100 Subject: [PATCH 063/128] added base64topdf definition file --- types/base64topdf/base64topdf-tests.ts | 8 ++++++++ types/base64topdf/index.d.ts | 13 +++++++++++++ types/base64topdf/tsconfig.json | 23 +++++++++++++++++++++++ types/base64topdf/tslint.json | 1 + 4 files changed, 45 insertions(+) create mode 100644 types/base64topdf/base64topdf-tests.ts create mode 100644 types/base64topdf/index.d.ts create mode 100644 types/base64topdf/tsconfig.json create mode 100644 types/base64topdf/tslint.json diff --git a/types/base64topdf/base64topdf-tests.ts b/types/base64topdf/base64topdf-tests.ts new file mode 100644 index 0000000000..109ec5fbff --- /dev/null +++ b/types/base64topdf/base64topdf-tests.ts @@ -0,0 +1,8 @@ +import * as base64topdf from 'base64topdf'; + +base64topdf.base64Encode('index.ts'); // $ExpectType void +base64topdf.base64Decode('decodethis', 'test.b64'); // $ExpectType void +base64topdf.rtfToText('rtf'); // $ExpectType string +base64topdf.textToRtf('text'); // $ExpectType string +base64topdf.strToBase64('str'); // $ExpectType string +base64topdf.base64ToStr('base64'); // $ExpectType string diff --git a/types/base64topdf/index.d.ts b/types/base64topdf/index.d.ts new file mode 100644 index 0000000000..97f9af7077 --- /dev/null +++ b/types/base64topdf/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for base64topdf 1.1 +// Project: https://github.com/rpsankar001 +// Definitions by: Lucas Riondel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace base64topdf; + +export function base64Encode(file: string): void; +export function base64Decode(base64str: string, file: string): void; +export function rtfToText(rtfStr: string): string; +export function textToRtf(textStr: string): string; +export function strToBase64(str: string): string; +export function base64ToStr(base64Str: string): string; diff --git a/types/base64topdf/tsconfig.json b/types/base64topdf/tsconfig.json new file mode 100644 index 0000000000..29fb459eb9 --- /dev/null +++ b/types/base64topdf/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "base64topdf-tests.ts" + ] +} diff --git a/types/base64topdf/tslint.json b/types/base64topdf/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/base64topdf/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From aec14ac7739e31d4ea329c52b28695646afedb7f Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 22 Feb 2018 09:26:54 -0800 Subject: [PATCH 064/128] three: Remove unnecessary dat.gui dependency (#23857) --- types/three/test/references.ts | 1 - .../test/webgl/webgl_animation_skinning_morph.ts | 14 ++------------ 2 files changed, 2 insertions(+), 13 deletions(-) diff --git a/types/three/test/references.ts b/types/three/test/references.ts index c5d3c66909..e2068d68a5 100644 --- a/types/three/test/references.ts +++ b/types/three/test/references.ts @@ -1,5 +1,4 @@ // References used by tests -/// /// /// diff --git a/types/three/test/webgl/webgl_animation_skinning_morph.ts b/types/three/test/webgl/webgl_animation_skinning_morph.ts index fcea4bba08..835d7a6ea5 100644 --- a/types/three/test/webgl/webgl_animation_skinning_morph.ts +++ b/types/three/test/webgl/webgl_animation_skinning_morph.ts @@ -186,18 +186,8 @@ } function initGUI() { - - var API = { - 'show model' : true, - 'show skeleton' : false - }; - - var gui = new dat.GUI(); - - gui.add( API, 'show model' ).onChange( function() { mesh.visible = API[ 'show model' ]; } ); - - gui.add( API, 'show skeleton' ).onChange( function() { helper.visible = API[ 'show skeleton' ]; } ); - + mesh.visible = true; + helper.visible = true; } function onDocumentMouseMove( event: MouseEvent ) { From f2667f08626faa62fa1a8b936a9531183e819768 Mon Sep 17 00:00:00 2001 From: Maurus Cuelenaere Date: Thu, 22 Feb 2018 18:35:20 +0100 Subject: [PATCH 065/128] Add a default export to big.js (#23769) * Add a default export to big.js As can be seen on https://github.com/MikeMcl/big.js/blob/master/big.js#L925, big.js exposes a default export. Expose this in the Typescript bindings as well. * Add default import test for big.js * Fix lint errors --- types/big.js/index.d.ts | 1 + types/big.js/test/big.js-import-default-tests.ts | 12 ++++++++++++ types/big.js/tsconfig.json | 3 ++- 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 types/big.js/test/big.js-import-default-tests.ts diff --git a/types/big.js/index.d.ts b/types/big.js/index.d.ts index 37f51a54bd..405622f7ee 100644 --- a/types/big.js/index.d.ts +++ b/types/big.js/index.d.ts @@ -295,6 +295,7 @@ export const Big: BigConstructor; export type Big_ = Big; export type BigConstructor_ = BigConstructor; export type BigSource_ = BigSource; +export default Big; declare global { namespace BigJs { diff --git a/types/big.js/test/big.js-import-default-tests.ts b/types/big.js/test/big.js-import-default-tests.ts new file mode 100644 index 0000000000..52841986be --- /dev/null +++ b/types/big.js/test/big.js-import-default-tests.ts @@ -0,0 +1,12 @@ +/* + + This file contains tests for the named export definitions of big.js. + Import the default Big constructor from 'big.js' + +*/ + +import Big from 'big.js'; + +function constructorTests() { + const x = new Big(9); // '9' +} diff --git a/types/big.js/tsconfig.json b/types/big.js/tsconfig.json index 950e8b410f..20fae3a55f 100644 --- a/types/big.js/tsconfig.json +++ b/types/big.js/tsconfig.json @@ -19,6 +19,7 @@ "files": [ "index.d.ts", "test/big.js-module-tests.ts", - "test/big.js-global-tests.ts" + "test/big.js-global-tests.ts", + "test/big.js-import-default-tests.ts" ] } \ No newline at end of file From 9cf5c9bd633faf5e7f5d851e74f1a8e5659eca70 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 22 Feb 2018 14:37:30 -0500 Subject: [PATCH 066/128] Adds types for google.analytics 'require' and 'provide' calls. --- types/google.analytics/google.analytics-tests.ts | 6 ++++++ types/google.analytics/index.d.ts | 2 ++ 2 files changed, 8 insertions(+) diff --git a/types/google.analytics/google.analytics-tests.ts b/types/google.analytics/google.analytics-tests.ts index 5256f636c7..a130e2c600 100644 --- a/types/google.analytics/google.analytics-tests.ts +++ b/types/google.analytics/google.analytics-tests.ts @@ -33,6 +33,12 @@ describe('UniversalAnalytics', () => { ga('send', 'timing', {timingCategory: 'category', timingVar: 'lookup', timingValue: 123, timingLabel: 'label'}); ga('trackerName.send', 'event', 'load'); + ga('require', 'somePlugin'); + ga('require', 'somePlugin', { some: 'options' }); + ga('provide', 'somePlugin', () => {}); + ga('provide', 'somePlugin', tracker => {}); + ga('provide', 'somePlugin', (tracker, options) => {}); + ga.create('UA-65432-1', 'auto'); ga.create('UA-65432-1', {some: 'config'}); ga.create('UA-65432-1', 'auto', {some: 'config'}); diff --git a/types/google.analytics/index.d.ts b/types/google.analytics/index.d.ts index b7d4a8a6f4..6d61962520 100644 --- a/types/google.analytics/index.d.ts +++ b/types/google.analytics/index.d.ts @@ -601,6 +601,8 @@ declare namespace UniversalAnalytics { }): void; (command: 'send', fieldsObject: FieldsObject): void; (command: string, hitType: HitType, ...fields: any[]): void; + (command: 'require', pluginName: string, pluginOptions?: Object): void; + (command: 'provide', pluginName: string, pluginConstructor: (tracker: Tracker, pluginOptions?: Object) => void): void; (command: 'create', trackingId: string, cookieDomain?: string, name?: string, fieldsObject?: FieldsObject): void; (command: 'remove'): void; From 3b84322b61a0133a422e16fa369c67f72396be8d Mon Sep 17 00:00:00 2001 From: segler-alex Date: Thu, 22 Feb 2018 20:42:48 +0100 Subject: [PATCH 067/128] amqp: added heartbeat to ConnectionOptions --- types/amqp/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/amqp/index.d.ts b/types/amqp/index.d.ts index ca39ce4404..4e2cd4e288 100644 --- a/types/amqp/index.d.ts +++ b/types/amqp/index.d.ts @@ -96,6 +96,7 @@ export interface ConnectionOptions { authMechanism?: string; vhost?: string; noDelay?: boolean; + heartbeat?: number; ssl?: { enabled: boolean; keyFile?: string; From 05143e9d80add9d9058b3d1bae7b69480e5d24df Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 22 Feb 2018 14:43:33 -0500 Subject: [PATCH 068/128] Corrects the ga('require'e', ...) plugin options type, since plugin options can actually have any type. --- types/google.analytics/google.analytics-tests.ts | 1 + types/google.analytics/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/types/google.analytics/google.analytics-tests.ts b/types/google.analytics/google.analytics-tests.ts index a130e2c600..63ca4e5ca4 100644 --- a/types/google.analytics/google.analytics-tests.ts +++ b/types/google.analytics/google.analytics-tests.ts @@ -34,6 +34,7 @@ describe('UniversalAnalytics', () => { ga('trackerName.send', 'event', 'load'); ga('require', 'somePlugin'); + ga('require', 'somePlugin', 'option'); ga('require', 'somePlugin', { some: 'options' }); ga('provide', 'somePlugin', () => {}); ga('provide', 'somePlugin', tracker => {}); diff --git a/types/google.analytics/index.d.ts b/types/google.analytics/index.d.ts index 6d61962520..b71fdef286 100644 --- a/types/google.analytics/index.d.ts +++ b/types/google.analytics/index.d.ts @@ -601,7 +601,7 @@ declare namespace UniversalAnalytics { }): void; (command: 'send', fieldsObject: FieldsObject): void; (command: string, hitType: HitType, ...fields: any[]): void; - (command: 'require', pluginName: string, pluginOptions?: Object): void; + (command: 'require', pluginName: string, pluginOptions?: any): void; (command: 'provide', pluginName: string, pluginConstructor: (tracker: Tracker, pluginOptions?: Object) => void): void; (command: 'create', trackingId: string, cookieDomain?: string, name?: string, fieldsObject?: FieldsObject): void; From ead8479b1c83efed59aa4ba636e28350b496c7e4 Mon Sep 17 00:00:00 2001 From: Flarna Date: Thu, 22 Feb 2018 22:41:22 +0100 Subject: [PATCH 069/128] Added calledWithNew() --- types/sinon/index.d.ts | 15 ++++++++------- types/sinon/sinon-tests.ts | 3 +++ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/types/sinon/index.d.ts b/types/sinon/index.d.ts index 9348f3a690..5d3288068d 100644 --- a/types/sinon/index.d.ts +++ b/types/sinon/index.d.ts @@ -353,19 +353,20 @@ declare namespace Sinon { calledThrice(spy: SinonSpy): void; callCount(spy: SinonSpy, count: number): void; callOrder(...spies: SinonSpy[]): void; - calledOn(spy: SinonSpy | SinonSpyCall, obj: any): void; + calledOn(spyOrSpyCall: SinonSpy | SinonSpyCall, obj: any): void; alwaysCalledOn(spy: SinonSpy, obj: any): void; - calledWith(spy: SinonSpy | SinonSpyCall, ...args: any[]): void; + calledWith(spyOrSpyCall: SinonSpy | SinonSpyCall, ...args: any[]): void; alwaysCalledWith(spy: SinonSpy, ...args: any[]): void; neverCalledWith(spy: SinonSpy, ...args: any[]): void; - calledWithExactly(spy: SinonSpy | SinonSpyCall, ...args: any[]): void; + calledWithExactly(spyOrSpyCall: SinonSpy | SinonSpyCall, ...args: any[]): void; alwaysCalledWithExactly(spy: SinonSpy, ...args: any[]): void; - calledWithMatch(spy: SinonSpy | SinonSpyCall, ...args: any[]): void; + calledWithMatch(spyOrSpyCall: SinonSpy | SinonSpyCall, ...args: any[]): void; alwaysCalledWithMatch(spy: SinonSpy, ...args: any[]): void; neverCalledWithMatch(spy: SinonSpy, ...args: any[]): void; - threw(spy: SinonSpy | SinonSpyCall): void; - threw(spy: SinonSpy | SinonSpyCall, exception: string): void; - threw(spy: SinonSpy | SinonSpyCall, exception: any): void; + calledWithNew(spyOrSpyCall: SinonSpy | SinonSpyCall): void; + threw(spyOrSpyCall: SinonSpy | SinonSpyCall): void; + threw(spyOrSpyCall: SinonSpy | SinonSpyCall, exception: string): void; + threw(spyOrSpyCall: SinonSpy | SinonSpyCall, exception: any): void; alwaysThrew(spy: SinonSpy): void; alwaysThrew(spy: SinonSpy, exception: string): void; alwaysThrew(spy: SinonSpy, exception: any): void; diff --git a/types/sinon/sinon-tests.ts b/types/sinon/sinon-tests.ts index 16ec014b21..6ce2254596 100644 --- a/types/sinon/sinon-tests.ts +++ b/types/sinon/sinon-tests.ts @@ -100,6 +100,9 @@ function testNine() { sinon.assert.calledOn(callback.secondCall, "this"); sinon.assert.threw(callback.thirdCall); sinon.assert.threw(callback.thirdCall, "Error"); + new (callback as any)(); + sinon.assert.calledWithNew(callback); + sinon.assert.calledWithNew(callback.getCall(4)); } function testAssert() { From ed8e6ff42de34d2d44b4d1af7fc206f750e754b4 Mon Sep 17 00:00:00 2001 From: Veit Lehmann Date: Thu, 22 Feb 2018 23:20:57 +0100 Subject: [PATCH 070/128] react-navigation: update for v1.1 --- types/react-navigation/index.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 2c3c384ac6..909d72d413 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-navigation 1.0 +// Type definitions for react-navigation 1.1 // Project: https://github.com/react-community/react-navigation // Definitions by: Huhuanming // mhcgrq @@ -11,6 +11,7 @@ // Tim Wang // Qibang Sun // Sergei Butko: +// Veit Lehmann: // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -278,6 +279,7 @@ export type NavigationStackScreenOptions = NavigationScreenOptions & { }; export interface NavigationStackRouterConfig { + headerTransitionPreset?: 'fade-in-place' | 'uikit'; initialRouteName?: string; initialRouteParams?: NavigationParams; paths?: NavigationPathsConfig; @@ -608,6 +610,8 @@ export interface TabViewConfig { // From navigators/TabNavigator.js export interface TabNavigatorConfig extends NavigationTabRouterConfig, TabViewConfig { + lazy?: boolean; + removeClippedSubviews?: boolean; initialLayout?: { height: number, width: number }; } From 060e346f624fbc533f0e2c4e54f7c23a7b46757c Mon Sep 17 00:00:00 2001 From: Ben Stevens Date: Fri, 23 Feb 2018 13:04:58 +0000 Subject: [PATCH 071/128] add types for jsontoxml --- types/jsontoxml/index.d.ts | 22 ++++++++++++++++++++++ types/jsontoxml/jsontoxml-tests.ts | 10 ++++++++++ types/jsontoxml/tsconfig.json | 24 ++++++++++++++++++++++++ types/jsontoxml/tslint.json | 1 + 4 files changed, 57 insertions(+) create mode 100644 types/jsontoxml/index.d.ts create mode 100644 types/jsontoxml/jsontoxml-tests.ts create mode 100644 types/jsontoxml/tsconfig.json create mode 100644 types/jsontoxml/tslint.json diff --git a/types/jsontoxml/index.d.ts b/types/jsontoxml/index.d.ts new file mode 100644 index 0000000000..f683050031 --- /dev/null +++ b/types/jsontoxml/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for jsontoxml 1.0 +// Project: https://github.com/soldair/node-jsontoxml +// Definitions by: benstevens48 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace jsontoxml { + function escape(str: string): string; + function cdata(str: string): string; + interface JsonToXmlOptions { + escape?: boolean; + xmlHeader?: boolean | {standalone?: boolean}; + docType?: string; + prettyPrint?: boolean; + indent?: string; + removeIllegalNameCharacters?: boolean; + html?: boolean; + } +} + +declare function jsontoxml(data: any, options?: jsontoxml.JsonToXmlOptions): string; + +export = jsontoxml; diff --git a/types/jsontoxml/jsontoxml-tests.ts b/types/jsontoxml/jsontoxml-tests.ts new file mode 100644 index 0000000000..98b9da5552 --- /dev/null +++ b/types/jsontoxml/jsontoxml-tests.ts @@ -0,0 +1,10 @@ +import jsontoxml = require('jsontoxml'); + +// $ExpectType string +jsontoxml({foo: 'bar'}, {escape: true, xmlHeader: true}); + +// $ExpectType string +jsontoxml.escape('&test'); + +// $ExpectType string +jsontoxml.cdata('test'); diff --git a/types/jsontoxml/tsconfig.json b/types/jsontoxml/tsconfig.json new file mode 100644 index 0000000000..b69f2e8fd3 --- /dev/null +++ b/types/jsontoxml/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "esModuleInterop": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jsontoxml-tests.ts" + ] +} diff --git a/types/jsontoxml/tslint.json b/types/jsontoxml/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jsontoxml/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 345f0b4e17533f97929c0bc8ca79d8961f3c728b Mon Sep 17 00:00:00 2001 From: azu Date: Sat, 24 Feb 2018 14:56:21 +0900 Subject: [PATCH 072/128] Add structured-source definitions --- types/structured-source/index.d.ts | 29 +++++++++++++++++++ .../structured-source-tests.ts | 15 ++++++++++ types/structured-source/tsconfig.json | 23 +++++++++++++++ types/structured-source/tslint.json | 1 + 4 files changed, 68 insertions(+) create mode 100644 types/structured-source/index.d.ts create mode 100644 types/structured-source/structured-source-tests.ts create mode 100644 types/structured-source/tsconfig.json create mode 100644 types/structured-source/tslint.json diff --git a/types/structured-source/index.d.ts b/types/structured-source/index.d.ts new file mode 100644 index 0000000000..ce7325cf9d --- /dev/null +++ b/types/structured-source/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for structured-source 3.0 +// Project: https://github.com/Constellation/structured-source +// Definitions by: azu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace StructuredSource { + interface SourcePosition { + // Line number starts with 1. + line: number; + // Column number starts with 0. + column: number; + } + interface SourceLocation { + start: SourcePosition; + end: SourcePosition; + } +} + +declare class StructuredSource { + /** + * @param source - source code text. + */ + constructor(source: string); + locationToRange(loc: StructuredSource.SourceLocation): [number, number]; + rangeToLocation(range: [number, number]): StructuredSource.SourceLocation; + positionToIndex(pos: StructuredSource.SourcePosition): number; + indexToPosition(index: number): StructuredSource.SourcePosition; +} +export = StructuredSource; diff --git a/types/structured-source/structured-source-tests.ts b/types/structured-source/structured-source-tests.ts new file mode 100644 index 0000000000..498cd7ddf2 --- /dev/null +++ b/types/structured-source/structured-source-tests.ts @@ -0,0 +1,15 @@ +import StructuredSource = require('structured-source'); + +const src = new StructuredSource('aaa\u2028aaaa\u2029aaaaa\n'); + +// positionToIndex({ line: number, column: number) -> number +src.positionToIndex({ line: 1, column: 2 }); +// indexToPosition(number) -> { line: number, column: number } +src.indexToPosition(2); +// rangeToLocation([ number, number ]) -> { start: { line: number, column: number}, end: { line: number, column: number } } +src.rangeToLocation([0, 2]); +// locationToRange({ start: { line: number, column: number}, end: { line: number, column: number } }) -> [ number, number ] +src.locationToRange({ + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } +}); diff --git a/types/structured-source/tsconfig.json b/types/structured-source/tsconfig.json new file mode 100644 index 0000000000..f0d949503e --- /dev/null +++ b/types/structured-source/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "structured-source-tests.ts" + ] +} diff --git a/types/structured-source/tslint.json b/types/structured-source/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/structured-source/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From dfde552d045f45150798df04b1461cac535b04d0 Mon Sep 17 00:00:00 2001 From: Ryo Kawaguchi Date: Sat, 24 Feb 2018 17:06:08 +0900 Subject: [PATCH 073/128] Re-enble dt-header lint rule. --- types/material-ui/index.d.ts | 7 +++---- types/material-ui/material-ui-tests.tsx | 2 +- types/material-ui/tsconfig.json | 2 +- types/material-ui/tslint.json | 8 ++------ 4 files changed, 7 insertions(+), 12 deletions(-) diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 85a8f46f65..8bea28fd5f 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for material-ui v0.20.1 +// Type definitions for material-ui 0.21 // Project: https://github.com/callemall/material-ui // Definitions by: Nathan Brown // Igor Beagorudsky @@ -519,7 +519,7 @@ declare namespace __MaterialUI { >(component: TComponent) => TComponent; export interface MuiThemeProviderProps { - muiTheme?: Styles.MuiTheme; + muiTheme?: MuiTheme; } export class MuiThemeProvider extends React.Component { } @@ -1864,8 +1864,7 @@ declare namespace __MaterialUI { value?: any; disabled?: boolean; } - export class Tab extends React.Component< - TabProps, {}> { + export class Tab extends React.Component { } } diff --git a/types/material-ui/material-ui-tests.tsx b/types/material-ui/material-ui-tests.tsx index 51b22c936c..c490a16265 100644 --- a/types/material-ui/material-ui-tests.tsx +++ b/types/material-ui/material-ui-tests.tsx @@ -4745,7 +4745,7 @@ class DropDownMenuOpenImmediateExample extends Component<{}, {value?: number}> { } } -const DropDownMenuAnchorExample: React.SFC<{}> = () => ( +const DropDownMenuAnchorExample: React.SFC = () => ( Date: Sun, 25 Feb 2018 14:27:56 +0900 Subject: [PATCH 074/128] Add type assertion --- types/structured-source/structured-source-tests.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/structured-source/structured-source-tests.ts b/types/structured-source/structured-source-tests.ts index 498cd7ddf2..cda6e99af2 100644 --- a/types/structured-source/structured-source-tests.ts +++ b/types/structured-source/structured-source-tests.ts @@ -2,13 +2,13 @@ import StructuredSource = require('structured-source'); const src = new StructuredSource('aaa\u2028aaaa\u2029aaaaa\n'); -// positionToIndex({ line: number, column: number) -> number +// $ExpectType: number src.positionToIndex({ line: 1, column: 2 }); -// indexToPosition(number) -> { line: number, column: number } +// $ExpectType: { line: number, column: number } src.indexToPosition(2); -// rangeToLocation([ number, number ]) -> { start: { line: number, column: number}, end: { line: number, column: number } } +// $ExpectType: { start: { line: number, column: number}, end: { line: number, column: number } } src.rangeToLocation([0, 2]); -// locationToRange({ start: { line: number, column: number}, end: { line: number, column: number } }) -> [ number, number ] +// $ExpectType: [ number, number ] src.locationToRange({ start: { line: 1, column: 0 }, end: { line: 1, column: 2 } From cad74e1634acbaef129eb42664876889799321a6 Mon Sep 17 00:00:00 2001 From: Martin Tracey Date: Sun, 25 Feb 2018 19:39:30 +0000 Subject: [PATCH 075/128] canvas-confetti: created type definition for v0.0.2 --- .../canvas-confetti/canvas-confetti-tests.ts | 45 ++++++++++ types/canvas-confetti/index.d.ts | 86 +++++++++++++++++++ types/canvas-confetti/tsconfig.json | 23 +++++ types/canvas-confetti/tslint.json | 1 + 4 files changed, 155 insertions(+) create mode 100644 types/canvas-confetti/canvas-confetti-tests.ts create mode 100644 types/canvas-confetti/index.d.ts create mode 100644 types/canvas-confetti/tsconfig.json create mode 100644 types/canvas-confetti/tslint.json diff --git a/types/canvas-confetti/canvas-confetti-tests.ts b/types/canvas-confetti/canvas-confetti-tests.ts new file mode 100644 index 0000000000..d29e57fbdb --- /dev/null +++ b/types/canvas-confetti/canvas-confetti-tests.ts @@ -0,0 +1,45 @@ +import confetti = require("canvas-confetti"); + +confetti.Promise = null; + +confetti(); + +confetti({ + particleCount: 150 +}); + +confetti({ + spread: 180 +}); + +confetti({ + particleCount: 100, + startVelocity: 30, + spread: 360, + origin: { + x: Math.random(), + // since they fall down, start a bit higher than random + y: Math.random() - 0.2 + } +}); + +confetti({ + particleCount: 100, + spread: 70, + origin: { + y: 0.6 + } +}); + +function r(min: number, max: number) { + return Math.random() * (max - min) + min; +} + +confetti({ + angle: r(55, 125), + spread: r(50, 70), + particleCount: r(50, 100), + origin: { + y: 0.6 + } +}); diff --git a/types/canvas-confetti/index.d.ts b/types/canvas-confetti/index.d.ts new file mode 100644 index 0000000000..3dddc6d750 --- /dev/null +++ b/types/canvas-confetti/index.d.ts @@ -0,0 +1,86 @@ +// Type definitions for canvas-confetti 0.0 +// Project: https://github.com/catdad/canvas-confetti#readme +// Definitions by: Martin Tracey +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * `confetti` takes a single optional object. When `window.Promise` is available, it will return a Promise to let you know when it is done. When promises are not available (like in IE), it will return + * `null`. You can polyfill promises using any of the popular polyfills. You can also provide a custom promise implementation to `confetti` through: + * + * `const MyPromise = require('some-promise-lib'); + * const confetti = require('canvas-confetti'); + * confetti.Promise = MyPromise;` + * + * If you call `confetti` multiple times before it is done, it + * will return the same promise every time. Internally, the same canvas element will be reused, continuing the existing animation with the new confetti added. The promise returned by each call to + * `confetti` will resolve once all animations are done. + * + */ +declare function confetti(options?: confetti.Options): Promise | null; + +declare namespace confetti { + /** + * You can polyfill promises using any of the popular polyfills. You can also provide a promise implementation to `confetti` through this property. + */ + let Promise: any; + + interface Options { + /** + * The number of confetti to launch. More is always fun... but be cool, there's a lot of math involved. + * @default 50 + */ + particleCount?: number; + /** + * The angle in which to launch the confetti, in degrees. 90 is straight up. + * @default 90 + */ + angle?: number; + /** + * How far off center the confetti can go, in degrees. 45 means the confetti will launch at the defined angle plus or minus 22.5 degrees. + * @default 45 + */ + spread?: number; + /** + * How fast the confetti will start going, in pixels. + * @default 45 + */ + startVelocity?: number; + /** + * How quickly the confetti will lose speed. Keep this number between 0 and 1, otherwise the confetti will gain speed. Better yet, just never change it. + * @default 0.9 + */ + decay?: number; + /** + * How many times the confetti will move. This is abstract... but play with it if the confetti disappear too quickly for you. + * @default 200 + */ + ticks?: number; + /** + * Where to start firing confetti from. Feel free to launch off-screen if you'd like. + */ + origin?: Origin; + /** + * An array of color strings, in the HEX format... you know, like #bada55. + */ + colors?: string[]; + /** + * The confetti should be on top, after all. But if you have a crazy high page, you can set it even higher. + * @default 100 + */ + zIndex?: number; + } + interface Origin { + /** + * The x position on the page, with 0 being the left edge and 1 being the right edge. + * @default 0.5 + */ + x?: number; + /** + * The y position on the page, with 0 being the left edge and 1 being the right edge. + * @default 0.5 + */ + y?: number; + } +} + +export = confetti; diff --git a/types/canvas-confetti/tsconfig.json b/types/canvas-confetti/tsconfig.json new file mode 100644 index 0000000000..33c159b3e3 --- /dev/null +++ b/types/canvas-confetti/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "canvas-confetti-tests.ts" + ] +} diff --git a/types/canvas-confetti/tslint.json b/types/canvas-confetti/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/canvas-confetti/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 32071c40b8e3494554aacf7181a563d4fb85977c Mon Sep 17 00:00:00 2001 From: Tim Wang Date: Mon, 26 Feb 2018 13:54:38 +0800 Subject: [PATCH 076/128] Refactor react-navigation types based on 1.2.0 flow type --- types/react-navigation/index.d.ts | 244 +++++++++++++----- .../react-navigation-tests.tsx | 36 ++- 2 files changed, 201 insertions(+), 79 deletions(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index edf5cbc915..53349d4be8 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -1,5 +1,5 @@ -// Type definitions for react-navigation 1.0 -// Project: https://github.com/react-community/react-navigation +// Type definitions for react-navigation 1.2 +// Project: https://github.com/react-navigation/react-navigation // Definitions by: Huhuanming // mhcgrq // fangpenlin @@ -10,16 +10,18 @@ // charlesfamu // Tim Wang // Qibang Sun +// Sergei Butko: +// Veit Lehmann: // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 /** * BEGIN FLOW TYPEDEFINITION.JS PORT - * Reference: https://github.com/react-community/react-navigation/tree/52a2846e77119148320bcea83b8982a8bc6acce3 + * Reference: https://github.com/react-navigation/react-navigation/tree/a37473c5e4833f48796ee6c7c9cb4a8ac49d9c06 * * NOTE: Please update the commit/link above when updating to a new Flow - * TypeDefinition.js reference, so we can conveniently just look at diffs on - * TypeDefinition.js between this latest reference point and the one you are + * react-navigation/flow/react-navigation.js reference, so we can conveniently just look at diffs on + * react-navigation/flow/react-navigation.js between this latest reference point and the one you are * using when making new updates. */ @@ -71,9 +73,9 @@ export interface NavigationState { routes: any[]; } -export type NavigationRoute = NavigationLeafRoute | NavigationStateRoute; +export type NavigationRoute = NavigationLeafRoute | NavigationStateRoute; -export interface NavigationLeafRoute { +export interface NavigationLeafRoute { /** * React's key used by some navigators. No need to specify these manually, * they will be defined by the router. @@ -92,16 +94,13 @@ export interface NavigationLeafRoute { * Params passed to this route when navigating to it, * e.g. `{ car_id: 123 }` in a route that displays a car. */ - params: Params; + params?: NavigationParams; } -export interface NavigationStateRoute extends NavigationLeafRoute { - index: number; - routes: Array>; -} +export type NavigationStateRoute = NavigationLeafRoute & NavigationState; -export type NavigationScreenOptionsGetter = ( - navigation: NavigationScreenProp, Action>, +export type NavigationScreenOptionsGetter = ( + navigation: NavigationScreenProp, screenProps?: { [key: string]: any } ) => Options; @@ -141,20 +140,20 @@ export interface NavigationRouter { * * {routeName: 'Foo', key: '123'} */ - getScreenOptions: NavigationScreenOptionsGetter; + getScreenOptions: NavigationScreenOptionsGetter; } export type NavigationScreenOption = T | (( - navigation: NavigationScreenProp, NavigationAction>, + navigation: NavigationScreenProp, config: T ) => T); export interface NavigationScreenDetails { options: T; - state: NavigationRoute; - navigation: NavigationScreenProp, NavigationAction>; + state: NavigationRoute; + navigation: NavigationScreenProp; } export interface NavigationScreenOptions { @@ -162,7 +161,7 @@ export interface NavigationScreenOptions { } export interface NavigationScreenConfigProps { - navigation: NavigationScreenProp, NavigationAction>; + navigation: NavigationScreenProp; screenProps: { [key: string]: any }; } @@ -170,10 +169,7 @@ export type NavigationScreenConfig = Options | (NavigationScreenConfigProps & ((navigationOptionsContainer: { - navigationOptions: NavigationScreenProp< - NavigationRoute, - NavigationAction - >, + navigationOptions: NavigationScreenProp, }) => Options)); export type NavigationComponent = @@ -262,6 +258,7 @@ export interface NavigationStackViewConfig { export type NavigationStackScreenOptions = NavigationScreenOptions & { header?: (React.ReactElement | ((headerProps: HeaderProps) => React.ReactElement)) | null; + headerTransparent?: boolean; headerTitle?: string | React.ReactElement; headerTitleStyle?: StyleProp; headerTintColor?: string; @@ -272,10 +269,13 @@ export type NavigationStackScreenOptions = NavigationScreenOptions & { headerPressColorAndroid?: string; headerRight?: React.ReactElement; headerStyle?: StyleProp; + headerBackground?: React.ReactNode | React.ComponentType; gesturesEnabled?: boolean; + gestureResponseDistance?: { vertical?: number; horizontal?: number }; }; export interface NavigationStackRouterConfig { + headerTransitionPreset?: 'fade-in-place' | 'uikit'; initialRouteName?: string; initialRouteParams?: NavigationParams; paths?: NavigationPathsConfig; @@ -299,18 +299,16 @@ export type NavigationAction = | NavigationStackAction | NavigationTabAction; -export type NavigationRouteConfig = T & { +export type NavigationRouteConfig = NavigationComponent | ({ navigationOptions?: NavigationScreenConfig, path?: string, -}; +} & NavigationScreenRouteConfig); -export type NavigationScreenRouteConfig = - { - screen: NavigationComponent, - } - | { - getScreen: () => NavigationComponent, - }; +export type NavigationScreenRouteConfig = NavigationComponent | { + screen: NavigationComponent, +} | { + getScreen: () => NavigationComponent, +}; export interface NavigationPathsConfig { [routeName: string]: string; @@ -325,7 +323,12 @@ export interface NavigationTabRouterConfig { // Does the back button cause the router to switch to the initial tab backBehavior?: 'none' | 'initialRoute'; // defaults `initialRoute` } - +export interface TabScene { + route: NavigationRoute; + focused: boolean; + index: number; + tintColor?: string; +} export interface NavigationTabScreenOptions extends NavigationScreenOptions { tabBarIcon?: React.ReactElement @@ -339,6 +342,11 @@ export interface NavigationTabScreenOptions extends NavigationScreenOptions { any > | string | null)); tabBarVisible?: boolean; + tabBarTestIDProps?: { testID?: string, accessibilityLabel?: string }; + tabBarOnPress?: (options: { + scene: TabScene, + jumpToIndex: (index: number) => void + }) => void; } export interface NavigationDrawerScreenOptions extends NavigationScreenOptions { @@ -348,26 +356,49 @@ export interface NavigationDrawerScreenOptions extends NavigationScreenOptions { any > | null)); drawerLabel?: - React.ReactElement + string + | React.ReactElement | ((options: { tintColor: (string | null), focused: boolean }) => (React.ReactElement< any > | null)); } export interface NavigationRouteConfigMap { - [routeName: string]: NavigationRouteConfig; + [routeName: string]: NavigationRouteConfig; } -export type NavigationDispatch = (action: A) => boolean; +export type NavigationDispatch = (action: NavigationAction) => boolean; -export interface NavigationProp { +export interface NavigationProp { state: S; - dispatch: NavigationDispatch; + dispatch: NavigationDispatch; } -export interface NavigationScreenProp { +export type EventType = +| 'willFocus' +| 'didFocus' +| 'willBlur' +| 'didBlur' +| 'action'; + +export interface NavigationEventPayload { + type: EventType; + action: NavigationAction; + state: NavigationState; + lastState: NavigationState; +} + +export type NavigationEventCallback = ( + payload: NavigationEventPayload +) => void; + +export interface NavigationEventSubscription { + remove: () => void; +} + +export interface NavigationScreenProp { state: S; - dispatch: NavigationDispatch; + dispatch: NavigationDispatch; goBack: (routeKey?: (string | null)) => boolean; navigate: ( routeName: string, @@ -375,10 +406,26 @@ export interface NavigationScreenProp { action?: NavigationAction ) => boolean; setParams: (newParams: NavigationParams) => boolean; + addListener: ( + eventName: string, + callback: NavigationEventCallback + ) => NavigationEventSubscription; + push: ( + routeName: string, + params?: NavigationParams, + action?: NavigationNavigateAction + ) => boolean; + replace: ( + routeName: string, + params?: NavigationParams, + action?: NavigationNavigateAction + ) => boolean; + pop: (n?: number, params?: { immediate?: boolean }) => boolean; + popToTop: (params?: { immediate?: boolean }) => boolean; } -export interface NavigationNavigatorProps { - navigation?: NavigationProp; +export interface NavigationNavigatorProps { + navigation?: NavigationProp; screenProps?: { [key: string]: any }; navigationOptions?: any; } @@ -402,7 +449,7 @@ export interface NavigationScene { isActive: boolean; isStale: boolean; key: string; - route: NavigationRoute; + route: NavigationRoute; } export interface NavigationTransitionProps { @@ -410,7 +457,7 @@ export interface NavigationTransitionProps { layout: NavigationLayout; // The destination navigation state of the transition - navigation: NavigationScreenProp; + navigation: NavigationScreenProp; // The progressive index of the transitioner's navigation state. position: AnimatedValue; @@ -498,7 +545,9 @@ export type NavigatorType = | 'react-navigation/DRAWER'; // From addNavigatorHelpers.js -export function addNavigationHelpers(navigation: NavigationProp): NavigationScreenProp; +export function addNavigationHelpers( + navigation: NavigationProp +): NavigationScreenProp; // From createNavigationContainer.js export interface NavigationContainerProps { @@ -531,15 +580,16 @@ export function StackNavigator( ): NavigationContainer; // DrawerItems -export const DrawerItems: React.ComponentClass; +export const DrawerItems: React.ComponentType; /** * Drawer Navigator */ export interface DrawerViewConfig { + drawerBackgroundColor?: string; drawerWidth?: number; drawerPosition?: 'left' | 'right'; - contentComponent?: (props: any) => React.ReactElement | React.ComponentClass; + contentComponent?: React.ComponentType; contentOptions?: any; style?: StyleProp; } @@ -566,10 +616,11 @@ export function DrawerNavigator( // From views/TabView/TabView.js export interface TabViewConfig { - tabBarComponent?: React.ComponentClass; + tabBarComponent?: React.ComponentType; tabBarPosition?: 'top' | 'bottom'; tabBarOptions?: { activeTintColor?: string, + allowFontScaling?: boolean, activeBackgroundColor?: string, inactiveTintColor?: string, inactiveBackgroundColor?: string, @@ -592,7 +643,11 @@ export interface TabViewConfig { } // From navigators/TabNavigator.js -export interface TabNavigatorConfig extends NavigationTabRouterConfig, TabViewConfig { } +export interface TabNavigatorConfig extends NavigationTabRouterConfig, TabViewConfig { + lazy?: boolean; + removeClippedSubviews?: boolean; + initialLayout?: { height: number, width: number }; +} // From navigators/TabNavigator.js export function TabNavigator( @@ -600,13 +655,74 @@ export function TabNavigator( drawConfig?: TabNavigatorConfig, ): NavigationContainer; -export const TabBarTop: React.ComponentClass; -export const TabBarBottom: React.ComponentClass; +export interface TabBarTopProps { + activeTintColor: string; + inactiveTintColor: string; + showIcon: boolean; + showLabel: boolean; + upperCaseLabel: boolean; + allowFontScaling: boolean; + position: AnimatedValue; + tabBarPosition: string; + navigation: NavigationScreenProp; + jumpToIndex: (index: number) => void; + getLabel: (scene: TabScene) => (React.ReactNode | string); + getOnPress: ( + previousScene: NavigationRoute, + scene: TabScene + ) => (args: { + previousScene: NavigationRoute, + scene: TabScene, + jumpToIndex: (index: number) => void, + }) => void; + renderIcon: (scene: TabScene) => React.ReactElement; + labelStyle?: TextStyle; + iconStyle?: ViewStyle; +} + +export interface TabBarBottomProps { + activeTintColor: string; + activeBackgroundColor: string; + adaptive?: boolean; + inactiveTintColor: string; + inactiveBackgroundColor: string; + showLabel?: boolean; + allowFontScaling: boolean; + position: AnimatedValue; + navigation: NavigationScreenProp; + jumpToIndex: (index: number) => void; + getLabel: (scene: TabScene) => (React.ReactNode | string); + getOnPress: ( + previousScene: NavigationRoute, + scene: TabScene + ) => (args: { + previousScene: NavigationRoute, + scene: TabScene, + jumpToIndex: (index: number) => void, + }) => void; + getTestIDProps: (scene: TabScene) => (scene: TabScene) => any; + renderIcon: (scene: TabScene) => React.ReactNode; + style?: ViewStyle; + animateStyle?: ViewStyle; + labelStyle?: TextStyle; + tabStyle?: ViewStyle; + showIcon?: boolean; +} + +export const TabBarTop: React.ComponentType; +export const TabBarBottom: React.ComponentType; /** * NavigationActions */ export namespace NavigationActions { + const BACK: 'Navigation/BACK'; + const INIT: 'Navigation/INIT'; + const NAVIGATE: 'Navigation/NAVIGATE'; + const RESET: 'Navigation/RESET'; + const SET_PARAMS: 'Navigation/SET_PARAMS'; + const URI: 'Navigation/URI'; + function init(options?: NavigationInitActionPayload): NavigationInitAction; function navigate(options: NavigationNavigateActionPayload): NavigationNavigateAction; function reset(options: NavigationResetActionPayload): NavigationResetAction; @@ -623,7 +739,7 @@ export interface TransitionerProps { transitionProps: NavigationTransitionProps, prevTransitionProps?: NavigationTransitionProps ) => NavigationTransitionSpec; - navigation: NavigationScreenProp; + navigation: NavigationScreenProp; onTransitionEnd?: () => void; onTransitionStart?: () => void; render: ( @@ -668,7 +784,7 @@ export function StackRouter( /** * Create Navigator * - * @see https://github.com/react-community/react-navigation/blob/master/src/navigators/createNavigator.js + * @see https://github.com/react-navigation/react-navigation/blob/master/src/navigators/createNavigator.js */ export function createNavigator( router: NavigationRouter, @@ -683,11 +799,11 @@ export function createNavigator( * This allows to use e.g. the StackNavigator and TabNavigator as root-level * components. * - * @see https://github.com/react-community/react-navigation/blob/master/src/createNavigationContainer.js + * @see https://github.com/react-navigation/react-navigation/blob/master/src/createNavigationContainer.js */ export function createNavigationContainer( Component: NavigationNavigator -): React.Component; +): NavigationContainer; /** * END MANUAL DEFINITIONS OUTSIDE OF TYPEDEFINITION.JS */ @@ -696,8 +812,8 @@ export function createNavigationContainer( * BEGIN CUSTOM CONVENIENCE INTERFACES */ -export interface NavigationScreenProps { - navigation: NavigationScreenProp, NavigationAction>; +export interface NavigationScreenProps { + navigation: NavigationScreenProp; screenProps?: { [key: string]: any }; navigationOptions?: NavigationScreenConfig; } @@ -727,3 +843,15 @@ export const HeaderBackButton: React.ComponentClass; * Header Component */ export const Header: React.ComponentClass; + +export interface NavigationInjectedProps { + navigation: NavigationScreenProp; +} + +export function withNavigation( + Component: React.ComponentType +): React.ComponentType; + +export function withNavigationFocus( + Component: React.ComponentType +): React.ComponentType; diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx index e8573bac89..2ac8e1617c 100644 --- a/types/react-navigation/react-navigation-tests.tsx +++ b/types/react-navigation/react-navigation-tests.tsx @@ -29,6 +29,7 @@ import { addNavigationHelpers, HeaderBackButton, Header, + NavigationParams, } from 'react-navigation'; // Constants @@ -40,21 +41,17 @@ const viewStyle: ViewStyle = { }; const ROUTE_NAME_START_SCREEN = "StartScreen"; -interface StartScreenNavigationParams { - id: number; - s: string; -} /** * @desc Simple screen component class with typed component props that should * receive the navigation prop from the AppNavigator. */ -class StartScreen extends React.Component> { +class StartScreen extends React.Component { render() { // Implicit type checks. - const navigationStateParams: StartScreenNavigationParams = this.props.navigation.state.params; - const id = this.props.navigation.state.params.id; - const s = this.props.navigation.state.params.s; + const navigationStateParams = this.props.navigation.state.params; + const id = this.props.navigation.state.params && this.props.navigation.state.params.id; + const s = this.props.navigation.state.params && this.props.navigation.state.params.s; return ( @@ -63,25 +60,22 @@ class StartScreen extends React.Component { - const params: NextScreenNavigationParams = { - id: this.props.navigation.state.params.id, - name: this.props.navigation.state.params.s, + const params = { + id: this.props.navigation.state.params && this.props.navigation.state.params.id, + name: this.props.navigation.state.params && this.props.navigation.state.params.s, }; this.props.navigation.navigate(ROUTE_NAME_NEXT_SCREEN, params); } } const ROUTE_NAME_NEXT_SCREEN = "NextScreen"; -interface NextScreenNavigationParams { - id: number; - name: string; -} -class NextScreen extends React.Component> { + +class NextScreen extends React.Component { render() { // Implicit type checks. - const navigationStateParams: NextScreenNavigationParams = this.props.navigation.state.params; - const id = this.props.navigation.state.params.id; - const name = this.props.navigation.state.params.name; + const navigationStateParams = this.props.navigation.state.params; + const id = this.props.navigation.state.params && this.props.navigation.state.params.id; + const name = this.props.navigation.state.params && this.props.navigation.state.params.name; return ( @@ -92,7 +86,7 @@ class NextScreen extends React.Component; + navigation: NavigationScreenProp; } /** * @desc Custom transitioner component. Follows react-navigation/src/views/CardStackTransitioner.js. From f1e2710d7671bc2d9b2da5269780cc7881a5a518 Mon Sep 17 00:00:00 2001 From: Tim Wang Date: Mon, 26 Feb 2018 14:18:31 +0800 Subject: [PATCH 077/128] Fix CI --- types/react-navigation/react-navigation-tests.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx index 112aa02964..a7eaad092b 100644 --- a/types/react-navigation/react-navigation-tests.tsx +++ b/types/react-navigation/react-navigation-tests.tsx @@ -61,7 +61,7 @@ class StartScreen extends React.Component { ); } - private navigateToNextScreen = (): void => { + private readonly navigateToNextScreen = (): void => { const params = { id: this.props.navigation.state.params && this.props.navigation.state.params.id, name: this.props.navigation.state.params && this.props.navigation.state.params.s, From 9ef92bafb5ad1b7d0096e9129c6f5a82a0c97ada Mon Sep 17 00:00:00 2001 From: Tim Wang Date: Mon, 26 Feb 2018 14:29:37 +0800 Subject: [PATCH 078/128] Replace React.ComponentType to React.ReactType --- types/react-navigation/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 53349d4be8..ba9eb44152 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -269,7 +269,7 @@ export type NavigationStackScreenOptions = NavigationScreenOptions & { headerPressColorAndroid?: string; headerRight?: React.ReactElement; headerStyle?: StyleProp; - headerBackground?: React.ReactNode | React.ComponentType; + headerBackground?: React.ReactNode | React.ReactType; gesturesEnabled?: boolean; gestureResponseDistance?: { vertical?: number; horizontal?: number }; }; @@ -580,7 +580,7 @@ export function StackNavigator( ): NavigationContainer; // DrawerItems -export const DrawerItems: React.ComponentType; +export const DrawerItems: React.ReactType; /** * Drawer Navigator @@ -589,7 +589,7 @@ export interface DrawerViewConfig { drawerBackgroundColor?: string; drawerWidth?: number; drawerPosition?: 'left' | 'right'; - contentComponent?: React.ComponentType; + contentComponent?: React.ReactType; contentOptions?: any; style?: StyleProp; } @@ -616,7 +616,7 @@ export function DrawerNavigator( // From views/TabView/TabView.js export interface TabViewConfig { - tabBarComponent?: React.ComponentType; + tabBarComponent?: React.ReactType; tabBarPosition?: 'top' | 'bottom'; tabBarOptions?: { activeTintColor?: string, From 07f5f260a9843c4cdf2cc27a1de9e5b15b999ab2 Mon Sep 17 00:00:00 2001 From: Tim Wang Date: Mon, 26 Feb 2018 14:34:40 +0800 Subject: [PATCH 079/128] Fix format and outdated comment --- types/react-navigation/index.d.ts | 126 ++++++++++++++---------------- 1 file changed, 57 insertions(+), 69 deletions(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index ba9eb44152..3a4b079000 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -16,7 +16,6 @@ // TypeScript Version: 2.6 /** - * BEGIN FLOW TYPEDEFINITION.JS PORT * Reference: https://github.com/react-navigation/react-navigation/tree/a37473c5e4833f48796ee6c7c9cb4a8ac49d9c06 * * NOTE: Please update the commit/link above when updating to a new Flow @@ -382,18 +381,18 @@ export type EventType = | 'action'; export interface NavigationEventPayload { - type: EventType; - action: NavigationAction; - state: NavigationState; - lastState: NavigationState; + type: EventType; + action: NavigationAction; + state: NavigationState; + lastState: NavigationState; } export type NavigationEventCallback = ( - payload: NavigationEventPayload + payload: NavigationEventPayload ) => void; export interface NavigationEventSubscription { - remove: () => void; + remove: () => void; } export interface NavigationScreenProp { @@ -530,26 +529,15 @@ export interface LayoutEvent { }; } -/** - * END FLOW TYPEDEFINITION.JS PORT - */ - -/** - * BEGIN MANUAL DEFINITIONS OUTSIDE OF TYPEDEFINITION.JS - */ - -// From navigators/NavigatorTypes.js export type NavigatorType = | 'react-navigation/STACK' | 'react-navigation/TABS' | 'react-navigation/DRAWER'; -// From addNavigatorHelpers.js export function addNavigationHelpers( navigation: NavigationProp ): NavigationScreenProp; -// From createNavigationContainer.js export interface NavigationContainerProps { uriPrefix?: string | RegExp; onNavigationStateChange?: ( @@ -656,57 +644,57 @@ export function TabNavigator( ): NavigationContainer; export interface TabBarTopProps { - activeTintColor: string; - inactiveTintColor: string; - showIcon: boolean; - showLabel: boolean; - upperCaseLabel: boolean; - allowFontScaling: boolean; - position: AnimatedValue; - tabBarPosition: string; - navigation: NavigationScreenProp; - jumpToIndex: (index: number) => void; - getLabel: (scene: TabScene) => (React.ReactNode | string); - getOnPress: ( - previousScene: NavigationRoute, - scene: TabScene - ) => (args: { - previousScene: NavigationRoute, - scene: TabScene, - jumpToIndex: (index: number) => void, - }) => void; - renderIcon: (scene: TabScene) => React.ReactElement; - labelStyle?: TextStyle; - iconStyle?: ViewStyle; + activeTintColor: string; + inactiveTintColor: string; + showIcon: boolean; + showLabel: boolean; + upperCaseLabel: boolean; + allowFontScaling: boolean; + position: AnimatedValue; + tabBarPosition: string; + navigation: NavigationScreenProp; + jumpToIndex: (index: number) => void; + getLabel: (scene: TabScene) => (React.ReactNode | string); + getOnPress: ( + previousScene: NavigationRoute, + scene: TabScene + ) => (args: { + previousScene: NavigationRoute, + scene: TabScene, + jumpToIndex: (index: number) => void, + }) => void; + renderIcon: (scene: TabScene) => React.ReactElement; + labelStyle?: TextStyle; + iconStyle?: ViewStyle; } export interface TabBarBottomProps { - activeTintColor: string; - activeBackgroundColor: string; - adaptive?: boolean; - inactiveTintColor: string; - inactiveBackgroundColor: string; - showLabel?: boolean; - allowFontScaling: boolean; - position: AnimatedValue; - navigation: NavigationScreenProp; - jumpToIndex: (index: number) => void; - getLabel: (scene: TabScene) => (React.ReactNode | string); - getOnPress: ( - previousScene: NavigationRoute, - scene: TabScene - ) => (args: { - previousScene: NavigationRoute, - scene: TabScene, - jumpToIndex: (index: number) => void, - }) => void; - getTestIDProps: (scene: TabScene) => (scene: TabScene) => any; - renderIcon: (scene: TabScene) => React.ReactNode; - style?: ViewStyle; - animateStyle?: ViewStyle; - labelStyle?: TextStyle; - tabStyle?: ViewStyle; - showIcon?: boolean; + activeTintColor: string; + activeBackgroundColor: string; + adaptive?: boolean; + inactiveTintColor: string; + inactiveBackgroundColor: string; + showLabel?: boolean; + allowFontScaling: boolean; + position: AnimatedValue; + navigation: NavigationScreenProp; + jumpToIndex: (index: number) => void; + getLabel: (scene: TabScene) => (React.ReactNode | string); + getOnPress: ( + previousScene: NavigationRoute, + scene: TabScene + ) => (args: { + previousScene: NavigationRoute, + scene: TabScene, + jumpToIndex: (index: number) => void, + }) => void; + getTestIDProps: (scene: TabScene) => (scene: TabScene) => any; + renderIcon: (scene: TabScene) => React.ReactNode; + style?: ViewStyle; + animateStyle?: ViewStyle; + labelStyle?: TextStyle; + tabStyle?: ViewStyle; + showIcon?: boolean; } export const TabBarTop: React.ComponentType; @@ -845,13 +833,13 @@ export const HeaderBackButton: React.ComponentClass; export const Header: React.ComponentClass; export interface NavigationInjectedProps { - navigation: NavigationScreenProp; + navigation: NavigationScreenProp; } export function withNavigation( - Component: React.ComponentType + Component: React.ComponentType ): React.ComponentType; export function withNavigationFocus( - Component: React.ComponentType + Component: React.ComponentType ): React.ComponentType; From 820f42b0ff9b8f6736ae3d764f51085727390826 Mon Sep 17 00:00:00 2001 From: Tim Wang Date: Mon, 26 Feb 2018 15:49:42 +0800 Subject: [PATCH 080/128] Fix addNavigationHelpers type --- types/react-navigation/index.d.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 3a4b079000..b9c3fd53f8 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -535,7 +535,14 @@ export type NavigatorType = | 'react-navigation/DRAWER'; export function addNavigationHelpers( - navigation: NavigationProp + navigation: { + state: S; + dispatch: (action: NavigationAction) => any; + addListener?: ( + eventName: string, + callback: NavigationEventCallback + ) => NavigationEventSubscription; + } ): NavigationScreenProp; export interface NavigationContainerProps { From 4739cf80e488687d8dc0d2f638f7b25602689b31 Mon Sep 17 00:00:00 2001 From: Tim Wang Date: Mon, 26 Feb 2018 16:53:56 +0800 Subject: [PATCH 081/128] Make getStateForAction lastState optional --- types/react-navigation/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index b9c3fd53f8..7cc0dc3d63 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -109,7 +109,7 @@ export interface NavigationRouter { * an optional previous state. When the action is considered handled but the * state is unchanged, the output state is null. */ - getStateForAction: (action: Action, lastState: (State | null)) => (State | null); + getStateForAction: (action: Action, lastState?: State) => (State | null); /** * Maps a URI-like string to an action. This can be mapped to a state From 0e479f508b14e21281cf2f427cb4e240fa009631 Mon Sep 17 00:00:00 2001 From: Silas Rech Date: Mon, 26 Feb 2018 15:58:48 +0100 Subject: [PATCH 082/128] Update inert types to 5.1 (#23864) --- types/h2o2/tsconfig.json | 3 + types/hapi-auth-jwt2/tsconfig.json | 5 +- types/hapi-decorators/tsconfig.json | 5 +- types/hapi/v16/tsconfig.json | 3 + types/inert/index.d.ts | 121 ++++++++++---- types/inert/inert-tests.ts | 202 +++++++++++------------- types/inert/tsconfig.json | 5 +- types/inert/tslint.json | 80 +--------- types/inert/v4/index.d.ts | 116 ++++++++++++++ types/inert/v4/inert-tests.ts | 130 +++++++++++++++ types/inert/v4/tsconfig.json | 34 ++++ types/inert/v4/tslint.json | 79 +++++++++ types/swagger-express-mw/tsconfig.json | 5 +- types/swagger-hapi/tsconfig.json | 5 +- types/swagger-node-runner/tsconfig.json | 5 +- types/swagger-restify-mw/tsconfig.json | 5 +- types/swagger-sails-hook/tsconfig.json | 5 +- types/vision/v4/tsconfig.json | 3 + 18 files changed, 574 insertions(+), 237 deletions(-) create mode 100644 types/inert/v4/index.d.ts create mode 100644 types/inert/v4/inert-tests.ts create mode 100644 types/inert/v4/tsconfig.json create mode 100644 types/inert/v4/tslint.json diff --git a/types/h2o2/tsconfig.json b/types/h2o2/tsconfig.json index 9d5b689ee1..eb41a55289 100644 --- a/types/h2o2/tsconfig.json +++ b/types/h2o2/tsconfig.json @@ -19,6 +19,9 @@ ], "hapi": [ "hapi/v16" + ], + "inert": [ + "inert/v4" ] }, "noEmit": true, diff --git a/types/hapi-auth-jwt2/tsconfig.json b/types/hapi-auth-jwt2/tsconfig.json index 1f8cc10075..ada8a3f94d 100644 --- a/types/hapi-auth-jwt2/tsconfig.json +++ b/types/hapi-auth-jwt2/tsconfig.json @@ -19,6 +19,9 @@ ], "hapi": [ "hapi/v16" + ], + "inert": [ + "inert/v4" ] }, "noEmit": true, @@ -28,4 +31,4 @@ "index.d.ts", "hapi-auth-jwt2-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/hapi-decorators/tsconfig.json b/types/hapi-decorators/tsconfig.json index 44437f4b9e..a018c33c53 100644 --- a/types/hapi-decorators/tsconfig.json +++ b/types/hapi-decorators/tsconfig.json @@ -21,6 +21,9 @@ ], "hapi": [ "hapi/v16" + ], + "inert": [ + "inert/v4" ] }, "noEmit": true, @@ -30,4 +33,4 @@ "index.d.ts", "hapi-decorators-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/hapi/v16/tsconfig.json b/types/hapi/v16/tsconfig.json index d3d30f97dc..517d678910 100644 --- a/types/hapi/v16/tsconfig.json +++ b/types/hapi/v16/tsconfig.json @@ -19,6 +19,9 @@ ], "hapi": [ "hapi/v16" + ], + "inert": [ + "inert/v4" ] }, "noEmit": true, diff --git a/types/inert/index.d.ts b/types/inert/index.d.ts index e74d1a4ce9..d8c1d90422 100644 --- a/types/inert/index.d.ts +++ b/types/inert/index.d.ts @@ -1,16 +1,28 @@ -// Type definitions for inert 4.2 +// Type definitions for inert 5.1 // Project: https://github.com/hapijs/inert/ -// Definitions by: Steve Ognibene , AJP +// Definitions by: Steve Ognibene +// Alexander James Phillips +// Silas Rech // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -import * as hapi from 'hapi'; +import { + Plugin, + Request, +} from 'hapi'; declare namespace inert { - export interface ReplyFileHandlerOptions { - /** confine - serve file relative to this directory and returns 403 Forbidden if the path resolves outside the confine directory. Defaults to true which uses the relativeTo route option as the confine. Set to false to disable this security feature. */ + type RequestHandler = (request: Request) => T; + + interface ReplyFileHandlerOptions { + /** + * confine - serve file relative to this directory and returns 403 Forbidden if the path resolves outside the confine directory. + * Defaults to true which uses the relativeTo route option as the confine. Set to false to disable this security feature. + */ confine?: boolean; - /** filename - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path */ + /** + * filename - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path + */ filename?: string; /** * mode - specifies whether to include the 'Content-Disposition' header with the response. Available values: @@ -19,9 +31,13 @@ declare namespace inert { * *'inline' */ mode?: false | 'attachment' | 'inline'; - /** lookupCompressed - if true, looks for for a pre-compressed version of the file with the same filename with an extension, depending on the accepted encoding. Defaults to false. */ + /** + * lookupCompressed - if true, looks for for a pre-compressed version of the file with the same filename with an extension, depending on the accepted encoding. Defaults to false. + */ lookupCompressed?: boolean; - /** lookupMap - an object which maps content encoding to expected file name extension. Defaults to `{ gzip: '.gz' }. */ + /** + * lookupMap - an object which maps content encoding to expected file name extension. Defaults to `{ gzip: '.gz' }. + */ lookupMap?: {[index: string]: string}; /** * etagMethod - specifies the method used to calculate the ETag header response. Available values: @@ -30,33 +46,56 @@ declare namespace inert { * * false - Disable ETag computation. */ etagMethod?: 'hash' | 'simple' | false; - /** start - offset in file to reading from, defaults to 0. */ + /** + * start - offset in file to reading from, defaults to 0. + */ start?: number; - /** end - offset in file to stop reading from. If not set, will read to end of file. */ + /** + * end - offset in file to stop reading from. If not set, will read to end of file. + */ end?: number; } - export interface FileHandlerRouteObject extends ReplyFileHandlerOptions { - /** path - a path string or function as described above (required). */ - path: string | hapi.RequestHandler; + interface FileHandlerRouteObject extends ReplyFileHandlerOptions { + /** + * path - a path string or function as described above (required). + */ + path: string | RequestHandler; } - export interface DirectoryHandlerRouteObject { - /** path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: - * * a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. - * * an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). - * * a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response. + interface DirectoryHandlerRouteObject { + /** + * path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: + * * a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. + * * an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). + * * a function with the signature function(request) which returns the path string or an array of path strings. + * If the function returns an error, the error is passed back to the client in the response. + */ + path: string | string[] | RequestHandler; + /** + * index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. + * The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. + * Any falsy value disables index file lookup. Defaults to true. */ - path: string | string[] | hapi.RequestHandler; - /** index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. */ index?: boolean | string | string[]; - /** listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. */ + /** + * listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. + */ listing?: boolean; - /** showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false. */ + /** + * showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false. + */ showHidden?: boolean; - /** redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. */ + /** + * redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. + * Useful for ensuring relative links inside the response are resolved correctly. + * Disabled when the server config router.stripTrailingSlash is true.Defaults to false. + */ redirectToSlash?: boolean; - /** lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */ + /** + * lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed + * version of the file to serve if the request supports content encoding. Defaults to false. + */ lookupCompressed?: boolean; /** * etagMethod - specifies the method used to calculate the ETag header response. Available values: @@ -65,7 +104,9 @@ declare namespace inert { * * false - Disable ETag computation. */ etagMethod?: 'hash' | 'simple' | false; - /** defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension. */ + /** + * defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension. + */ defaultExtension?: string; } @@ -81,8 +122,12 @@ declare namespace inert { } } +declare const inert: Plugin; + +export = inert; + declare module 'hapi' { - interface RouteHandlerPlugins { + interface RouteOptions { /** * The file handler * @@ -92,25 +137,33 @@ declare module 'hapi' { * * an object with one or more of the following options @see IFileHandler * @see {@link https://github.com/hapijs/inert#the-file-handler} */ - file?: string | RequestHandler | inert.FileHandlerRouteObject; + file?: string | inert.RequestHandler | inert.FileHandlerRouteObject; /** * The directory handler * - * Generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: + * Generates a directory endpoint for serving static content from a directory. + * Routes using the directory handler must include a path parameter at the end of the path string + * (e.g. /path/to/somewhere/{param} where the parameter name does not matter). + * The path parameter can use any of the parameter options (e.g. {param} for one level files only, + * {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). + * If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. + * The directory handler is an object with the following options: * @see {@link https://github.com/hapijs/inert#the-directory-handler} */ directory?: inert.DirectoryHandlerRouteObject; + files?: { + /** + * Set the relative path + */ + relativeTo: string; + }; } - interface Base_Reply { + interface ResponseToolkit { /** * Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. * @see {@link https://github.com/hapijs/inert#replyfilepath-options} */ - file: (path: string, options?: inert.ReplyFileHandlerOptions) => Response; + file(path: string, options?: inert.ReplyFileHandlerOptions): ResponseObject; } } - -declare var inert: hapi.PluginFunction; - -export = inert; diff --git a/types/inert/inert-tests.ts b/types/inert/inert-tests.ts index 9062e13f6b..b772a38259 100644 --- a/types/inert/inert-tests.ts +++ b/types/inert/inert-tests.ts @@ -1,130 +1,106 @@ -// Copied from: https://github.com/hapijs/inert#examples +import { + Server, + Lifecycle, +} from 'hapi'; -import Path = require('path'); -import Hapi = require('hapi'); -import Inert = require('inert'); +import * as path from 'path'; +import * as inert from 'inert'; -const server = new Hapi.Server({ - connections: { - routes: { - files: { - relativeTo: Path.join(__dirname, 'public') +const server = new Server({ + port: 3000, + routes: { + files: { + relativeTo: path.join(__dirname, 'public') + } + } +}); + +const provision = async () => { + await server.register(inert); + + await server.register({ + plugin: inert, + options: { etagsCacheMaxSize: 400 }, + }); + + await server.register({ + plugin: inert, + once: true, + }); + + server.route({ + method: 'GET', + path: '/{param*}', + handler: { + directory: { + path: '.', + redirectToSlash: true, + index: true } } - } -}); -server.connection({ port: 3000 }); + }); -server.register(Inert, () => {}); - -// added in addition to code from docs -const options: Inert.OptionalRegistrationOptions = {etagsCacheMaxSize: 400}; -server.register({ - register: Inert, - options, -}, (err) => {}); - -// added in addition to code from docs -server.register({ - register: Inert, - once: true, -}, (err) => {}); - -server.route({ - method: 'GET', - path: '/{param*}', - handler: { - directory: { - path: '.', - redirectToSlash: true, - index: true + // https://github.com/hapijs/inert#serving-a-single-file + server.route({ + method: 'GET', + path: '/{path*}', + handler: { + file: 'page.html' } - } -}); + }); -server.start((err) => { + // https://github.com/hapijs/inert#customized-file-response + server.route({ + method: 'GET', + path: '/file', + handler(request, reply) { + let path = 'plain.txt'; + if (request.headers['x-magic'] === 'sekret') { + path = 'awesome.png'; + } - if (err) { - throw err; - } + return reply.file(path).vary('x-magic'); + } + }); - console.log('Server running at:', server.info!.uri); -}); - -// https://github.com/hapijs/inert#serving-a-single-file - -server.route({ - method: 'GET', - path: '/{path*}', - handler: { - file: 'page.html' - } -}); - -// https://github.com/hapijs/inert#customized-file-response - -server.route({ - method: 'GET', - path: '/file', - handler: function (request, reply) { - - let path = 'plain.txt'; - if (request.headers['x-magic'] === 'sekret') { - path = 'awesome.png'; + const handler: Lifecycle.Method = (request, h) => { + const response = request.response; + if (response instanceof Error && response.output.statusCode === 404) { + return h.file('404.html').code(404); } - return reply.file(path).vary('x-magic'); - } -}); + return h.continue; + }; -const handler: Hapi.ServerExtRequestHandler = function (request, reply) { + server.ext('onPostHandler', handler); - const response = request.response!; - if (response.isBoom && - response.output!.statusCode === 404) { + const file: inert.FileHandlerRouteObject = { + path: '', + confine: true, + }; - return reply.file('404.html').code(404); - } + const directory: inert.DirectoryHandlerRouteObject = { + path: '', + listing: true + }; - return reply.continue(); -} - -server.ext('onPostHandler', handler); - -// additional code added in addition to doc example code - -var file: Inert.FileHandlerRouteObject = { - path: '', - confine: true, -}; -var directory: Inert.DirectoryHandlerRouteObject = { - path: '', - listing: true -}; - -file = { - path: '', - confine: true, -}; - -server.route({ - path: '', - method: 'GET', - handler: { - file, - directory: { - path: function(){ - if(Math.random() > 0.5) { - return ''; - } - else if(Math.random() > 0) { - return ['']; - } - return new Error(''); + server.route({ + path: '', + method: 'GET', + handler: { + file, + directory: { + path() { + if (Math.random() > 0.5) { + return ''; + } else if (Math.random() > 0) { + return ['']; + } + return new Error(''); + }, + BAD_listing: true, }, - BAD_listing: true, // TODO change typings to make this error }, - }, - config: { files: { relativeTo: __dirname } } -}) - + options: { files: { relativeTo: __dirname } } + }); +}; diff --git a/types/inert/tsconfig.json b/types/inert/tsconfig.json index c96c356741..238aa1a3eb 100644 --- a/types/inert/tsconfig.json +++ b/types/inert/tsconfig.json @@ -16,9 +16,6 @@ "paths": { "boom": [ "boom/v4" - ], - "hapi": [ - "hapi/v16" ] }, "noEmit": true, @@ -28,4 +25,4 @@ "index.d.ts", "inert-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/inert/tslint.json b/types/inert/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/inert/tslint.json +++ b/types/inert/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/inert/v4/index.d.ts b/types/inert/v4/index.d.ts new file mode 100644 index 0000000000..e74d1a4ce9 --- /dev/null +++ b/types/inert/v4/index.d.ts @@ -0,0 +1,116 @@ +// Type definitions for inert 4.2 +// Project: https://github.com/hapijs/inert/ +// Definitions by: Steve Ognibene , AJP +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import * as hapi from 'hapi'; + +declare namespace inert { + export interface ReplyFileHandlerOptions { + /** confine - serve file relative to this directory and returns 403 Forbidden if the path resolves outside the confine directory. Defaults to true which uses the relativeTo route option as the confine. Set to false to disable this security feature. */ + confine?: boolean; + /** filename - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path */ + filename?: string; + /** + * mode - specifies whether to include the 'Content-Disposition' header with the response. Available values: + * * false - header is not included. This is the default value. + * * 'attachment' + * *'inline' + */ + mode?: false | 'attachment' | 'inline'; + /** lookupCompressed - if true, looks for for a pre-compressed version of the file with the same filename with an extension, depending on the accepted encoding. Defaults to false. */ + lookupCompressed?: boolean; + /** lookupMap - an object which maps content encoding to expected file name extension. Defaults to `{ gzip: '.gz' }. */ + lookupMap?: {[index: string]: string}; + /** + * etagMethod - specifies the method used to calculate the ETag header response. Available values: + * * 'hash' - SHA1 sum of the file contents, suitable for distributed deployments. Default value. + * * 'simple' - Hex encoded size and modification date, suitable when files are stored on a single server. + * * false - Disable ETag computation. + */ + etagMethod?: 'hash' | 'simple' | false; + /** start - offset in file to reading from, defaults to 0. */ + start?: number; + /** end - offset in file to stop reading from. If not set, will read to end of file. */ + end?: number; + } + + export interface FileHandlerRouteObject extends ReplyFileHandlerOptions { + /** path - a path string or function as described above (required). */ + path: string | hapi.RequestHandler; + } + + export interface DirectoryHandlerRouteObject { + /** path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: + * * a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. + * * an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). + * * a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response. + */ + path: string | string[] | hapi.RequestHandler; + /** index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. */ + index?: boolean | string | string[]; + /** listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. */ + listing?: boolean; + /** showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false. */ + showHidden?: boolean; + /** redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. */ + redirectToSlash?: boolean; + /** lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */ + lookupCompressed?: boolean; + /** + * etagMethod - specifies the method used to calculate the ETag header response. Available values: + * * 'hash' - SHA1 sum of the file contents, suitable for distributed deployments. Default value. + * * 'simple' - Hex encoded size and modification date, suitable when files are stored on a single server. + * * false - Disable ETag computation. + */ + etagMethod?: 'hash' | 'simple' | false; + /** defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension. */ + defaultExtension?: string; + } + + /** + * inert accepts the following registration options + * @see {@link https://github.com/hapijs/inert#registration-options} + */ + interface OptionalRegistrationOptions { + /** + * sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000. + */ + etagsCacheMaxSize?: number; + } +} + +declare module 'hapi' { + interface RouteHandlerPlugins { + /** + * The file handler + * + * Generates a static file endpoint for serving a single file. file can be set to: + * * a relative or absolute file path string (relative paths are resolved based on the route files configuration). + * * a function with the signature function(request) which returns the relative or absolute file path. + * * an object with one or more of the following options @see IFileHandler + * @see {@link https://github.com/hapijs/inert#the-file-handler} + */ + file?: string | RequestHandler | inert.FileHandlerRouteObject; + /** + * The directory handler + * + * Generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: + * @see {@link https://github.com/hapijs/inert#the-directory-handler} + */ + directory?: inert.DirectoryHandlerRouteObject; + } + + interface Base_Reply { + /** + * Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. + * @see {@link https://github.com/hapijs/inert#replyfilepath-options} + */ + file: (path: string, options?: inert.ReplyFileHandlerOptions) => Response; + } +} + +declare var inert: hapi.PluginFunction; + +export = inert; diff --git a/types/inert/v4/inert-tests.ts b/types/inert/v4/inert-tests.ts new file mode 100644 index 0000000000..9062e13f6b --- /dev/null +++ b/types/inert/v4/inert-tests.ts @@ -0,0 +1,130 @@ +// Copied from: https://github.com/hapijs/inert#examples + +import Path = require('path'); +import Hapi = require('hapi'); +import Inert = require('inert'); + +const server = new Hapi.Server({ + connections: { + routes: { + files: { + relativeTo: Path.join(__dirname, 'public') + } + } + } +}); +server.connection({ port: 3000 }); + +server.register(Inert, () => {}); + +// added in addition to code from docs +const options: Inert.OptionalRegistrationOptions = {etagsCacheMaxSize: 400}; +server.register({ + register: Inert, + options, +}, (err) => {}); + +// added in addition to code from docs +server.register({ + register: Inert, + once: true, +}, (err) => {}); + +server.route({ + method: 'GET', + path: '/{param*}', + handler: { + directory: { + path: '.', + redirectToSlash: true, + index: true + } + } +}); + +server.start((err) => { + + if (err) { + throw err; + } + + console.log('Server running at:', server.info!.uri); +}); + +// https://github.com/hapijs/inert#serving-a-single-file + +server.route({ + method: 'GET', + path: '/{path*}', + handler: { + file: 'page.html' + } +}); + +// https://github.com/hapijs/inert#customized-file-response + +server.route({ + method: 'GET', + path: '/file', + handler: function (request, reply) { + + let path = 'plain.txt'; + if (request.headers['x-magic'] === 'sekret') { + path = 'awesome.png'; + } + + return reply.file(path).vary('x-magic'); + } +}); + +const handler: Hapi.ServerExtRequestHandler = function (request, reply) { + + const response = request.response!; + if (response.isBoom && + response.output!.statusCode === 404) { + + return reply.file('404.html').code(404); + } + + return reply.continue(); +} + +server.ext('onPostHandler', handler); + +// additional code added in addition to doc example code + +var file: Inert.FileHandlerRouteObject = { + path: '', + confine: true, +}; +var directory: Inert.DirectoryHandlerRouteObject = { + path: '', + listing: true +}; + +file = { + path: '', + confine: true, +}; + +server.route({ + path: '', + method: 'GET', + handler: { + file, + directory: { + path: function(){ + if(Math.random() > 0.5) { + return ''; + } + else if(Math.random() > 0) { + return ['']; + } + return new Error(''); + }, + BAD_listing: true, // TODO change typings to make this error + }, + }, + config: { files: { relativeTo: __dirname } } +}) + diff --git a/types/inert/v4/tsconfig.json b/types/inert/v4/tsconfig.json new file mode 100644 index 0000000000..fd468493b4 --- /dev/null +++ b/types/inert/v4/tsconfig.json @@ -0,0 +1,34 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "boom": [ + "boom/v4" + ], + "hapi": [ + "hapi/v16" + ], + "inert": [ + "inert/v4" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "inert-tests.ts" + ] +} diff --git a/types/inert/v4/tslint.json b/types/inert/v4/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/inert/v4/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} diff --git a/types/swagger-express-mw/tsconfig.json b/types/swagger-express-mw/tsconfig.json index 1d597728f7..c1db9f10a4 100644 --- a/types/swagger-express-mw/tsconfig.json +++ b/types/swagger-express-mw/tsconfig.json @@ -19,6 +19,9 @@ ], "hapi": [ "hapi/v16" + ], + "inert": [ + "inert/v4" ] }, "noEmit": true, @@ -28,4 +31,4 @@ "index.d.ts", "swagger-express-mw-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/swagger-hapi/tsconfig.json b/types/swagger-hapi/tsconfig.json index 410688bcf1..df8e735e23 100644 --- a/types/swagger-hapi/tsconfig.json +++ b/types/swagger-hapi/tsconfig.json @@ -19,6 +19,9 @@ ], "hapi": [ "hapi/v16" + ], + "inert": [ + "inert/v4" ] }, "noEmit": true, @@ -28,4 +31,4 @@ "index.d.ts", "swagger-hapi-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/swagger-node-runner/tsconfig.json b/types/swagger-node-runner/tsconfig.json index e559433107..d8bb8c8f52 100644 --- a/types/swagger-node-runner/tsconfig.json +++ b/types/swagger-node-runner/tsconfig.json @@ -19,6 +19,9 @@ ], "hapi": [ "hapi/v16" + ], + "inert": [ + "inert/v4" ] }, "noEmit": true, @@ -28,4 +31,4 @@ "index.d.ts", "swagger-node-runner-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/swagger-restify-mw/tsconfig.json b/types/swagger-restify-mw/tsconfig.json index 8c5f09a930..ec732988fc 100644 --- a/types/swagger-restify-mw/tsconfig.json +++ b/types/swagger-restify-mw/tsconfig.json @@ -19,6 +19,9 @@ ], "hapi": [ "hapi/v16" + ], + "inert": [ + "inert/v4" ] }, "noEmit": true, @@ -28,4 +31,4 @@ "index.d.ts", "swagger-restify-mw-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/swagger-sails-hook/tsconfig.json b/types/swagger-sails-hook/tsconfig.json index 508453b078..98768dd651 100644 --- a/types/swagger-sails-hook/tsconfig.json +++ b/types/swagger-sails-hook/tsconfig.json @@ -19,6 +19,9 @@ ], "hapi": [ "hapi/v16" + ], + "inert": [ + "inert/v4" ] }, "noEmit": true, @@ -28,4 +31,4 @@ "index.d.ts", "swagger-sails-hook-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/vision/v4/tsconfig.json b/types/vision/v4/tsconfig.json index bee5c542c4..2ab1f666a0 100644 --- a/types/vision/v4/tsconfig.json +++ b/types/vision/v4/tsconfig.json @@ -20,6 +20,9 @@ "hapi": [ "hapi/v16" ], + "inert": [ + "inert/v4" + ], "vision": [ "vision/v4" ] From cc4dd221339073fe2babad043b6f2837fe4cecfd Mon Sep 17 00:00:00 2001 From: Grant Timmerman Date: Mon, 26 Feb 2018 07:19:22 -0800 Subject: [PATCH 083/128] Add Google Apps Script Slides (#23657) * Add Apps Script Google Slides * Update CODEOWNERS * Update CODEOWNERS --- .github/CODEOWNERS | 2 +- .../google-apps-script.slides.d.ts | 1423 +++++++++++++++++ types/google-apps-script/index.d.ts | 1 + 3 files changed, 1425 insertions(+), 1 deletion(-) create mode 100644 types/google-apps-script/google-apps-script.slides.d.ts diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index a03915a264..be7e9011fd 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1214,7 +1214,7 @@ /types/gm/ @ChaosinaCan @maartenvanvliet /types/go/ @NorthwoodsSoftware /types/google-adwords-scripts/ @jafaircl -/types/google-apps-script/ @motemen +/types/google-apps-script/ @motemen @grant /types/google-apps-script-oauth2/ @dhayab /types/google-cloud__datastore/ @beaulac /types/google-cloud__pubsub/ @pheromonez diff --git a/types/google-apps-script/google-apps-script.slides.d.ts b/types/google-apps-script/google-apps-script.slides.d.ts new file mode 100644 index 0000000000..494663f002 --- /dev/null +++ b/types/google-apps-script/google-apps-script.slides.d.ts @@ -0,0 +1,1423 @@ +// Type definitions for Google Apps Script 2018-02-14 +// Project: https://developers.google.com/apps-script/ +// Definitions by: motemen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + +declare namespace GoogleAppsScript { + export module Slides { + /** + * A 3x3 matrix used to transform source coordinates (x1, y1) into destination coordinates (x2, y2) + * according to matrix multiplication: + * + * [ x2 ] [ scaleX shearX translateX ] [ x1 ] + * [ y2 ] = [ shearY scaleY translateY ] [ y1 ] + * [ 1 ] [ 0 0 1 ] [ 1 ] + * + * After transformation, + * + * x2 = scaleX * x1 + shearX * y1 + translateX + * y2 = scaleY * y1 + shearY * x1 + translateY + */ + export interface AffineTransform { + getScaleX(): Number; + getScaleY(): Number; + getShearX(): Number; + getShearY(): Number; + getTranslateX(): Number; + getTranslateY(): Number; + toBuilder(): AffineTransformBuilder; + } + + /** + * A builder for AffineTransform objects. Defaults to the identity transform. + * + * Call AffineTransformBuilder#build() to get the AffineTransform object. + * + * var transform = + * SlidesApp.newAffineTransformBuilder().setScaleX(2.0).setShearY(1.1).build(); + * + * The resulting transform matrix is + * [ 2.0 0.0 0.0 ] + * [ 1.1 1.0 0.0 ] + * [ 0 0 1 ] + */ + export interface AffineTransformBuilder { + build(): AffineTransform; + setScaleX(scaleX: Number): AffineTransformBuilder; + setScaleY(scaleY: Number): AffineTransformBuilder; + setShearX(shearX: Number): AffineTransformBuilder; + setShearY(shearY: Number): AffineTransformBuilder; + setTranslateX(translateX: Number): AffineTransformBuilder; + setTranslateY(translateY: Number): AffineTransformBuilder; + } + + /** + * The alignment position to apply. + */ + export enum AlignmentPosition { CENTER, HORIZONTAL_CENTER, VERTICAL_CENTER } + + /** + * The kinds of start and end forms with which linear geometry can be rendered. + * + * Some values are based on the "ST_LineEndType" simple type described in section 20.1.10.33 of + * of "Office Open XML File Formats - Fundamentals and Markup Language Reference", part 1 of ECMA-376 4th + * edition. + */ + export enum ArrowStyle { UNSUPPORTED, NONE, STEALTH_ARROW, FILL_ARROW, FILL_CIRCLE, FILL_SQUARE, FILL_DIAMOND, OPEN_ARROW, OPEN_CIRCLE, OPEN_SQUARE, OPEN_DIAMOND } + + /** + * An element of text that is dynamically replaced with content that can change over time, such as a + * slide number. + */ + export interface AutoText { + getAutoTextType(): AutoTextType; + getIndex(): Integer; + getRange(): TextRange; + } + + /** + * The types of auto text. + */ + export enum AutoTextType { UNSUPPORTED, SLIDE_NUMBER } + + /** + * Describes the border around an element. + */ + export interface Border { + getDashStyle(): DashStyle; + getLineFill(): LineFill; + getWeight(): Number; + isVisible(): boolean; + setDashStyle(style: DashStyle): Border; + setTransparent(): Border; + setWeight(points: Number): Border; + } + + /** + * The table cell merge states. + */ + export enum CellMergeState { NORMAL, HEAD, MERGED } + + /** + * An opaque color + */ + export interface Color { + asRgbColor(): RgbColor; + asThemeColor(): ThemeColor; + getColorType(): ColorType; + } + + /** + * A color scheme defines a mapping from members of ThemeColorType to the actual colors used + * to render them. + */ + export interface ColorScheme { + getConcreteColor(theme: ThemeColorType): Color; + getThemeColors(): ThemeColorType[]; + } + + /** + * The types of Colors + */ + export enum ColorType { UNSUPPORTED, RGB, THEME } + + /** + * The content alignments for a Shape or TableCell. The supported alignments + * correspond to predefined text anchoring types from the ECMA-376 standard. + * + * More information on those alignments can be found in the description of + * the ST_TextAnchoringType simple type in section 20.1.10.59 of "Office Open XML File + * Formats - Fundamentals and Markup Language Reference", part 1 of ECMA-376 4th + * edition. + */ + export enum ContentAlignment { UNSUPPORTED, TOP, MIDDLE, BOTTOM } + + /** + * The kinds of dashes with which linear geometry can be rendered. These values are based on the + * "ST_PresetLineDashVal" simple type described in section 20.1.10.48 of "Office Open XML File + * Formats - Fundamentals and Markup Language Reference", part 1 of ECMA-376 4th + * edition. + */ + export enum DashStyle { UNSUPPORTED, SOLID, DOT, DASH, DASH_DOT, LONG_DASH, LONG_DASH_DOT } + + /** + * Describes the page element's background + */ + export interface Fill { + getSolidFill(): SolidFill; + getType(): FillType; + isVisible(): boolean; + setSolidFill(color: Color): void; + setSolidFill(color: Color, alpha: Number): void; + setSolidFill(red: Integer, green: Integer, blue: Integer): void; + setSolidFill(red: Integer, green: Integer, blue: Integer, alpha: Number): void; + setSolidFill(hexString: string): void; + setSolidFill(hexString: string, alpha: Number): void; + setSolidFill(color: ThemeColorType): void; + setSolidFill(color: ThemeColorType, alpha: Number): void; + setTransparent(): void; + } + + /** + * The kinds of fill. + */ + export enum FillType { UNSUPPORTED, NONE, SOLID } + + /** + * A collection of PageElements joined as a single unit. + */ + export interface Group { + alignOnPage(alignmentPosition: AlignmentPosition): Group; + duplicate(): PageElement; + getChildren(): PageElement[]; + getDescription(): string; + getHeight(): Number; + getInherentHeight(): Number; + getInherentWidth(): Number; + getLeft(): Number; + getObjectId(): string; + getPageElementType(): PageElementType; + getParentGroup(): Group; + getParentPage(): Page; + getRotation(): Number; + getTitle(): string; + getTop(): Number; + getTransform(): AffineTransform; + getWidth(): Number; + preconcatenateTransform(transform: AffineTransform): Group; + remove(): void; + scaleHeight(ratio: Number): Group; + scaleWidth(ratio: Number): Group; + select(): void; + select(replace: boolean): void; + setHeight(height: Number): Group; + setLeft(left: Number): Group; + setRotation(angle: Number): Group; + setTop(top: Number): Group; + setTransform(transform: AffineTransform): Group; + setWidth(width: Number): Group; + ungroup(): void; + } + + /** + * A PageElement representing an image. + */ + export interface Image { + alignOnPage(alignmentPosition: AlignmentPosition): Image; + duplicate(): PageElement; + getBorder(): Border; + getContentUrl(): string; + getDescription(): string; + getHeight(): Number; + getInherentHeight(): Number; + getInherentWidth(): Number; + getLeft(): Number; + getLink(): Link; + getObjectId(): string; + getPageElementType(): PageElementType; + getParentGroup(): Group; + getParentPage(): Page; + getRotation(): Number; + getSourceUrl(): string; + getTitle(): string; + getTop(): Number; + getTransform(): AffineTransform; + getWidth(): Number; + preconcatenateTransform(transform: AffineTransform): Image; + remove(): void; + removeLink(): void; + replace(blobSource: Base.BlobSource): Image; + replace(blobSource: Base.BlobSource, crop: boolean): Image; + replace(imageUrl: string): Image; + replace(imageUrl: string, crop: boolean): Image; + scaleHeight(ratio: Number): Image; + scaleWidth(ratio: Number): Image; + select(): void; + select(replace: boolean): void; + setHeight(height: Number): Image; + setLeft(left: Number): Image; + setLinkSlide(slideIndex: Integer): Link; + setLinkSlide(slide: Slide): Link; + setLinkSlide(slidePosition: SlidePosition): Link; + setLinkUrl(url: string): Link; + setRotation(angle: Number): Image; + setTop(top: Number): Image; + setTransform(transform: AffineTransform): Image; + setWidth(width: Number): Image; + } + + /** + * A layout in a presentation. + * + * Each layout serves as a template for slides that inherit from it, determining how content on + * those slides is arranged and styled. + */ + export interface Layout { + getBackground(): PageBackground; + getColorScheme(): ColorScheme; + getGroups(): Group[]; + getImages(): Image[]; + getLayoutName(): string; + getLines(): Line[]; + getMaster(): Master; + getObjectId(): string; + getPageElements(): PageElement[]; + getPageType(): PageType; + getPlaceholder(placeholderType: PlaceholderType): PageElement; + getPlaceholder(placeholderType: PlaceholderType, placeholderIndex: Integer): PageElement; + getPlaceholders(): PageElement[]; + getShapes(): Shape[]; + getSheetsCharts(): SheetsChart[]; + getTables(): Table[]; + getVideos(): Video[]; + getWordArts(): WordArt[]; + group(pageElements: PageElement[]): Group; + insertGroup(group: Group): Group; + insertImage(blobSource: Base.BlobSource): Image; + insertImage(blobSource: Base.BlobSource, left: Number, top: Number, width: Number, height: Number): Image; + insertImage(image: Image): Image; + insertImage(imageUrl: string): Image; + insertImage(imageUrl: string, left: Number, top: Number, width: Number, height: Number): Image; + insertLine(line: Line): Line; + insertLine(lineCategory: LineCategory, startLeft: Number, startTop: Number, endLeft: Number, endTop: Number): Line; + insertPageElement(pageElement: PageElement): PageElement; + insertShape(shape: Shape): Shape; + insertShape(shapeType: ShapeType): Shape; + insertShape(shapeType: ShapeType, left: Number, top: Number, width: Number, height: Number): Shape; + insertSheetsChart(sourceChart: Spreadsheet.EmbeddedChart): SheetsChart; + insertSheetsChart(sourceChart: Spreadsheet.EmbeddedChart, left: Number, top: Number, width: Number, height: Number): SheetsChart; + insertSheetsChart(sheetsChart: SheetsChart): SheetsChart; + insertSheetsChartAsImage(sourceChart: Spreadsheet.EmbeddedChart): Image; + insertSheetsChartAsImage(sourceChart: Spreadsheet.EmbeddedChart, left: Number, top: Number, width: Number, height: Number): Image; + insertTable(numRows: Integer, numColumns: Integer): Table; + insertTable(numRows: Integer, numColumns: Integer, left: Number, top: Number, width: Number, height: Number): Table; + insertTable(table: Table): Table; + insertVideo(videoUrl: string): Video; + insertVideo(videoUrl: string, left: Number, top: Number, width: Number, height: Number): Video; + insertVideo(video: Video): Video; + insertWordArt(wordArt: WordArt): WordArt; + remove(): void; + replaceAllText(findText: string, replaceText: string): Integer; + replaceAllText(findText: string, replaceText: string, matchCase: boolean): Integer; + selectAsCurrentPage(): void; + } + + /** + * A PageElement representing a line. + */ + export interface Line { + alignOnPage(alignmentPosition: AlignmentPosition): Line; + duplicate(): PageElement; + getDashStyle(): DashStyle; + getDescription(): string; + getEnd(): Point; + getEndArrow(): ArrowStyle; + getHeight(): Number; + getInherentHeight(): Number; + getInherentWidth(): Number; + getLeft(): Number; + getLineFill(): LineFill; + getLineType(): LineType; + getLink(): Link; + getObjectId(): string; + getPageElementType(): PageElementType; + getParentGroup(): Group; + getParentPage(): Page; + getRotation(): Number; + getStart(): Point; + getStartArrow(): ArrowStyle; + getTitle(): string; + getTop(): Number; + getTransform(): AffineTransform; + getWeight(): Number; + getWidth(): Number; + preconcatenateTransform(transform: AffineTransform): Line; + remove(): void; + removeLink(): void; + scaleHeight(ratio: Number): Line; + scaleWidth(ratio: Number): Line; + select(): void; + select(replace: boolean): void; + setDashStyle(style: DashStyle): Line; + setEnd(left: Number, top: Number): Line; + setEnd(point: Point): Line; + setEndArrow(style: ArrowStyle): Line; + setHeight(height: Number): Line; + setLeft(left: Number): Line; + setLinkSlide(slideIndex: Integer): Link; + setLinkSlide(slide: Slide): Link; + setLinkSlide(slidePosition: SlidePosition): Link; + setLinkUrl(url: string): Link; + setRotation(angle: Number): Line; + setStart(left: Number, top: Number): Line; + setStart(point: Point): Line; + setStartArrow(style: ArrowStyle): Line; + setTop(top: Number): Line; + setTransform(transform: AffineTransform): Line; + setWeight(points: Number): Line; + setWidth(width: Number): Line; + } + + /** + * The line category. + * + * The exact LineType created is determined based on the category and how it's routed to + * connect to other page elements. + */ + export enum LineCategory { STRAIGHT, BENT, CURVED } + + /** + * Describes the fill of a line or outline + */ + export interface LineFill { + getFillType(): LineFillType; + getSolidFill(): SolidFill; + setSolidFill(color: Color): void; + setSolidFill(color: Color, alpha: Number): void; + setSolidFill(red: Integer, green: Integer, blue: Integer): void; + setSolidFill(red: Integer, green: Integer, blue: Integer, alpha: Number): void; + setSolidFill(hexString: string): void; + setSolidFill(hexString: string, alpha: Number): void; + setSolidFill(color: ThemeColorType): void; + setSolidFill(color: ThemeColorType, alpha: Number): void; + } + + /** + * The kinds of line fill. + */ + export enum LineFillType { UNSUPPORTED, NONE, SOLID } + + /** + * The line types. + * + * Derived from a subset of the values of the "ST_ShapeType" simple type in section 20.1.10.55 of + * "Office Open XML File Formats - Fundamentals and Markup Language Reference", part 1 of ECMA-376 4th + * edition. + */ + export enum LineType { UNSUPPORTED, STRAIGHT_CONNECTOR_1, BENT_CONNECTOR_2, BENT_CONNECTOR_3, BENT_CONNECTOR_4, BENT_CONNECTOR_5, CURVED_CONNECTOR_2, CURVED_CONNECTOR_3, CURVED_CONNECTOR_4, CURVED_CONNECTOR_5 } + + /** + * A hypertext link. + */ + export interface Link { + getLinkType(): LinkType; + getLinkedSlide(): Slide; + getSlideId(): string; + getSlideIndex(): Integer; + getSlidePosition(): SlidePosition; + getUrl(): string; + } + + /** + * The types of a Link. + */ + export enum LinkType { UNSUPPORTED, URL, SLIDE_POSITION, SLIDE_ID, SLIDE_INDEX } + + /** + * A list in the text. + */ + export interface List { + getListId(): string; + getListParagraphs(): Paragraph[]; + } + + /** + * Preset patterns of glyphs for lists in text. + * + * These presets use these glyphs: + * + * ARROW: An arrow, ➔, corresponding to a Unicode U+2794 code point + * + * ARROW3D: An arrow with 3D shading, ➢, corresponding to a Unicode U+27a2 code point + * + * CHECKBOX: A hollow square, ❏, corresponding to a Unicode U+274f code point + * + * CIRCLE: A hollow circle, ○, corresponding to a Unicode U+25cb code point + * + * DIAMOND: A solid diamond, ◆, corresponding to a Unicode U+25c6 code point + * + * `DIAMONDX: A diamond with an 'x', ❖, corresponding to a Unicode U+2756 code point + * + * HOLLOWDIAMOND: A hollow diamond, ◇, corresponding to a Unicode U+25c7 code point + * + * DISC: A solid circle, ●, corresponding to a Unicode U+25cf code point + * + * SQUARE: A solid square, ■, corresponding to a Unicode U+25a0 code point + * + * STAR: A star, ★, corresponding to a Unicode U+2605 code point + * + * ALPHA: A lowercase letter, like 'a', 'b', or 'c'. + * + * UPPERALPHA: An uppercase letter, like 'A', 'B', or 'C'. + * + * DIGIT: A number, like '1', '2', or '3'. + * + * ZERODIGIT: A number where single digit numbers are prefixed with a zero, like '01', '02', + * or '03'. Numbers with more than one digit are not prefixed a zero. + * + * ROMAN: A lowercase roman numeral, like 'i', 'ii', or 'iii'. + * + * UPPERROMAN: A uppercase roman numeral, like 'I', 'II', or 'III'. + * + * LEFTTRIANGLE: A triangle pointing left, ◄, corresponding to a Unicode U+25c4 code + * point + */ + export enum ListPreset { DISC_CIRCLE_SQUARE, DIAMONDX_ARROW3D_SQUARE, CHECKBOX, ARROW_DIAMOND_DISC, STAR_CIRCLE_SQUARE, ARROW3D_CIRCLE_SQUARE, LEFTTRIANGLE_DIAMOND_DISC, DIAMONDX_HOLLOWDIAMOND_SQUARE, DIAMOND_CIRCLE_SQUARE, DIGIT_ALPHA_ROMAN, DIGIT_ALPHA_ROMAN_PARENS, DIGIT_NESTED, UPPERALPHA_ALPHA_ROMAN, UPPERROMAN_UPPERALPHA_DIGIT, ZERODIGIT_ALPHA_ROMAN } + + /** + * The list styling for a range of text. + */ + export interface ListStyle { + applyListPreset(listPreset: ListPreset): ListStyle; + getGlyph(): string; + getList(): List; + getNestingLevel(): Integer; + isInList(): boolean; + removeFromList(): ListStyle; + } + + /** + * A master in a presentation. + * + * Masters contains all common page elements and the common properties for a set of layouts. They + * serve three purposes: + * + * Placeholder shapes on a master contain the default text styles and shape properties of all + * placeholder shapes on pages that use that master. + * + * The properties of a master page define the common page properties inherited by its layouts. + * + * Any other shapes on the master slide appear on all slides using that master, regardless of + * their layout. + */ + export interface Master { + getBackground(): PageBackground; + getColorScheme(): ColorScheme; + getGroups(): Group[]; + getImages(): Image[]; + getLayouts(): Layout[]; + getLines(): Line[]; + getObjectId(): string; + getPageElements(): PageElement[]; + getPageType(): PageType; + getPlaceholder(placeholderType: PlaceholderType): PageElement; + getPlaceholder(placeholderType: PlaceholderType, placeholderIndex: Integer): PageElement; + getPlaceholders(): PageElement[]; + getShapes(): Shape[]; + getSheetsCharts(): SheetsChart[]; + getTables(): Table[]; + getVideos(): Video[]; + getWordArts(): WordArt[]; + group(pageElements: PageElement[]): Group; + insertGroup(group: Group): Group; + insertImage(blobSource: Base.BlobSource): Image; + insertImage(blobSource: Base.BlobSource, left: Number, top: Number, width: Number, height: Number): Image; + insertImage(image: Image): Image; + insertImage(imageUrl: string): Image; + insertImage(imageUrl: string, left: Number, top: Number, width: Number, height: Number): Image; + insertLine(line: Line): Line; + insertLine(lineCategory: LineCategory, startLeft: Number, startTop: Number, endLeft: Number, endTop: Number): Line; + insertPageElement(pageElement: PageElement): PageElement; + insertShape(shape: Shape): Shape; + insertShape(shapeType: ShapeType): Shape; + insertShape(shapeType: ShapeType, left: Number, top: Number, width: Number, height: Number): Shape; + insertSheetsChart(sourceChart: Spreadsheet.EmbeddedChart): SheetsChart; + insertSheetsChart(sourceChart: Spreadsheet.EmbeddedChart, left: Number, top: Number, width: Number, height: Number): SheetsChart; + insertSheetsChart(sheetsChart: SheetsChart): SheetsChart; + insertSheetsChartAsImage(sourceChart: Spreadsheet.EmbeddedChart): Image; + insertSheetsChartAsImage(sourceChart: Spreadsheet.EmbeddedChart, left: Number, top: Number, width: Number, height: Number): Image; + insertTable(numRows: Integer, numColumns: Integer): Table; + insertTable(numRows: Integer, numColumns: Integer, left: Number, top: Number, width: Number, height: Number): Table; + insertTable(table: Table): Table; + insertVideo(videoUrl: string): Video; + insertVideo(videoUrl: string, left: Number, top: Number, width: Number, height: Number): Video; + insertVideo(video: Video): Video; + insertWordArt(wordArt: WordArt): WordArt; + remove(): void; + replaceAllText(findText: string, replaceText: string): Integer; + replaceAllText(findText: string, replaceText: string, matchCase: boolean): Integer; + selectAsCurrentPage(): void; + } + + /** + * A notes master in a presentation. + * + * Notes masters define the default text styles and page elements for all notes pages. Notes + * masters are read-only. + */ + export interface NotesMaster { + getGroups(): Group[]; + getImages(): Image[]; + getLines(): Line[]; + getObjectId(): string; + getPageElements(): PageElement[]; + getPlaceholder(placeholderType: PlaceholderType): PageElement; + getPlaceholder(placeholderType: PlaceholderType, placeholderIndex: Integer): PageElement; + getPlaceholders(): PageElement[]; + getShapes(): Shape[]; + getSheetsCharts(): SheetsChart[]; + getTables(): Table[]; + getVideos(): Video[]; + getWordArts(): WordArt[]; + } + + /** + * A notes page in a presentation. + * + * These pages contain the content for presentation handouts, including a a shape that contains + * the slide's speaker notes. Each slide has one corresponding notes page. Only the text in the + * speaker notes shape can be modified. + */ + export interface NotesPage { + getGroups(): Group[]; + getImages(): Image[]; + getLines(): Line[]; + getObjectId(): string; + getPageElements(): PageElement[]; + getPlaceholder(placeholderType: PlaceholderType): PageElement; + getPlaceholder(placeholderType: PlaceholderType, placeholderIndex: Integer): PageElement; + getPlaceholders(): PageElement[]; + getShapes(): Shape[]; + getSheetsCharts(): SheetsChart[]; + getSpeakerNotesShape(): Shape; + getTables(): Table[]; + getVideos(): Video[]; + getWordArts(): WordArt[]; + replaceAllText(findText: string, replaceText: string): Integer; + replaceAllText(findText: string, replaceText: string, matchCase: boolean): Integer; + } + + /** + * A page in a presentation. + */ + export interface Page { + asLayout(): Layout; + asMaster(): Master; + asSlide(): Slide; + getBackground(): PageBackground; + getColorScheme(): ColorScheme; + getGroups(): Group[]; + getImages(): Image[]; + getLines(): Line[]; + getObjectId(): string; + getPageElements(): PageElement[]; + getPageType(): PageType; + getPlaceholder(placeholderType: PlaceholderType): PageElement; + getPlaceholder(placeholderType: PlaceholderType, placeholderIndex: Integer): PageElement; + getPlaceholders(): PageElement[]; + getShapes(): Shape[]; + getSheetsCharts(): SheetsChart[]; + getTables(): Table[]; + getVideos(): Video[]; + getWordArts(): WordArt[]; + group(pageElements: PageElement[]): Group; + insertGroup(group: Group): Group; + insertImage(blobSource: Base.BlobSource): Image; + insertImage(blobSource: Base.BlobSource, left: Number, top: Number, width: Number, height: Number): Image; + insertImage(image: Image): Image; + insertImage(imageUrl: string): Image; + insertImage(imageUrl: string, left: Number, top: Number, width: Number, height: Number): Image; + insertLine(line: Line): Line; + insertLine(lineCategory: LineCategory, startLeft: Number, startTop: Number, endLeft: Number, endTop: Number): Line; + insertPageElement(pageElement: PageElement): PageElement; + insertShape(shape: Shape): Shape; + insertShape(shapeType: ShapeType): Shape; + insertShape(shapeType: ShapeType, left: Number, top: Number, width: Number, height: Number): Shape; + insertSheetsChart(sourceChart: Spreadsheet.EmbeddedChart): SheetsChart; + insertSheetsChart(sourceChart: Spreadsheet.EmbeddedChart, left: Number, top: Number, width: Number, height: Number): SheetsChart; + insertSheetsChart(sheetsChart: SheetsChart): SheetsChart; + insertSheetsChartAsImage(sourceChart: Spreadsheet.EmbeddedChart): Image; + insertSheetsChartAsImage(sourceChart: Spreadsheet.EmbeddedChart, left: Number, top: Number, width: Number, height: Number): Image; + insertTable(numRows: Integer, numColumns: Integer): Table; + insertTable(numRows: Integer, numColumns: Integer, left: Number, top: Number, width: Number, height: Number): Table; + insertTable(table: Table): Table; + insertVideo(videoUrl: string): Video; + insertVideo(videoUrl: string, left: Number, top: Number, width: Number, height: Number): Video; + insertVideo(video: Video): Video; + insertWordArt(wordArt: WordArt): WordArt; + remove(): void; + replaceAllText(findText: string, replaceText: string): Integer; + replaceAllText(findText: string, replaceText: string, matchCase: boolean): Integer; + selectAsCurrentPage(): void; + } + + /** + * Describes the page's background + */ + export interface PageBackground { + getPictureFill(): PictureFill; + getSolidFill(): SolidFill; + getType(): PageBackgroundType; + isVisible(): boolean; + setPictureFill(blobSource: Base.BlobSource): void; + setPictureFill(imageUrl: string): void; + setSolidFill(color: Color): void; + setSolidFill(color: Color, alpha: Number): void; + setSolidFill(red: Integer, green: Integer, blue: Integer): void; + setSolidFill(red: Integer, green: Integer, blue: Integer, alpha: Number): void; + setSolidFill(hexString: string): void; + setSolidFill(hexString: string, alpha: Number): void; + setSolidFill(color: ThemeColorType): void; + setSolidFill(color: ThemeColorType, alpha: Number): void; + setTransparent(): void; + } + + /** + * The kinds of page backgrounds. + */ + export enum PageBackgroundType { UNSUPPORTED, NONE, SOLID, PICTURE } + + /** + * A visual element rendered on a page. + */ + export interface PageElement { + alignOnPage(alignmentPosition: AlignmentPosition): PageElement; + asGroup(): Group; + asImage(): Image; + asLine(): Line; + asShape(): Shape; + asSheetsChart(): SheetsChart; + asTable(): Table; + asVideo(): Video; + asWordArt(): WordArt; + duplicate(): PageElement; + getDescription(): string; + getHeight(): Number; + getInherentHeight(): Number; + getInherentWidth(): Number; + getLeft(): Number; + getObjectId(): string; + getPageElementType(): PageElementType; + getParentGroup(): Group; + getParentPage(): Page; + getRotation(): Number; + getTitle(): string; + getTop(): Number; + getTransform(): AffineTransform; + getWidth(): Number; + preconcatenateTransform(transform: AffineTransform): PageElement; + remove(): void; + scaleHeight(ratio: Number): PageElement; + scaleWidth(ratio: Number): PageElement; + select(): void; + select(replace: boolean): void; + setHeight(height: Number): PageElement; + setLeft(left: Number): PageElement; + setRotation(angle: Number): PageElement; + setTop(top: Number): PageElement; + setTransform(transform: AffineTransform): PageElement; + setWidth(width: Number): PageElement; + } + + /** + * A collection of one or more PageElement instances. + */ + export interface PageElementRange { + getPageElements(): PageElement[]; + } + + /** + * The page element type. + */ + export enum PageElementType { UNSUPPORTED, SHAPE, IMAGE, VIDEO, TABLE, GROUP, LINE, WORD_ART, SHEETS_CHART } + + /** + * A collection of one or more Page instances. + */ + export interface PageRange { + getPages(): Page[]; + } + + /** + * The page types. + */ + export enum PageType { UNSUPPORTED, SLIDE, LAYOUT, MASTER } + + /** + * A segment of text terminated by a newline character. + */ + export interface Paragraph { + getIndex(): Integer; + getRange(): TextRange; + } + + /** + * The types of text alignment for a paragraph. + */ + export enum ParagraphAlignment { UNSUPPORTED, START, CENTER, END, JUSTIFIED } + + /** + * The styles of text that apply to entire paragraphs. + * + * Read methods in this class return null if the corresponding TextRange spans + * multiple paragraphs, and those paragraphs have different values for the read method being called. + * To avoid this, query for paragraph styles using the TextRange returned by the Paragraph.getRange() method. + */ + export interface ParagraphStyle { + getIndentEnd(): Number; + getIndentFirstLine(): Number; + getIndentStart(): Number; + getLineSpacing(): Number; + getParagraphAlignment(): ParagraphAlignment; + getSpaceAbove(): Number; + getSpaceBelow(): Number; + getSpacingMode(): SpacingMode; + getTextDirection(): TextDirection; + setIndentEnd(indent: Number): ParagraphStyle; + setIndentFirstLine(indent: Number): ParagraphStyle; + setIndentStart(indent: Number): ParagraphStyle; + setLineSpacing(spacing: Number): ParagraphStyle; + setParagraphAlignment(alignment: ParagraphAlignment): ParagraphStyle; + setSpaceAbove(space: Number): ParagraphStyle; + setSpaceBelow(space: Number): ParagraphStyle; + setSpacingMode(mode: SpacingMode): ParagraphStyle; + setTextDirection(direction: TextDirection): ParagraphStyle; + } + + /** + * A fill that renders an image that's stretched to the dimensions of its container. + */ + export interface PictureFill { + getContentUrl(): string; + getSourceUrl(): string; + } + + /** + * The placeholder types. Many of these placeholder types correspond to placeholder IDs from the + * ECMA-376 standard. More information on those shapes can be found in the description of the + * "ST_PlaceholderType" type in section 19.7.10 of "Office Open XML File Formats - Fundamentals and + * Markup Language Reference", part 1 of ECMA-376 5th + * edition. + */ + export enum PlaceholderType { UNSUPPORTED, NONE, BODY, CHART, CLIP_ART, CENTERED_TITLE, DIAGRAM, DATE_AND_TIME, FOOTER, HEADER, MEDIA, OBJECT, PICTURE, SLIDE_NUMBER, SUBTITLE, TABLE, TITLE, SLIDE_IMAGE } + + /** + * A point representing a location. + */ + export interface Point { + getX(): Number; + getY(): Number; + } + + /** + * Predefined layouts. These are commonly found layouts in presentations. However, there is no + * guarantee that these layouts are present in the current master as they could have been deleted or + * not part of the used theme. Additionally, the placeholders on each layout may have been changed. + */ + export enum PredefinedLayout { UNSUPPORTED, BLANK, CAPTION_ONLY, TITLE, TITLE_AND_BODY, TITLE_AND_TWO_COLUMNS, TITLE_ONLY, SECTION_HEADER, SECTION_TITLE_AND_DESCRIPTION, ONE_COLUMN_TEXT, MAIN_POINT, BIG_NUMBER } + + /** + * A presentation. + */ + export interface Presentation { + addEditor(emailAddress: string): Presentation; + addEditor(user: Base.User): Presentation; + addEditors(emailAddresses: String[]): Presentation; + addViewer(emailAddress: string): Presentation; + addViewer(user: Base.User): Presentation; + addViewers(emailAddresses: String[]): Presentation; + appendSlide(): Slide; + appendSlide(layout: Layout): Slide; + appendSlide(predefinedLayout: PredefinedLayout): Slide; + appendSlide(slide: Slide): Slide; + getEditors(): Base.User[]; + getId(): string; + getLayouts(): Layout[]; + getMasters(): Master[]; + getName(): string; + getNotesMaster(): NotesMaster; + getNotesPageHeight(): Number; + getNotesPageWidth(): Number; + getPageHeight(): Number; + getPageWidth(): Number; + getSelection(): Selection; + getSlides(): Slide[]; + getUrl(): string; + getViewers(): Base.User[]; + insertSlide(insertionIndex: Integer): Slide; + insertSlide(insertionIndex: Integer, layout: Layout): Slide; + insertSlide(insertionIndex: Integer, predefinedLayout: PredefinedLayout): Slide; + insertSlide(insertionIndex: Integer, slide: Slide): Slide; + removeEditor(emailAddress: string): Presentation; + removeEditor(user: Base.User): Presentation; + removeViewer(emailAddress: string): Presentation; + removeViewer(user: Base.User): Presentation; + replaceAllText(findText: string, replaceText: string): Integer; + replaceAllText(findText: string, replaceText: string, matchCase: boolean): Integer; + saveAndClose(): void; + setName(name: string): void; + } + + /** + * A color defined by red, green, blue color channels. + */ + export interface RgbColor { + asHexString(): string; + getBlue(): Integer; + getColorType(): ColorType; + getGreen(): Integer; + getRed(): Integer; + } + + /** + * The user's selection in the active presentation. + * + * var selection = SlidesApp.getActivePresentation().getSelection(); + * var currentPage = selection.getCurrentPage(); + * var selectionType = selection.getSelectionType(); + * } + */ + export interface Selection { + getCurrentPage(): Page; + getPageElementRange(): PageElementRange; + getPageRange(): PageRange; + getSelectionType(): SelectionType; + getTableCellRange(): TableCellRange; + getTextRange(): TextRange; + } + + /** + * Type of Selection. + * + * The SelectionType represents the most specific type of one or more objects that are + * selected. As an example if one or more TableCell instances are selected in a Table, the selection type is SelectionType.TABLE_CELL. The TableCellRange can be + * retrieved by using the Selection.getTableCellRange. The Table can be retrieved by + * using the Selection.getPageElementRange and the Page can be retrieved from the + * Selection.getCurrentPage. + */ + export enum SelectionType { UNSUPPORTED, NONE, TEXT, TABLE_CELL, PAGE, PAGE_ELEMENT, CURRENT_PAGE } + + /** + * A PageElement representing a generic shape that does not have a more specific + * classification. Includes text boxes, rectangles, and other predefined shapes. + */ + export interface Shape { + alignOnPage(alignmentPosition: AlignmentPosition): Shape; + duplicate(): PageElement; + getBorder(): Border; + getContentAlignment(): ContentAlignment; + getDescription(): string; + getFill(): Fill; + getHeight(): Number; + getInherentHeight(): Number; + getInherentWidth(): Number; + getLeft(): Number; + getLink(): Link; + getObjectId(): string; + getPageElementType(): PageElementType; + getParentGroup(): Group; + getParentPage(): Page; + getParentPlaceholder(): PageElement; + getPlaceholderIndex(): Integer; + getPlaceholderType(): PlaceholderType; + getRotation(): Number; + getShapeType(): ShapeType; + getText(): TextRange; + getTitle(): string; + getTop(): Number; + getTransform(): AffineTransform; + getWidth(): Number; + preconcatenateTransform(transform: AffineTransform): Shape; + remove(): void; + removeLink(): void; + replaceWithImage(blobSource: Base.BlobSource): Image; + replaceWithImage(blobSource: Base.BlobSource, crop: boolean): Image; + replaceWithImage(imageUrl: string): Image; + replaceWithImage(imageUrl: string, crop: boolean): Image; + replaceWithSheetsChart(sourceChart: Spreadsheet.EmbeddedChart): SheetsChart; + replaceWithSheetsChartAsImage(sourceChart: Spreadsheet.EmbeddedChart): Image; + scaleHeight(ratio: Number): Shape; + scaleWidth(ratio: Number): Shape; + select(): void; + select(replace: boolean): void; + setContentAlignment(contentAlignment: ContentAlignment): Shape; + setHeight(height: Number): Shape; + setLeft(left: Number): Shape; + setLinkSlide(slideIndex: Integer): Link; + setLinkSlide(slide: Slide): Link; + setLinkSlide(slidePosition: SlidePosition): Link; + setLinkUrl(url: string): Link; + setRotation(angle: Number): Shape; + setTop(top: Number): Shape; + setTransform(transform: AffineTransform): Shape; + setWidth(width: Number): Shape; + } + + /** + * The shape types. Many of these shapes correspond to predefined shapes from the ECMA-376 standard. + * More information on those shapes can be found in the description of the "ST_ShapeType" simple + * type in section 20.1.10.55 of "Office Open XML File Formats - Fundamentals and Markup Language + * Reference", part 1 of ECMA-376 4th + * edition. + */ + export enum ShapeType { UNSUPPORTED, TEXT_BOX, RECTANGLE, ROUND_RECTANGLE, ELLIPSE, ARC, BENT_ARROW, BENT_UP_ARROW, BEVEL, BLOCK_ARC, BRACE_PAIR, BRACKET_PAIR, CAN, CHEVRON, CHORD, CLOUD, CORNER, CUBE, CURVED_DOWN_ARROW, CURVED_LEFT_ARROW, CURVED_RIGHT_ARROW, CURVED_UP_ARROW, DECAGON, DIAGONAL_STRIPE, DIAMOND, DODECAGON, DONUT, DOUBLE_WAVE, DOWN_ARROW, DOWN_ARROW_CALLOUT, FOLDED_CORNER, FRAME, HALF_FRAME, HEART, HEPTAGON, HEXAGON, HOME_PLATE, HORIZONTAL_SCROLL, IRREGULAR_SEAL_1, IRREGULAR_SEAL_2, LEFT_ARROW, LEFT_ARROW_CALLOUT, LEFT_BRACE, LEFT_BRACKET, LEFT_RIGHT_ARROW, LEFT_RIGHT_ARROW_CALLOUT, LEFT_RIGHT_UP_ARROW, LEFT_UP_ARROW, LIGHTNING_BOLT, MATH_DIVIDE, MATH_EQUAL, MATH_MINUS, MATH_MULTIPLY, MATH_NOT_EQUAL, MATH_PLUS, MOON, NO_SMOKING, NOTCHED_RIGHT_ARROW, OCTAGON, PARALLELOGRAM, PENTAGON, PIE, PLAQUE, PLUS, QUAD_ARROW, QUAD_ARROW_CALLOUT, RIBBON, RIBBON_2, RIGHT_ARROW, RIGHT_ARROW_CALLOUT, RIGHT_BRACE, RIGHT_BRACKET, ROUND_1_RECTANGLE, ROUND_2_DIAGONAL_RECTANGLE, ROUND_2_SAME_RECTANGLE, RIGHT_TRIANGLE, SMILEY_FACE, SNIP_1_RECTANGLE, SNIP_2_DIAGONAL_RECTANGLE, SNIP_2_SAME_RECTANGLE, SNIP_ROUND_RECTANGLE, STAR_10, STAR_12, STAR_16, STAR_24, STAR_32, STAR_4, STAR_5, STAR_6, STAR_7, STAR_8, STRIPED_RIGHT_ARROW, SUN, TRAPEZOID, TRIANGLE, UP_ARROW, UP_ARROW_CALLOUT, UP_DOWN_ARROW, UTURN_ARROW, VERTICAL_SCROLL, WAVE, WEDGE_ELLIPSE_CALLOUT, WEDGE_RECTANGLE_CALLOUT, WEDGE_ROUND_RECTANGLE_CALLOUT, FLOW_CHART_ALTERNATE_PROCESS, FLOW_CHART_COLLATE, FLOW_CHART_CONNECTOR, FLOW_CHART_DECISION, FLOW_CHART_DELAY, FLOW_CHART_DISPLAY, FLOW_CHART_DOCUMENT, FLOW_CHART_EXTRACT, FLOW_CHART_INPUT_OUTPUT, FLOW_CHART_INTERNAL_STORAGE, FLOW_CHART_MAGNETIC_DISK, FLOW_CHART_MAGNETIC_DRUM, FLOW_CHART_MAGNETIC_TAPE, FLOW_CHART_MANUAL_INPUT, FLOW_CHART_MANUAL_OPERATION, FLOW_CHART_MERGE, FLOW_CHART_MULTIDOCUMENT, FLOW_CHART_OFFLINE_STORAGE, FLOW_CHART_OFFPAGE_CONNECTOR, FLOW_CHART_ONLINE_STORAGE, FLOW_CHART_OR, FLOW_CHART_PREDEFINED_PROCESS, FLOW_CHART_PREPARATION, FLOW_CHART_PROCESS, FLOW_CHART_PUNCHED_CARD, FLOW_CHART_PUNCHED_TAPE, FLOW_CHART_SORT, FLOW_CHART_SUMMING_JUNCTION, FLOW_CHART_TERMINATOR, ARROW_EAST, ARROW_NORTH_EAST, ARROW_NORTH, SPEECH, STARBURST, TEARDROP, ELLIPSE_RIBBON, ELLIPSE_RIBBON_2, CLOUD_CALLOUT, CUSTOM } + + /** + * A PageElement representing a linked chart embedded from Google Sheets. + */ + export interface SheetsChart { + alignOnPage(alignmentPosition: AlignmentPosition): SheetsChart; + asImage(): Image; + duplicate(): PageElement; + getChartId(): Integer; + getDescription(): string; + getEmbedType(): SheetsChartEmbedType; + getHeight(): Number; + getInherentHeight(): Number; + getInherentWidth(): Number; + getLeft(): Number; + getLink(): Link; + getObjectId(): string; + getPageElementType(): PageElementType; + getParentGroup(): Group; + getParentPage(): Page; + getRotation(): Number; + getSpreadsheetId(): string; + getTitle(): string; + getTop(): Number; + getTransform(): AffineTransform; + getWidth(): Number; + preconcatenateTransform(transform: AffineTransform): SheetsChart; + refresh(): void; + remove(): void; + removeLink(): void; + scaleHeight(ratio: Number): SheetsChart; + scaleWidth(ratio: Number): SheetsChart; + select(): void; + select(replace: boolean): void; + setHeight(height: Number): SheetsChart; + setLeft(left: Number): SheetsChart; + setLinkSlide(slideIndex: Integer): Link; + setLinkSlide(slide: Slide): Link; + setLinkSlide(slidePosition: SlidePosition): Link; + setLinkUrl(url: string): Link; + setRotation(angle: Number): SheetsChart; + setTop(top: Number): SheetsChart; + setTransform(transform: AffineTransform): SheetsChart; + setWidth(width: Number): SheetsChart; + } + + /** + * The Sheets chart's embed type. + */ + export enum SheetsChartEmbedType { UNSUPPORTED, IMAGE } + + /** + * A slide in a presentation. + * + * These pages contain the content you are presenting to your audience. Most slides are based on + * a master and a layout. You can specify which layout to use for each slide when it is created. + */ + export interface Slide { + duplicate(): Slide; + getBackground(): PageBackground; + getColorScheme(): ColorScheme; + getGroups(): Group[]; + getImages(): Image[]; + getLayout(): Layout; + getLines(): Line[]; + getNotesPage(): NotesPage; + getObjectId(): string; + getPageElements(): PageElement[]; + getPageType(): PageType; + getPlaceholder(placeholderType: PlaceholderType): PageElement; + getPlaceholder(placeholderType: PlaceholderType, placeholderIndex: Integer): PageElement; + getPlaceholders(): PageElement[]; + getShapes(): Shape[]; + getSheetsCharts(): SheetsChart[]; + getTables(): Table[]; + getVideos(): Video[]; + getWordArts(): WordArt[]; + group(pageElements: PageElement[]): Group; + insertGroup(group: Group): Group; + insertImage(blobSource: Base.BlobSource): Image; + insertImage(blobSource: Base.BlobSource, left: Number, top: Number, width: Number, height: Number): Image; + insertImage(image: Image): Image; + insertImage(imageUrl: string): Image; + insertImage(imageUrl: string, left: Number, top: Number, width: Number, height: Number): Image; + insertLine(line: Line): Line; + insertLine(lineCategory: LineCategory, startLeft: Number, startTop: Number, endLeft: Number, endTop: Number): Line; + insertPageElement(pageElement: PageElement): PageElement; + insertShape(shape: Shape): Shape; + insertShape(shapeType: ShapeType): Shape; + insertShape(shapeType: ShapeType, left: Number, top: Number, width: Number, height: Number): Shape; + insertSheetsChart(sourceChart: Spreadsheet.EmbeddedChart): SheetsChart; + insertSheetsChart(sourceChart: Spreadsheet.EmbeddedChart, left: Number, top: Number, width: Number, height: Number): SheetsChart; + insertSheetsChart(sheetsChart: SheetsChart): SheetsChart; + insertSheetsChartAsImage(sourceChart: Spreadsheet.EmbeddedChart): Image; + insertSheetsChartAsImage(sourceChart: Spreadsheet.EmbeddedChart, left: Number, top: Number, width: Number, height: Number): Image; + insertTable(numRows: Integer, numColumns: Integer): Table; + insertTable(numRows: Integer, numColumns: Integer, left: Number, top: Number, width: Number, height: Number): Table; + insertTable(table: Table): Table; + insertVideo(videoUrl: string): Video; + insertVideo(videoUrl: string, left: Number, top: Number, width: Number, height: Number): Video; + insertVideo(video: Video): Video; + insertWordArt(wordArt: WordArt): WordArt; + move(index: Integer): void; + remove(): void; + replaceAllText(findText: string, replaceText: string): Integer; + replaceAllText(findText: string, replaceText: string, matchCase: boolean): Integer; + selectAsCurrentPage(): void; + } + + /** + * The relative position of a Slide. + */ + export enum SlidePosition { NEXT_SLIDE, PREVIOUS_SLIDE, FIRST_SLIDE, LAST_SLIDE } + + /** + * Creates and opens Presentations that can be edited. + * + * // Open a presentation by ID. + * var preso = SlidesApp.openById('PRESENTATION_ID_GOES_HERE'); + * + * // Create and open a presentation. + * preso = SlidesApp.create('Presentation Name'); + */ + export interface SlidesApp { + AlignmentPosition: typeof AlignmentPosition; + ArrowStyle: typeof ArrowStyle; + AutoTextType: typeof AutoTextType; + CellMergeState: typeof CellMergeState; + ColorType: typeof ColorType; + ContentAlignment: typeof ContentAlignment; + DashStyle: typeof DashStyle; + FillType: typeof FillType; + LineCategory: typeof LineCategory; + LineFillType: typeof LineFillType; + LineType: typeof LineType; + LinkType: typeof LinkType; + ListPreset: typeof ListPreset; + PageBackgroundType: typeof PageBackgroundType; + PageElementType: typeof PageElementType; + PageType: typeof PageType; + ParagraphAlignment: typeof ParagraphAlignment; + PlaceholderType: typeof PlaceholderType; + PredefinedLayout: typeof PredefinedLayout; + SelectionType: typeof SelectionType; + ShapeType: typeof ShapeType; + SheetsChartEmbedType: typeof SheetsChartEmbedType; + SlidePosition: typeof SlidePosition; + SpacingMode: typeof SpacingMode; + TextBaselineOffset: typeof TextBaselineOffset; + TextDirection: typeof TextDirection; + ThemeColorType: typeof ThemeColorType; + VideoSourceType: typeof VideoSourceType; + create(name: string): Presentation; + getActivePresentation(): Presentation; + getUi(): Base.Ui; + newAffineTransformBuilder(): AffineTransformBuilder; + openById(id: string): Presentation; + openByUrl(url: string): Presentation; + } + + /** + * A solid color fill. + * + * SolidFill objects are detached and immutable, so do not reflect changes made after + * they have been created. + */ + export interface SolidFill { + getAlpha(): Number; + getColor(): Color; + } + + /** + * The different modes for paragraph spacing. + */ + export enum SpacingMode { UNSUPPORTED, NEVER_COLLAPSE, COLLAPSE_LISTS } + + /** + * A PageElement representing a table. + */ + export interface Table { + alignOnPage(alignmentPosition: AlignmentPosition): Table; + appendColumn(): TableColumn; + appendRow(): TableRow; + duplicate(): PageElement; + getCell(rowIndex: Integer, columnIndex: Integer): TableCell; + getColumn(columnIndex: Integer): TableColumn; + getDescription(): string; + getHeight(): Number; + getInherentHeight(): Number; + getInherentWidth(): Number; + getLeft(): Number; + getNumColumns(): Integer; + getNumRows(): Integer; + getObjectId(): string; + getPageElementType(): PageElementType; + getParentGroup(): Group; + getParentPage(): Page; + getRotation(): Number; + getRow(rowIndex: Integer): TableRow; + getTitle(): string; + getTop(): Number; + getTransform(): AffineTransform; + getWidth(): Number; + insertColumn(index: Integer): TableColumn; + insertRow(index: Integer): TableRow; + preconcatenateTransform(transform: AffineTransform): Table; + remove(): void; + scaleHeight(ratio: Number): Table; + scaleWidth(ratio: Number): Table; + select(): void; + select(replace: boolean): void; + setHeight(height: Number): Table; + setLeft(left: Number): Table; + setRotation(angle: Number): Table; + setTop(top: Number): Table; + setTransform(transform: AffineTransform): Table; + setWidth(width: Number): Table; + } + + /** + * A cell in a table. + */ + export interface TableCell { + getColumnIndex(): Integer; + getColumnSpan(): Integer; + getContentAlignment(): ContentAlignment; + getFill(): Fill; + getHeadCell(): TableCell; + getMergeState(): CellMergeState; + getParentColumn(): TableColumn; + getParentRow(): TableRow; + getParentTable(): Table; + getRowIndex(): Integer; + getRowSpan(): Integer; + getText(): TextRange; + setContentAlignment(contentAlignment: ContentAlignment): TableCell; + } + + /** + * A collection of one or more TableCell instances. + */ + export interface TableCellRange { + getTableCells(): TableCell[]; + } + + /** + * A column in a table. A column consists of a list of table cells. A column is identified by the + * column index. + */ + export interface TableColumn { + getCell(cellIndex: Integer): TableCell; + getIndex(): Integer; + getNumCells(): Integer; + getParentTable(): Table; + getWidth(): Number; + remove(): void; + } + + /** + * A row in a table. A row consists of a list of table cells. A row is identified by the row index. + */ + export interface TableRow { + getCell(cellIndex: Integer): TableCell; + getIndex(): Integer; + getMinimumHeight(): Number; + getNumCells(): Integer; + getParentTable(): Table; + remove(): void; + } + + /** + * The text vertical offset from its normal position. + */ + export enum TextBaselineOffset { UNSUPPORTED, NONE, SUPERSCRIPT, SUBSCRIPT } + + /** + * The directions text can flow in. + */ + export enum TextDirection { UNSUPPORTED, LEFT_TO_RIGHT, RIGHT_TO_LEFT } + + /** + * A segment of the text contents of a Shape or a TableCell. + */ + export interface TextRange { + appendParagraph(text: string): Paragraph; + appendRange(textRange: TextRange): TextRange; + appendRange(textRange: TextRange, matchSourceFormatting: boolean): TextRange; + appendText(text: string): TextRange; + asRenderedString(): string; + asString(): string; + clear(): void; + clear(startOffset: Integer, endOffset: Integer): void; + find(pattern: string): TextRange[]; + find(pattern: string, startOffset: Integer): TextRange[]; + getAutoTexts(): AutoText[]; + getEndIndex(): Integer; + getLength(): Integer; + getLinks(): TextRange[]; + getListParagraphs(): Paragraph[]; + getListStyle(): ListStyle; + getParagraphStyle(): ParagraphStyle; + getParagraphs(): Paragraph[]; + getRange(startOffset: Integer, endOffset: Integer): TextRange; + getRuns(): TextRange[]; + getStartIndex(): Integer; + getTextStyle(): TextStyle; + insertParagraph(startOffset: Integer, text: string): Paragraph; + insertRange(startOffset: Integer, textRange: TextRange): TextRange; + insertRange(startOffset: Integer, textRange: TextRange, matchSourceFormatting: boolean): TextRange; + insertText(startOffset: Integer, text: string): TextRange; + isEmpty(): boolean; + replaceAllText(findText: string, replaceText: string): Integer; + replaceAllText(findText: string, replaceText: string, matchCase: boolean): Integer; + select(): void; + setText(newText: string): TextRange; + } + + /** + * The style of text. + * + * Read methods in this class return null if the corresponding TextRange spans + * multiple text runs, and those runs have different values for the read method being called. To + * avoid this, query for text styles using the TextRanges returned by the TextRange.getRuns() method. + */ + export interface TextStyle { + getBackgroundColor(): Color; + getBaselineOffset(): TextBaselineOffset; + getFontFamily(): string; + getFontSize(): Number; + getFontWeight(): Integer; + getForegroundColor(): Color; + getLink(): Link; + hasLink(): boolean; + isBackgroundTransparent(): boolean; + isBold(): boolean; + isItalic(): boolean; + isSmallCaps(): boolean; + isStrikethrough(): boolean; + isUnderline(): boolean; + removeLink(): TextStyle; + setBackgroundColor(color: Color): TextStyle; + setBackgroundColor(red: Integer, green: Integer, blue: Integer): TextStyle; + setBackgroundColor(hexColor: string): TextStyle; + setBackgroundColor(color: ThemeColorType): TextStyle; + setBackgroundColorTransparent(): TextStyle; + setBaselineOffset(offset: TextBaselineOffset): TextStyle; + setBold(bold: boolean): TextStyle; + setFontFamily(fontFamily: string): TextStyle; + setFontFamilyAndWeight(fontFamily: string, fontWeight: Integer): TextStyle; + setFontSize(fontSize: Number): TextStyle; + setForegroundColor(foregroundColor: Color): TextStyle; + setForegroundColor(red: Integer, green: Integer, blue: Integer): TextStyle; + setForegroundColor(hexColor: string): TextStyle; + setForegroundColor(color: ThemeColorType): TextStyle; + setItalic(italic: boolean): TextStyle; + setLinkSlide(slideIndex: Integer): TextStyle; + setLinkSlide(slide: Slide): TextStyle; + setLinkSlide(slidePosition: SlidePosition): TextStyle; + setLinkUrl(url: string): TextStyle; + setSmallCaps(smallCaps: boolean): TextStyle; + setStrikethrough(strikethrough: boolean): TextStyle; + setUnderline(underline: boolean): TextStyle; + } + + /** + * A color that refers to an entry in the page's ColorScheme. + */ + export interface ThemeColor { + getColorType(): ColorType; + getThemeColorType(): ThemeColorType; + } + + /** + * The name of an entry in the page's color scheme. + */ + export enum ThemeColorType { UNSUPPORTED, DARK1, LIGHT1, DARK2, LIGHT2, ACCENT1, ACCENT2, ACCENT3, ACCENT4, ACCENT5, ACCENT6, HYPERLINK, FOLLOWED_HYPERLINK } + + /** + * A PageElement representing a video. + */ + export interface Video { + alignOnPage(alignmentPosition: AlignmentPosition): Video; + duplicate(): PageElement; + getBorder(): Border; + getDescription(): string; + getHeight(): Number; + getInherentHeight(): Number; + getInherentWidth(): Number; + getLeft(): Number; + getObjectId(): string; + getPageElementType(): PageElementType; + getParentGroup(): Group; + getParentPage(): Page; + getRotation(): Number; + getSource(): VideoSourceType; + getThumbnailUrl(): string; + getTitle(): string; + getTop(): Number; + getTransform(): AffineTransform; + getUrl(): string; + getVideoId(): string; + getWidth(): Number; + preconcatenateTransform(transform: AffineTransform): Video; + remove(): void; + scaleHeight(ratio: Number): Video; + scaleWidth(ratio: Number): Video; + select(): void; + select(replace: boolean): void; + setHeight(height: Number): Video; + setLeft(left: Number): Video; + setRotation(angle: Number): Video; + setTop(top: Number): Video; + setTransform(transform: AffineTransform): Video; + setWidth(width: Number): Video; + } + + /** + * The video source types. + */ + export enum VideoSourceType { UNSUPPORTED, YOUTUBE } + + /** + * A PageElement representing word art. + */ + export interface WordArt { + alignOnPage(alignmentPosition: AlignmentPosition): WordArt; + duplicate(): PageElement; + getDescription(): string; + getHeight(): Number; + getInherentHeight(): Number; + getInherentWidth(): Number; + getLeft(): Number; + getLink(): Link; + getObjectId(): string; + getPageElementType(): PageElementType; + getParentGroup(): Group; + getParentPage(): Page; + getRenderedText(): string; + getRotation(): Number; + getTitle(): string; + getTop(): Number; + getTransform(): AffineTransform; + getWidth(): Number; + preconcatenateTransform(transform: AffineTransform): WordArt; + remove(): void; + removeLink(): void; + scaleHeight(ratio: Number): WordArt; + scaleWidth(ratio: Number): WordArt; + select(): void; + select(replace: boolean): void; + setHeight(height: Number): WordArt; + setLeft(left: Number): WordArt; + setLinkSlide(slideIndex: Integer): Link; + setLinkSlide(slide: Slide): Link; + setLinkSlide(slidePosition: SlidePosition): Link; + setLinkUrl(url: string): Link; + setRotation(angle: Number): WordArt; + setTop(top: Number): WordArt; + setTransform(transform: AffineTransform): WordArt; + setWidth(width: Number): WordArt; + } + + } +} + +declare var SlidesApp: GoogleAppsScript.Slides.SlidesApp; diff --git a/types/google-apps-script/index.d.ts b/types/google-apps-script/index.d.ts index 0e4ca164a9..df2cca1363 100644 --- a/types/google-apps-script/index.d.ts +++ b/types/google-apps-script/index.d.ts @@ -26,6 +26,7 @@ /// /// /// +/// /// /// /// From 2e531425dc21bb3a19e54232d3c7d8b5f150762d Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 26 Feb 2018 10:25:49 -0500 Subject: [PATCH 084/128] HelloJs: added display type, typed promise value return for login, typed return value GetAuthReponse (#23614) * - added display type - typed promise value return for login - typed return value GetAuthReponse * bumping version number for hellojs * fixed module declaration for unit tests * reverted last module declaration fixes * removed namespace declaration to pass linting * hellojs :put namespace declaration back and improved global var declaration * hellojs: removed the global definition as per recomendation of Andy --- types/hellojs/hellojs-tests.ts | 4 ---- types/hellojs/index.d.ts | 38 +++++++++++++++++++++++++++------- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/types/hellojs/hellojs-tests.ts b/types/hellojs/hellojs-tests.ts index e5b76d3ceb..4a4e068379 100644 --- a/types/hellojs/hellojs-tests.ts +++ b/types/hellojs/hellojs-tests.ts @@ -1,7 +1,3 @@ -import * as hello from 'hellojs'; - -// Test code copied from Azure AD B2C sample app at -// https://github.com/Azure-Samples/active-directory-b2c-javascript-hellojs-singlepageapp/tree/cd5982f09a7bff0a72b7b4e44c4b5190b09e20fa hello.init({ serviceName: { name: 'Test', diff --git a/types/hellojs/index.d.ts b/types/hellojs/index.d.ts index 16b19afb4a..e8efdaf19c 100644 --- a/types/hellojs/index.d.ts +++ b/types/hellojs/index.d.ts @@ -1,11 +1,13 @@ -// Type definitions for hello.js 1.15 +// Type definitions for hello.js 1.16 // Project: http://adodson.com/hello.js/ // Definitions by: Pavel Zika // Mikko Vuorinen +// Vincent Biret // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 export = hello; +export as namespace hello; declare const hello: hello.HelloJSStatic; @@ -53,9 +55,11 @@ declare namespace hello { type HelloJSTokenResponseType = "token" | "code"; + type HelloJSDisplayType = "popup" | "page" | "none"; + interface HelloJSLoginOptions { redirect_uri?: string; - display?: string; + display?: HelloJSDisplayType; scope?: string; response_type?: HelloJSTokenResponseType; force?: boolean | null; @@ -87,19 +91,39 @@ declare namespace hello { interface HelloJSEventArgument { network: string; - authResponse?: any; + authResponse?: HelloJSAuthResponse; + } + + interface HelloJSLoginEventArguement { + network: string; + authResponse?: HelloJSAuthResponse; + error?: Error; + } + + interface HelloJSAuthResponse { + access_token?: string; + token_type?: string; + expires_in?: number; + id_token?: string; + state?: string; + session_state?: string; + network?: string; + display?: HelloJSDisplayType; + redirect_uri?: string; + scope?: string; + expires?: number; } interface HelloJSStatic extends HelloJSEvent { init(serviceAppIds: { [id: string]: string; }, options?: HelloJSLoginOptions): void; init(servicesDef: { [id: string]: HelloJSServiceDef; }): void; - login(callback: () => void): PromiseLike; - login(options?: HelloJSLoginOptions, callback?: () => void): PromiseLike; - login(network?: string, options?: HelloJSLoginOptions, callback?: () => void): PromiseLike; + login(callback: () => void): PromiseLike; + login(options?: HelloJSLoginOptions, callback?: () => void): PromiseLike; + login(network?: string, options?: HelloJSLoginOptions, callback?: () => void): PromiseLike; logout(callback?: () => void): PromiseLike; logout(options?: HelloJSLogoutOptions, callback?: () => void): PromiseLike; logout(network?: string, options?: HelloJSLogoutOptions, callback?: () => void): PromiseLike; - getAuthResponse(network?: string): any; + getAuthResponse(network?: string): HelloJSAuthResponse; settings: HelloJSLoginOptions; (network: string): HelloJSStatic; utils: HelloJSUtils; From fda3aeee066db68c0fedf8e4b8a30fc4b5466293 Mon Sep 17 00:00:00 2001 From: sgoll <1277035+sgoll@users.noreply.github.com> Date: Mon, 26 Feb 2018 17:15:46 +0100 Subject: [PATCH 085/128] [ramda] Add type for string-based reverse (#23927) * Add type for string-based reverse * Add test for string-based reverse * Use separate documentation for each overload --- types/ramda/index.d.ts | 4 ++++ types/ramda/ramda-tests.ts | 7 +++++++ 2 files changed, 11 insertions(+) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 108a12bf0e..205df9f569 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -1601,6 +1601,10 @@ declare namespace R { * Returns a new list with the same elements as the original list, just in the reverse order. */ reverse(list: ReadonlyArray): T[]; + /** + * Returns a new string with the characters in reverse order. + */ + reverse(str: string): string; /** * Scan is similar to reduce, but returns a list of successively reduced values from the left. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index eacb4558e3..8aef1c65fc 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -977,6 +977,13 @@ type Pair = KeyValuePair; R.reverse([]); // => [] }; +() => { + R.reverse('abc'); // => 'cba' + R.reverse('ab'); // => 'ba' + R.reverse('a'); // => 'a' + R.reverse(''); // => '' +}; + () => { const numbers = [1, 2, 3, 4]; R.scan(R.multiply, 1, numbers); // => [1, 1, 2, 6, 24] From fb314c384208f1d1780ef3c43dc20fd31a2a19a5 Mon Sep 17 00:00:00 2001 From: peszek90 <36853408+peszek90@users.noreply.github.com> Date: Mon, 26 Feb 2018 17:21:05 +0100 Subject: [PATCH 086/128] Add rotation to RegularShapeOptions (#23925) Add rotation to RegularShapeOptions --- types/openlayers/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index b7073bcda2..8a711771fa 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -14392,6 +14392,7 @@ declare module olx { angle?: number; snapToPixel?: boolean; stroke?: ol.style.Stroke; + rotation?: number; } From 3af269687caa7d34ad9482e7994eab626d7e676b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leo=20Vujani=C4=87?= Date: Mon, 26 Feb 2018 17:29:02 +0100 Subject: [PATCH 087/128] Type definitions for parity-poe 0.3 (#23903) * Added tslint and tsconfig * Added type definitions for Parity POE 0.3 * Added tests for type definitions * Removed unnecessarily reference 'node' which is already referenced in the type definition --- types/parity-poe/index.d.ts | 33 ++++++++++++++ types/parity-poe/parity-poe-tests.ts | 68 ++++++++++++++++++++++++++++ types/parity-poe/tsconfig.json | 23 ++++++++++ types/parity-poe/tslint.json | 1 + 4 files changed, 125 insertions(+) create mode 100644 types/parity-poe/index.d.ts create mode 100644 types/parity-poe/parity-poe-tests.ts create mode 100644 types/parity-poe/tsconfig.json create mode 100644 types/parity-poe/tslint.json diff --git a/types/parity-poe/index.d.ts b/types/parity-poe/index.d.ts new file mode 100644 index 0000000000..46ccf3291a --- /dev/null +++ b/types/parity-poe/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for Parity POE 0.3 +// Project: https://github.com/paritytrading/node-parity-poe +// Definitions by: Leo Vujanić +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +/** + * Declares Parity POE message structure + * Full reference can be found here https://github.com/paritytrading/parity/blob/master/libraries/net/doc/POE.md + */ +export interface POEMessage { + messageType: string; + orderId?: string; + timestamp?: number; + canceledQuantity?: number; + reason?: string; + liquidityFlag?: string; + matchNumber?: number; + side?: string; + instrument?: string; + quantity?: number; + price?: number; +} + +export function formatInbound(message: POEMessage): Buffer; + +export function parseInbound(buffer: Buffer): POEMessage; + +export function formatOutbound(message: POEMessage): Buffer; + +export function parseOutbound(buffer: Buffer): POEMessage; diff --git a/types/parity-poe/parity-poe-tests.ts b/types/parity-poe/parity-poe-tests.ts new file mode 100644 index 0000000000..c5b50d5189 --- /dev/null +++ b/types/parity-poe/parity-poe-tests.ts @@ -0,0 +1,68 @@ +import { formatInbound, parseInbound, formatOutbound, parseOutbound, POEMessage } from "parity-poe"; + +const buffer = new Buffer("test"); +const message: POEMessage = { + messageType: 'A' +}; + +/** + * formatInbound tests + */ + +// $ExpectType Buffer +formatInbound(message); + +// Invalid type +// $ExpectError +formatInbound(''); + +// $ExpectError +formatInbound({}); + +// Invalid sub type +// $ExpectError +formatInbound({ + messageType: 1 +}); + +/** + * parseInbound tests + */ + +// $ExpectType POEMessage +parseInbound(buffer); + +// Invalid type +// $ExpectError +parseInbound(''); + +/** + * formatOutbound tests + */ + +// $ExpectType Buffer +formatOutbound(message); + +// Invalid type +// $ExpectError +formatOutbound(''); + +// $ExpectError +formatOutbound({}); + +// Invalid sub type +// $ExpectError +formatOutbound({ + messageType: 1 +}); + +/** + * parseOutbound tests + */ + +// $ExpectType POEMessage +parseOutbound(buffer); + +// Invalid type +// $ExpectError +parseOutbound(''); diff --git a/types/parity-poe/tsconfig.json b/types/parity-poe/tsconfig.json new file mode 100644 index 0000000000..9dc0748761 --- /dev/null +++ b/types/parity-poe/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "parity-poe-tests.ts" + ] +} diff --git a/types/parity-poe/tslint.json b/types/parity-poe/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/parity-poe/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 67e122d7f6b3836d29324c0af11e35e87b2b2458 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leo=20Vujani=C4=87?= Date: Mon, 26 Feb 2018 17:29:35 +0100 Subject: [PATCH 088/128] Type definitions for parity-pmr 0.1 (#23902) * Added type definitions for parity-pmr 0.1 * Removed unnecessarily reference 'node' which is already referenced in the type definition --- types/parity-pmr/index.d.ts | 30 ++++++++++++++++++++++++++++ types/parity-pmr/parity-pmr-tests.ts | 29 +++++++++++++++++++++++++++ types/parity-pmr/tsconfig.json | 23 +++++++++++++++++++++ types/parity-pmr/tslint.json | 1 + 4 files changed, 83 insertions(+) create mode 100644 types/parity-pmr/index.d.ts create mode 100644 types/parity-pmr/parity-pmr-tests.ts create mode 100644 types/parity-pmr/tsconfig.json create mode 100644 types/parity-pmr/tslint.json diff --git a/types/parity-pmr/index.d.ts b/types/parity-pmr/index.d.ts new file mode 100644 index 0000000000..0e05da1d6e --- /dev/null +++ b/types/parity-pmr/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for parity-pmr 0.1 +// Project: https://github.com/paritytrading/node-parity-pmr#readme +// Definitions by: Leo Vujanić +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * Declares Parity PMR message structure + * Full reference can be found here https://github.com/paritytrading/parity/blob/master/libraries/net/doc/PMR.md + */ +export interface PMRMessage { + messageType: string; + version?: number; + timestamp?: number; + username?: string; + orderNumber?: string; + side?: string; + instrument?: string; + quantity?: number; + price?: number; + canceledQuantity?: number; + matchNumber?: number; + restingOrderNumber?: number; + incomingOrderNumber?: number; +} + +export function format(message: PMRMessage): Buffer; + +export function parse(buffer: Buffer): PMRMessage; diff --git a/types/parity-pmr/parity-pmr-tests.ts b/types/parity-pmr/parity-pmr-tests.ts new file mode 100644 index 0000000000..03bcc3534d --- /dev/null +++ b/types/parity-pmr/parity-pmr-tests.ts @@ -0,0 +1,29 @@ +import { format, parse, PMRMessage } from "parity-pmr"; + +const buffer = new Buffer("test"); +const message: PMRMessage = { + messageType: 'E' +}; + +// $ExpectType Buffer +format(message); + +// Invalid type +// $ExpectError +format(''); + +// $ExpectError +format({}); + +// Invalid sub type +// $ExpectError +format({ + messageType: 1 +}); + +// $ExpectType PMRMessage +parse(buffer); + +// Invalid type +// $ExpectError +parse(''); diff --git a/types/parity-pmr/tsconfig.json b/types/parity-pmr/tsconfig.json new file mode 100644 index 0000000000..e73825b582 --- /dev/null +++ b/types/parity-pmr/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "parity-pmr-tests.ts" + ] +} diff --git a/types/parity-pmr/tslint.json b/types/parity-pmr/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/parity-pmr/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 9d85a0c77340da9fd815aa18fbfb7c89cc0870f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vilim=20Stubi=C4=8Dan?= Date: Mon, 26 Feb 2018 17:31:11 +0100 Subject: [PATCH 089/128] Type definitions for parity-pmd 0.4.0 (#23901) * Type definitions for parity-pmd 0.4.0 * Contributors list update * Removed unnecessary reference to node --- types/parity-pmd/index.d.ts | 27 +++++++++++++++++++++++++++ types/parity-pmd/parity-pmd-tests.ts | 27 +++++++++++++++++++++++++++ types/parity-pmd/tsconfig.json | 23 +++++++++++++++++++++++ types/parity-pmd/tslint.json | 1 + 4 files changed, 78 insertions(+) create mode 100644 types/parity-pmd/index.d.ts create mode 100644 types/parity-pmd/parity-pmd-tests.ts create mode 100644 types/parity-pmd/tsconfig.json create mode 100644 types/parity-pmd/tslint.json diff --git a/types/parity-pmd/index.d.ts b/types/parity-pmd/index.d.ts new file mode 100644 index 0000000000..30b02d72ef --- /dev/null +++ b/types/parity-pmd/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for parity-pmd 0.4 +// Project: https://github.com/paritytrading/node-parity-pmd#readme +// Definitions by: Leonard Vujanić +// Vilim Stubičan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +/** + * Declares Parity PMD message structure + * Full reference can be found here https://github.com/paritytrading/parity/blob/master/libraries/net/doc/PMD.md + */ +export interface PMDMessage { + messageType: string; + version?: string; + timestamp?: number; + orderNumber?: number; + side?: string; + instrument?: string; + quantity?: number; + price?: number; +} + +export function format(message: PMDMessage): Buffer; + +export function parse(buffer: Buffer): PMDMessage; diff --git a/types/parity-pmd/parity-pmd-tests.ts b/types/parity-pmd/parity-pmd-tests.ts new file mode 100644 index 0000000000..3645e7598c --- /dev/null +++ b/types/parity-pmd/parity-pmd-tests.ts @@ -0,0 +1,27 @@ +import { format, parse, PMDMessage } from 'parity-pmd'; + +// Arrange +const buffer = new Buffer(5); +buffer.writeUInt8(0x56, 0); +buffer.writeUInt32BE(70, 1); +const parsedContent: PMDMessage = parse(buffer); + +// Act & Assert +// $ExpectType PMDMessage +parse(buffer); + +// $ExpectType Buffer +format(parsedContent); + +// Invalid type +// $ExpectError +parse(''); + +// $ExpectError +format({}); + +// Invalid sub type +// $ExpectError +format({ + messageType: 1 +}); diff --git a/types/parity-pmd/tsconfig.json b/types/parity-pmd/tsconfig.json new file mode 100644 index 0000000000..92345f62fb --- /dev/null +++ b/types/parity-pmd/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "parity-pmd-tests.ts" + ] +} diff --git a/types/parity-pmd/tslint.json b/types/parity-pmd/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/parity-pmd/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 66ddd925606c1774b62009726b08b5ab66b3b5da Mon Sep 17 00:00:00 2001 From: Dmitry Guketlev Date: Mon, 26 Feb 2018 19:31:50 +0300 Subject: [PATCH 090/128] Add typings for forever agent (#23900) --- types/forever-agent/forever-agent-tests.ts | 37 ++++++++++++++++++++++ types/forever-agent/index.d.ts | 28 ++++++++++++++++ types/forever-agent/tsconfig.json | 23 ++++++++++++++ types/forever-agent/tslint.json | 1 + 4 files changed, 89 insertions(+) create mode 100644 types/forever-agent/forever-agent-tests.ts create mode 100644 types/forever-agent/index.d.ts create mode 100644 types/forever-agent/tsconfig.json create mode 100644 types/forever-agent/tslint.json diff --git a/types/forever-agent/forever-agent-tests.ts b/types/forever-agent/forever-agent-tests.ts new file mode 100644 index 0000000000..b1ba9965fc --- /dev/null +++ b/types/forever-agent/forever-agent-tests.ts @@ -0,0 +1,37 @@ +import ForeverAgent = require("forever-agent"); + +const agent = new ForeverAgent(); +const agentSsl = new ForeverAgent.SSL(); + +const agentWithBaseOptions = new ForeverAgent({ + keepAlive: true, + keepAliveMsecs: 100, + maxFreeSockets: 500, + maxSockets: 100, +}); + +const agentSslWithBaseOptions = new ForeverAgent({ + keepAlive: true, + keepAliveMsecs: 100, + maxFreeSockets: 500, + maxSockets: 100, +}); + +const agentWithAllOptions = new ForeverAgent({ + keepAlive: true, + keepAliveMsecs: 100, + maxFreeSockets: 500, + maxSockets: 100, + minSockets: 500, +}); + +const agentSslWithAllOptions = new ForeverAgent({ + keepAlive: true, + keepAliveMsecs: 100, + maxFreeSockets: 500, + maxSockets: 100, + minSockets: 500, +}); + +const agentDefaultMinSockets = ForeverAgent.defaultMinSockets; +const agentSslDefaultMinSockets = ForeverAgent.SSL.defaultMinSockets; diff --git a/types/forever-agent/index.d.ts b/types/forever-agent/index.d.ts new file mode 100644 index 0000000000..1126a2a1c4 --- /dev/null +++ b/types/forever-agent/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for forever-agent 0.6 +// Project: https://github.com/mikeal/forever-agent +// Definitions by: Dmitry Guketlev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Agent as HttpAgent, AgentOptions as HttpAgentOptions } from "http"; + +export = ForeverAgentModule; + +interface ForeverAgentOptions extends HttpAgentOptions { + minSockets?: number; +} + +declare class ForeverAgent extends HttpAgent { + constructor(options?: ForeverAgentOptions); + + static defaultMinSockets: number; +} + +declare class ForeverAgentSSL extends ForeverAgent { + constructor(options?: ForeverAgentOptions); +} + +declare const ForeverAgentModule: typeof ForeverAgent & { + SSL: typeof ForeverAgentSSL, +}; diff --git a/types/forever-agent/tsconfig.json b/types/forever-agent/tsconfig.json new file mode 100644 index 0000000000..4868c35d0c --- /dev/null +++ b/types/forever-agent/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "forever-agent-tests.ts" + ] +} diff --git a/types/forever-agent/tslint.json b/types/forever-agent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/forever-agent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 6627256182d01771d4284baae48fb762914b110d Mon Sep 17 00:00:00 2001 From: johanblumenberg Date: Mon, 26 Feb 2018 17:32:47 +0100 Subject: [PATCH 091/128] Add missing types to expect (#23924) * expect: add toBeNull(), toBeDefined(), toBeUndefined() * expect: add expect(...).not * expect: add typings for expect.any() * expect: added toMatchObject() * expect: added toHaveBeenLastCalledWith() --- types/expect/expect-tests.ts | 115 +++++++++++++++++++++++++++++++++++ types/expect/index.d.ts | 8 +++ 2 files changed, 123 insertions(+) diff --git a/types/expect/expect-tests.ts b/types/expect/expect-tests.ts index 41bdbe5581..fea4a3d4d9 100644 --- a/types/expect/expect-tests.ts +++ b/types/expect/expect-tests.ts @@ -88,6 +88,17 @@ describe('A spy', () => { expect(spy).toHaveBeenCalledWith(1, 2, 3); }); + it('knows the arguments it was last called with', () => { + spy(0, 1, 2); + spy(1, 2, 3); + expect(spy).toHaveBeenLastCalledWith(1, 2, 3); + }); + + it('accepts to have been called with any object', () => { + spy({}); + expect(spy).toHaveBeenCalledWith(expect.any(Object)); + }); + describe('that calls some other function', () => { let otherContext: any; let otherArguments: any; @@ -462,6 +473,66 @@ describe('toBeFalsy', () => { }); }); +describe('toBeDefined', () => { + it('does not throw on defined actual values', () => { + expect(() => { + expect(1).toBeDefined(); + expect(0).toBeDefined(); + expect(null).toBeDefined(); + }).toNotThrow(); + }); + + it('throws on undefined actual values', () => { + expect(() => { + expect(undefined).toBeDefined(); + }).toThrow(); + }); +}); + +describe('toBeUndefined', () => { + it('throws on defined values', () => { + expect(() => { + expect(42).toBeUndefined(); + }).toThrow(); + + expect(() => { + expect(0).toBeUndefined(); + }).toThrow(); + + expect(() => { + expect(null).toBeUndefined(); + }).toThrow(); + }); + + it('does not throw with undefined actual values', () => { + expect(() => { + expect(undefined).toBeUndefined(); + }).toNotThrow(); + }); +}); + +describe('toBeNull', () => { + it('throws on non-null values', () => { + expect(() => { + expect(42).toBeNull(); + }).toThrow(); + + expect(() => { + expect(0).toBeNull(); + }).toThrow(); + + expect(() => { + expect(undefined).toBeNull(); + }).toThrow(); + }); + + it('does not throw with null actual values', () => { + expect(() => { + expect(null).toBeNull(); + }).toNotThrow(); + }); +}); + describe('toEqual', () => { it('works', () => { expect(() => { @@ -953,6 +1024,36 @@ describe('expect(array).toNotMatch', () => { }); }); +describe('expect(object).toMatchObject', () => { + it('does not throw when the actual value matches', () => { + expect(() => { + expect({ + statusCode: 200, + headers: { + server: 'express web server' + } + }).toMatchObject({ + statusCode: 200, + headers: {} + }); + }).toNotThrow(); + }); + + it('throws when the actual value does not match', () => { + expect(() => { + expect({ + statusCode: 200, + headers: { + server: 'nginx web server' + } + }).toMatchObject({ + statusCode: 201, + headers: {} + }); + }).toThrow(/to match/); + }); +}); + describe('toNotEqual', () => { it('works', () => { expect('actual').toNotEqual('expected'); @@ -1100,3 +1201,17 @@ describe('withContext', () => { }).toThrow(/must be a function/); }); }); + +describe('not', () => { + it('does not throw on different values', () => { + expect(() => { + expect(1).not.toEqual(2); + }).toNotThrow(); + }); + + it('throws on equal values', () => { + expect(() => { + expect(1).not.toEqual(1); + }).toThrow(); + }); +}); diff --git a/types/expect/index.d.ts b/types/expect/index.d.ts index a37e8366f1..0e7ea18e91 100644 --- a/types/expect/index.d.ts +++ b/types/expect/index.d.ts @@ -14,6 +14,9 @@ declare namespace expect { toBeTruthy(message?: string): Expectation; toNotExist(message?: string): Expectation; toBeFalsy(message?: string): Expectation; + toBeNull(message?: string): Expectation; + toBeDefined(message?: string): Expectation; + toBeUndefined(message?: string): Expectation; toBe(value: T, message?: string): Expectation; toNotBe(value: any, message?: string): Expectation; @@ -28,6 +31,7 @@ declare namespace expect { toNotBeAn(value: string | {}, message?: string): Expectation; toMatch(value: string | RegExp | {}, message?: string): Expectation; toNotMatch(value: string | RegExp | {}, message?: string): Expectation; + toMatchObject(value: {}, message?: string): Expectation; toBeLessThan(value: number, message?: string): Expectation; toBeLessThanOrEqualTo(value: number, messasge?: string): Expectation; @@ -55,6 +59,9 @@ declare namespace expect { toHaveBeenCalled(message?: string): Expectation; toNotHaveBeenCalled(message?: string): Expectation; toHaveBeenCalledWith(...args: any[]): Expectation; + toHaveBeenLastCalledWith(...args: any[]): Expectation; + + not: Expectation; // deprecated withContext(context: any): Expectation; @@ -90,6 +97,7 @@ declare namespace expect { function restoreSpies(): void; function assert(condition: boolean, messageFormat: string, ...extraArgs: any[]): void; function extend(extension: Extension): void; + function any(ctor: { new (): T }): T; } declare function expect(actual: T): expect.Expectation; From 385efad406784987948549534a2f72ce0b6eb3c9 Mon Sep 17 00:00:00 2001 From: AEPKILL Date: Tue, 27 Feb 2018 00:42:37 +0800 Subject: [PATCH 092/128] Type definitions for sass-webpack-plugin 1.0.0 (#23898) * finish * add tslint * pass lint * fix some error * fix export error --- types/sass-webpack-plugin/index.d.ts | 32 +++++++++++++++++++ .../sass-webpack-plugin-tests.ts | 30 +++++++++++++++++ types/sass-webpack-plugin/tsconfig.json | 17 ++++++++++ types/sass-webpack-plugin/tslint.json | 1 + 4 files changed, 80 insertions(+) create mode 100644 types/sass-webpack-plugin/index.d.ts create mode 100644 types/sass-webpack-plugin/sass-webpack-plugin-tests.ts create mode 100644 types/sass-webpack-plugin/tsconfig.json create mode 100644 types/sass-webpack-plugin/tslint.json diff --git a/types/sass-webpack-plugin/index.d.ts b/types/sass-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..df589ca034 --- /dev/null +++ b/types/sass-webpack-plugin/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for sass-webpack-plugin 1.0 +// Project: https://github.com/jalkoby/sass-webpack-plugin +// Definitions by: AEPKILL +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { Options } from 'node-sass'; +import { Plugin } from 'webpack'; + +declare namespace SassPlugin { + type NODE_ENV = 'production' | 'development'; + type FileRule = string | string[] | { [key: string]: string }; + interface Config { + sourceMap?: boolean; + autoprefixer?: boolean; + sass?: Options; + } +} + +declare class SassPlugin extends Plugin { + constructor( + file: SassPlugin.FileRule, + mode?: SassPlugin.NODE_ENV | SassPlugin.Config + ); + constructor( + file: SassPlugin.FileRule, + mode: SassPlugin.NODE_ENV, + config?: SassPlugin.Config + ); +} + +export = SassPlugin; diff --git a/types/sass-webpack-plugin/sass-webpack-plugin-tests.ts b/types/sass-webpack-plugin/sass-webpack-plugin-tests.ts new file mode 100644 index 0000000000..26fc27f4bb --- /dev/null +++ b/types/sass-webpack-plugin/sass-webpack-plugin-tests.ts @@ -0,0 +1,30 @@ +import SassPlugin = require('sass-webpack-plugin'); + +type NODE_ENV = SassPlugin.NODE_ENV; + +const env = process.env.NODE_ENV as NODE_ENV; + +new SassPlugin('./src/styles/index.scss'); + +// production ready +new SassPlugin('./src/styles/index.scss', env); + +// multi files +new SassPlugin(['./src/styles/one.scss', './src/styles/two.sass'], env); + +// a different output filename +new SassPlugin({ './src/styles/index.scss': 'bundle.css' }, env); + +// with sass tuning +new SassPlugin('./src/styles/index.scss', env, { + sass: { + includePaths: ['node_modules/bootstrap-sass/assets/stylesheets'] + } +}); + +// with source maps + compressing - autoprefixing +new SassPlugin('./src/styles/index.scss', { + sourceMap: true, + sass: { outputStyle: 'compressed' }, + autoprefixer: false +}); diff --git a/types/sass-webpack-plugin/tsconfig.json b/types/sass-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..f062aaeb5d --- /dev/null +++ b/types/sass-webpack-plugin/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "sass-webpack-plugin-tests.ts"] +} diff --git a/types/sass-webpack-plugin/tslint.json b/types/sass-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sass-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 6e4017430211e42afdcb4ee2f79526dca826ea6b Mon Sep 17 00:00:00 2001 From: Jimmy Luong Date: Tue, 27 Feb 2018 03:44:31 +1100 Subject: [PATCH 093/128] Add type definitions for @atlaskit/button (#23897) --- .../atlaskit__button-tests.tsx | 38 ++++++++ types/atlaskit__button/index.d.ts | 93 +++++++++++++++++++ types/atlaskit__button/tsconfig.json | 20 ++++ types/atlaskit__button/tslint.json | 1 + 4 files changed, 152 insertions(+) create mode 100644 types/atlaskit__button/atlaskit__button-tests.tsx create mode 100644 types/atlaskit__button/index.d.ts create mode 100644 types/atlaskit__button/tsconfig.json create mode 100644 types/atlaskit__button/tslint.json diff --git a/types/atlaskit__button/atlaskit__button-tests.tsx b/types/atlaskit__button/atlaskit__button-tests.tsx new file mode 100644 index 0000000000..dd592255e9 --- /dev/null +++ b/types/atlaskit__button/atlaskit__button-tests.tsx @@ -0,0 +1,38 @@ +import Button, { ButtonGroup, themeNamespace } from "@atlaskit/button"; + +import * as React from "react"; +import { render } from "react-dom"; + +declare const container: Element; + +render( + + + , + container +); diff --git a/types/atlaskit__button/index.d.ts b/types/atlaskit__button/index.d.ts new file mode 100644 index 0000000000..e9a613fabd --- /dev/null +++ b/types/atlaskit__button/index.d.ts @@ -0,0 +1,93 @@ +// Type definitions for @atlaskit/button 6.4 +// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/ +// Definitions by: Jimmy Luong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { + Component, + ReactNode, + ReactElement, + ComponentClass, + MouseEventHandler +} from "react"; + +export type ButtonAppearances = + | "default" + | "danger" + | "link" + | "primary" + | "subtle" + | "subtle-link" + | "warning" + | "help"; + +export interface ButtonProps { + /** The base styling to apply to the button. */ + readonly appearance?: ButtonAppearances; + /** Pass aria-controls to underlying html button. */ + readonly ariaControls?: string; + /** Pass aria-expanded to underlying html button. */ + readonly ariaExpanded?: boolean; + /** Pass aria-haspopup to underlying html button. */ + readonly ariaHaspopup?: boolean; + /** This button's child nodes. */ + readonly children?: ReactNode; + /** Add a classname to the button. */ + readonly className?: string; + /** A custom component to use instead of the default button. */ + readonly component?: ComponentClass; + /** Name property of a linked form that the button submits when clicked. */ + readonly form?: string; + /** Provides a url for buttons being used as a link. */ + readonly href?: string; + /** Places an icon within the button, after the button's text. */ + readonly iconAfter?: ReactElement; + /** Places an icon within the button, before the button's text. */ + readonly iconBefore?: ReactElement; + /** Pass a reference on to the styled component */ + readonly innerRef?: (instance: any) => void; + /** Provide a unique id to the button. */ + readonly id?: string; + /** Set if the button is disabled. */ + readonly isDisabled?: boolean; + /** Change the style to indicate the button is selected. */ + readonly isSelected?: boolean; + /** Handler to be called on click. */ + readonly onClick?: MouseEventHandler; + /** Set the amount of padding in the button. */ + readonly spacing?: ButtonSpacing; + /** Assign specific tabIndex order to the underlying html button. */ + readonly tabIndex?: number; + /** Pass target down to a link within the button component, if a href is provided. */ + readonly target?: string; + /** Set whether it is a button or a form submission. */ + readonly type?: ButtonType; + /** Option to fit button width to its parent width */ + readonly shouldFitContainer?: boolean; +} + +export type ButtonType = "button" | "submit"; + +export type ButtonSpacing = "compact" | "default" | "none"; + +export interface ButtonState { + readonly isActive: boolean; + readonly isFocus: boolean; + readonly isHover: boolean; +} + +declare class Button extends Component {} + +export interface ButtonGroupProps { + /** The appearance to apply to all buttons. */ + readonly appearance?: ButtonAppearances; + /** The buttons to render. */ + readonly children: ReactNode; +} + +export class ButtonGroup extends Component {} + +export const themeNamespace: string; + +export default Button; diff --git a/types/atlaskit__button/tsconfig.json b/types/atlaskit__button/tsconfig.json new file mode 100644 index 0000000000..3f374a6b3e --- /dev/null +++ b/types/atlaskit__button/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "paths": { + "@atlaskit/button": ["atlaskit__button"] + } + }, + "files": ["index.d.ts", "atlaskit__button-tests.tsx"] +} diff --git a/types/atlaskit__button/tslint.json b/types/atlaskit__button/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/atlaskit__button/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3bdafbcb56c0762e60d93b45fd68ee73d6425bf1 Mon Sep 17 00:00:00 2001 From: Dancespiele Date: Mon, 26 Feb 2018 17:49:21 +0100 Subject: [PATCH 094/128] add types definitions for the roads project (#23832) * add types for the roads project * fix a type --- types/roads/index.d.ts | 245 +++++++++++++++++++++++++++++++++++++ types/roads/roads-tests.ts | 68 ++++++++++ types/roads/tsconfig.json | 24 ++++ types/roads/tslint.json | 3 + 4 files changed, 340 insertions(+) create mode 100644 types/roads/index.d.ts create mode 100644 types/roads/roads-tests.ts create mode 100644 types/roads/tsconfig.json create mode 100644 types/roads/tslint.json diff --git a/types/roads/index.d.ts b/types/roads/index.d.ts new file mode 100644 index 0000000000..55028403b6 --- /dev/null +++ b/types/roads/index.d.ts @@ -0,0 +1,245 @@ +// Type definitions for roads 5.0 +// Project: https://github.com/Dashron/roads +// Definitions by: Francisco Jesus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 +/// + +/** + * Roads module + */ +export type Keys = string; +export type Option = {[k in Keys]: any}; + +/** + * @param method The HTTP method that was provided to the request + * @param url The URL that was provided to the request + * @param body The body that was provided to the request, after it was properly parsed into an object + * @param headers The headers that were provided to the request + * @param next The next step of the handler chain + */ +export interface Router { + method: string; + path: string; + fn: () => void; +} + +/** + * @param babelify A set of options that can influence the build process. See all fields below + * @param envify An object to pass to envify. This allows you to change values between your server and client scripts + * @param exclude An array of files that should not be included in the build process + * @param use_sourcemaps Whether or not the build process should include source maps + */ +export interface Options { + babelify?: Option; + envify?: Option; + exclude?: string[]; + external?: any; + use_sourcemaps?: boolean; +} + +/** + * A Road is a container that holds an array of functions + * @see new Road() + */ +export class Road { + /** + * Add a custom function that will be executed before every request + * @param fn Will be called any time a request is made on the object. + * @see Road.use(Function fn) + */ + use(fn: (method: string, url: any, body: any, headers: Headers, next: () => any) => any): any; + + /** + * Locate and execute the resource method associated with the request parameters + * @param method The request HTTP method + * @param url The request Url + * @param body the request body + * @param headers The request headers + * @see Road.request(string method, string url, dynamic body, Object headers) + */ + request(method: string, url: string, body?: any, headers?: Headers): any; +} + +/** + * The response object contains all of the information you want to send to the client + * @param body The body of the response + * @param status The HTTP Status code + * @param headers Key value pairs of http headers + * @see Road.Response + */ +export class Response { + constructor(body: any, status: number, headers?: Option); + + /** + * Add a cookie method to the response object. Allows you to set cookies + * @param name The name of the cookie + * @param value The value name + * @param options Cookie options + */ + setCookie(name: string, value: string, options?: any): void; + + /** + * Get all the cookies + */ + getCookies(): any; +} + +/** + * A helper error, that contains information relevant to common HTTP errors + * @param message A message describing the HTTP error + * @param code An official http status code + * @see Roads.HttpError + */ +export class HttpError { + invalid_request: number; + unauthorized: number; + forbidden: number; + not_found: number; + method_not_allowed: number; + not_acceptable: number; + conflict: number; + gone: number; + unprocessable_entity: number; + too_many_requests: number; + internal_server_error: number; + constructor(message: string, code: number); +} + +/** + * Middleware object + */ +export namespace middleware { + /** + * Very simple middleware to apply a single value to the request context + * @param key The key that should store the value on the request context + * @param val val The value to apply to the request context + */ + function applyToContext(key: string, val: any): () => any; + + /** + * Middleware to kill the trailing slash on http requests + * @see killSlash() + */ + function killSlash(): any; + + /** + * Middleware to Apply proper cors headers + * @param allow_origins Either * to allow all origins, or an explicit list of valid origins + * @param allow_headers A white list of headers that the client is allowed to send in their requests + */ + function cors(allow_origins: string | string[], allow_headers?: string[]): any; + + /** + * Translate the request body into a usable value + * @param body request body + * @param content_type media type of the body + */ + function parseBody(body: any, content_type: string): object | string; + + /** + * Adds two simple functions to get and set a page title on the request context. This is very helpful for isomorphic js, since on the client, page titles aren't part of the rendered view data. + */ + function setTitle(): any; + + /** + * Applies a method to the request context that allows you to make requests into another roads object + * @param key The name of the key in the request context that will store the roads request + * @param road road The roads object that you will interact with + */ + function reroute(key: string, road: Road): () => any; + + /** + * Middleware to Apply proper cors headers + */ + class SimpleRouter { + /** + * It have all the routers configured + */ + routers: Router[]; + + /** + * @param road The road for the routers + */ + constructor(road?: Road); + + /** + * @param road apply manualy the router middleware + */ + applyMiddleware(road: Road): void; + + /** + * Add a route to receive the request + * @param method Methot to receive the request + * @param path Paht to receive the request + * @param fn Handle the request received + */ + addRoute(method: string, path: string, fn: (url: any, body: any, headers: Headers, next: () => any) => any): any; + + /** + * Receive file request + * @param file_path path of the file to receive + * @param prefix prefix of the path file + */ + addRouteFile(file_path: string, prefix?: string): any; + } +} + +/** + * To integrate to differents HTTP server + */ +export namespace integrations { + /** + * Integration to express + * @param road The Road object that contains all routing information for this integration + */ + function express(road: Road): () => any; + + /** + * Integration to koa + * @param road The Road object that contains all routing information for this integration + */ + function koa(road: Road): () => any; +} + +/** + * A helper object to easily enable PJAX on your website using roads + */ +export class PJAX { + /** + * @param road The road that will turn your pjax requests into HTML + * @param container_element The element that will be filled with your roads output + * @param window The pages window object to help set page title and other items + */ + constructor(road: Road, container_element?: Element | null, window?: Window | null); + + /** + * Adds middleware to the assigned road whcih will adds setTitle to the request context. This allows you to easily update the page title + */ + addTitleMiddleware(): this; + + /** + * Assigns the cookie middlware to the road to properly handle cookies + * @param document The pages document object to properly parse and set cookies + */ + addCookieMiddleware(document: Document): any; + + /** + * Hooks up the PJAX functionality to the information provided via the constructor + */ + register(): any; + + /** + * @param response_object The response from the roads request + */ + render(response_object: object): any; +} + +/** + * Browserify function to convert your script to run in the browser + * @param input_file The source file that will be converted to use in the browser + * @param output_file The output file that will be accessible by your browser + * @param options A set of options that can influence the build process. See all fields below + */ +export function build(input_file: string, output_file: string, options?: Options): any; diff --git a/types/roads/roads-tests.ts b/types/roads/roads-tests.ts new file mode 100644 index 0000000000..6914c3d218 --- /dev/null +++ b/types/roads/roads-tests.ts @@ -0,0 +1,68 @@ +import { build, Road, middleware, integrations, Response, HttpError, PJAX } from "roads"; + +const road = new Road(); +const router = new middleware.SimpleRouter(road); + +road.use(middleware.cors("*")); + +road.use(middleware.killSlash); + +router.addRoute("GET", "/user", (path, body, headers, next) => { + const response = new Response({name: "test"}, 200, {"last-modified": (new Date()).toString()}); + response.setCookie("name", "value", {path: ''}); + response.getCookies(); + return response; +}); + +router.addRouteFile('./example.png', 'http://image-example.com'); + +road.request("GET", "/user") + .then((response: any) => { + console.log(`response: ${JSON.stringify(response)}`); + }); + +road.use((method, url, body, headers, next) => { + return JSON.stringify({ + method, + url, + body, + headers, + next + }); +}); + +road.use((method, url, body, headers, next) => { + // execute the actual resource method, and return the response + return next() + // Catch any errors that are thrown by the resources + .catch ((err: any) => { + // Wrap the errors in response objects. If they are [HttpErrors](#roadshttperror) we adjust the status code + switch (err.code) { + case 404: + return new HttpError(err.massage , 404); + case 405: + return new HttpError(err.massage, 405); + case 500: + default: + return new HttpError(err.massage, 500); + } + }); +}); + +const pjax = new PJAX(road, document.getElementById('container'), window); +pjax.register(); +build(__dirname + '/static/client.js', __dirname + '/static/client.brws.js', { + use_sourcemaps: true, + external: { + roads: { + output_file: __dirname + '/static/roads.brws.js', + }, + react: { + output_file: __dirname + '/static/react.brws.js', + } + }, + babelify: {presets: ['react']} +}); + +const koa = integrations.koa(road); +const express = integrations.express(road); diff --git a/types/roads/tsconfig.json b/types/roads/tsconfig.json new file mode 100644 index 0000000000..ac8a53a641 --- /dev/null +++ b/types/roads/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "roads-tests.ts" + ] +} diff --git a/types/roads/tslint.json b/types/roads/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/roads/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 4843cd33e3eb82203b08c2b7cea022e469695edc Mon Sep 17 00:00:00 2001 From: Muhammad Fawwaz Orabi Date: Mon, 26 Feb 2018 18:51:35 +0200 Subject: [PATCH 095/128] Add type definitions for react-helmet-async (#23825) * Add type definitions for react-helmet-async * Require TS 2.6 * Rename FilledContext to PopulatedContext * Add tests --- types/react-helmet-async/index.d.ts | 20 +++++++++++++++++++ .../react-helmet-async-tests.tsx | 15 ++++++++++++++ types/react-helmet-async/tsconfig.json | 17 ++++++++++++++++ types/react-helmet-async/tslint.json | 1 + 4 files changed, 53 insertions(+) create mode 100644 types/react-helmet-async/index.d.ts create mode 100644 types/react-helmet-async/react-helmet-async-tests.tsx create mode 100644 types/react-helmet-async/tsconfig.json create mode 100644 types/react-helmet-async/tslint.json diff --git a/types/react-helmet-async/index.d.ts b/types/react-helmet-async/index.d.ts new file mode 100644 index 0000000000..1a240b075b --- /dev/null +++ b/types/react-helmet-async/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for react-helmet-async 0.0 +// Project: https://github.com/staylor/react-helmet-async#readme +// Definitions by: forabi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +import Helmet, { HelmetData } from 'react-helmet'; +export default Helmet; + +export interface PopulatedContext { + helmet: HelmetData; +} + +interface ProviderProps { + context?: {}; +} + +export class HelmetProvider extends React.Component {} diff --git a/types/react-helmet-async/react-helmet-async-tests.tsx b/types/react-helmet-async/react-helmet-async-tests.tsx new file mode 100644 index 0000000000..e91f437edc --- /dev/null +++ b/types/react-helmet-async/react-helmet-async-tests.tsx @@ -0,0 +1,15 @@ +import * as React from 'react'; +import { renderToString } from 'react-dom/server'; +import Helmet, { HelmetProvider, PopulatedContext } from 'react-helmet-async'; + +const helmetContext = {}; + +const markup = renderToString( + +
+ + Hello, world! + +
+
+); diff --git a/types/react-helmet-async/tsconfig.json b/types/react-helmet-async/tsconfig.json new file mode 100644 index 0000000000..bbd3f732ac --- /dev/null +++ b/types/react-helmet-async/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "jsx": "react", + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "react-helmet-async-tests.tsx"] +} diff --git a/types/react-helmet-async/tslint.json b/types/react-helmet-async/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-helmet-async/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 651ab56894e243abead0a763643213a0a760747b Mon Sep 17 00:00:00 2001 From: Brian Schlenker Date: Mon, 26 Feb 2018 08:55:05 -0800 Subject: [PATCH 096/128] Upgrade es6-promisify typings to 6.0.0 (#23739) * Upgrade es6-promisify typings to 6.0.0 * Change test import to be not relative --- types/es6-promisify/es6-promisify-tests.ts | 10 +---- types/es6-promisify/index.d.ts | 47 +++++++++++++++------- 2 files changed, 35 insertions(+), 22 deletions(-) diff --git a/types/es6-promisify/es6-promisify-tests.ts b/types/es6-promisify/es6-promisify-tests.ts index e2e004a950..e86c4f7f9e 100644 --- a/types/es6-promisify/es6-promisify-tests.ts +++ b/types/es6-promisify/es6-promisify-tests.ts @@ -1,6 +1,6 @@ /// -import promisify = require('es6-promisify'); +import { promisify } from 'es6-promisify'; function callbackFunction(a: string, b: string, callback: (error: any, combined: string) => void): void { callback(undefined, a + b); @@ -10,14 +10,8 @@ function multiArgFunction(a: string, b: string, c: string, callback: (error: any callback(undefined, a + c, b + c); } -const noKeys: promisify.Settings = {}; -const multiArgFunctionSettings: promisify.Settings = { - thisArg: multiArgFunction, - multiArgs: true -}; - const callbackPromiseFactory: (...args: any[]) => Promise = promisify(callbackFunction); -const multiArgPromiseFactory: (...args: any[]) => Promise = promisify(multiArgFunction, multiArgFunctionSettings); +const multiArgPromiseFactory: (...args: any[]) => Promise = promisify(multiArgFunction); const callbackPromise: Promise = callbackPromiseFactory('stringA', 'stringB'); const multiArgPromise: Promise = multiArgPromiseFactory('stringA', 'stringB', 'stringC'); diff --git a/types/es6-promisify/index.d.ts b/types/es6-promisify/index.d.ts index 8965b48503..1ce79ec210 100644 --- a/types/es6-promisify/index.d.ts +++ b/types/es6-promisify/index.d.ts @@ -1,24 +1,43 @@ -// Type definitions for es6-promisify 5.0 +// Type definitions for es6-promisify 6.0 // Project: https://github.com/digitaldesignlabs/es6-promisify#readme // Definitions by: Harry Shipton +// Brian Schlenker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function es6_promisify(original: (...args: any[]) => any, settings?: es6_promisify.Settings): ((...args: any[]) => Promise); - // If the issue at https://github.com/Microsoft/TypeScript/issues/1360 is fixed, -// then an update should be submitted replacing the above declaration with the -// following declarations. +// then an update should be submitted replacing the promisify declaration with +// the following declarations. /* -declare function es6_promisify(original: (...args: any[], callback: (error: any, arg: T) => any) => any, settings?: Settings): ((...args: any[]) => Promise); +function promisify(original: (...args: any[], callback: (error: any, arg: T) => any) => any): ((...args: any[]) => Promise); -declare function es6_promisify(original: (...args: any[], callback: (error: any, ...args: any[]) => any) => any, settings?: Settings): ((...args: any[]) => Promise); +function promisify(original: (...args: any[], callback: (error: any, ...args: any[]) => any) => any): ((...args: any[]) => Promise); */ -declare namespace es6_promisify { - interface Settings { - thisArg?: any; - multiArgs?: boolean; - } -} +export type Callback = (err: any, arg?: T) => any; +export type CallbackFunction = (...args: any[]) => any; +export type PromiseFunction = (...args: any[]) => Promise; -export = es6_promisify; +export function promisify(original: (cb: Callback) => any): + () => Promise; +export function promisify(original: (param1: U, cb: Callback) => any): + (param1: U) => Promise; +export function promisify(original: (param1: U, param2: V, cb: Callback) => any): + (param1: U, param2: V) => Promise; +export function promisify(original: (param1: U, param2: V, param3: W, cb: Callback) => any): + (param1: U, param2: V, param3: W) => Promise; +export function promisify(original: CallbackFunction): PromiseFunction; + +export namespace promisify { + /** + * This symbol can be placed on the function to be promisified to + * provide names as an array of strings for the values in a success + * callback. + */ + const argumentNames: symbol; + + /** + * The user can supply their own Promise implementation by setting it + * here. Otherwise, the global Promise object will be used. + */ + let Promise: PromiseConstructor; +} From 5bdd72f928a7f136e2bbb5ff2dd0a451659e64d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kevin=20Tji=C3=A5m?= Date: Tue, 27 Feb 2018 00:55:52 +0800 Subject: [PATCH 097/128] [@types/three] Fix function signatures for some Animation related classes (#23782) * fix(three): fix function signature for AnimationMixer.stopAllAction * fix(three): change first arg in AnimationClip.findByName to array --- types/three/three-core.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 3ba0be89e8..a5e2b6486c 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -271,7 +271,7 @@ export class AnimationClip { optimize(): AnimationClip; static CreateFromMorphTargetSequence( name: string, morphTargetSequence: MorphTarget[], fps: number, noLoop: boolean ): AnimationClip; - static findByName( clipArray: AnimationClip, name: string ): AnimationClip; + static findByName( clipArray: AnimationClip[], name: string ): AnimationClip; static CreateClipsFromMorphTargetSequences( morphTargets: MorphTarget[], fps: number, noLoop: boolean ): AnimationClip[]; static parse( json: any ): AnimationClip; static parseAnimation( animation: any, bones: Bone[], nodeName: string ): AnimationClip; @@ -286,7 +286,7 @@ export class AnimationMixer extends EventDispatcher { clipAction(clip: AnimationClip, root?: any): AnimationAction; existingAction(clip: AnimationClip, root?: any): AnimationAction; - stopAllAction(clip: AnimationClip, root?: any): AnimationMixer; + stopAllAction(): AnimationMixer; update(deltaTime: number): AnimationMixer; getRoot(): any; uncacheClip(clip: AnimationClip): void; From 786fae6a7fca5529a926b0adffddcd9b4de73d13 Mon Sep 17 00:00:00 2001 From: Peter Burns Date: Mon, 26 Feb 2018 08:59:53 -0800 Subject: [PATCH 098/128] ExportNamedDeclaration#source can be null (#23909) e.g. this named declaration has a source: ```javascript export {foo} from './bar.js'; ``` and this one does not: ```javascript export const foo = 10; ``` Try it out at https://astexplorer.net/ to confirm. --- types/babel-types/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index cbed3e076c..b1de338923 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -422,7 +422,7 @@ export interface ExportNamedDeclaration extends Node { type: "ExportNamedDeclaration"; declaration: Declaration; specifiers: ExportSpecifier[]; - source: StringLiteral; + source: StringLiteral | null; } export interface ExportSpecifier extends Node { From 28a3b11694e22cb7ded033ad53e2bb860b710542 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Mon, 26 Feb 2018 12:02:12 -0500 Subject: [PATCH 099/128] [simplebar] Allow SimpleBar to be imported as a module. (#23911) * [simplebar] Allow SimpleBar to be imported as a module. * [simplebar] Add missing author. --- types/simplebar/index.d.ts | 5 ++++- types/simplebar/test/module-tests.ts | 4 ++++ types/simplebar/tsconfig.json | 5 +++-- 3 files changed, 11 insertions(+), 3 deletions(-) create mode 100644 types/simplebar/test/module-tests.ts diff --git a/types/simplebar/index.d.ts b/types/simplebar/index.d.ts index 64533d7408..46b6b9e737 100644 --- a/types/simplebar/index.d.ts +++ b/types/simplebar/index.d.ts @@ -1,9 +1,12 @@ // Type definitions for simplebar.js 2.4 // Project: https://github.com/Grsmto/simplebar -// Definitions by: Leonard Thieu +// Definitions by: Gregor Woiwode , Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 +export as namespace SimpleBar; +export = SimpleBar; + declare class SimpleBar { static removeObserver(): void; diff --git a/types/simplebar/test/module-tests.ts b/types/simplebar/test/module-tests.ts new file mode 100644 index 0000000000..b7d10d73bf --- /dev/null +++ b/types/simplebar/test/module-tests.ts @@ -0,0 +1,4 @@ +import SimpleBar = require('simplebar'); + +// $ExpectType typeof SimpleBar +SimpleBar; diff --git a/types/simplebar/tsconfig.json b/types/simplebar/tsconfig.json index 467b6358e4..9c51115e84 100644 --- a/types/simplebar/tsconfig.json +++ b/types/simplebar/tsconfig.json @@ -19,6 +19,7 @@ }, "files": [ "index.d.ts", - "simplebar-tests.ts" + "simplebar-tests.ts", + "test/module-tests.ts" ] -} \ No newline at end of file +} From 3b04deac0953c4b0539bda1abf36a48f160fff4f Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 26 Feb 2018 09:03:12 -0800 Subject: [PATCH 100/128] Added 'decompress-response'. (#23885) --- .../decompress-response-tests.ts | 6 +++++ types/decompress-response/index.d.ts | 11 +++++++++ types/decompress-response/tsconfig.json | 23 +++++++++++++++++++ types/decompress-response/tslint.json | 1 + 4 files changed, 41 insertions(+) create mode 100644 types/decompress-response/decompress-response-tests.ts create mode 100644 types/decompress-response/index.d.ts create mode 100644 types/decompress-response/tsconfig.json create mode 100644 types/decompress-response/tslint.json diff --git a/types/decompress-response/decompress-response-tests.ts b/types/decompress-response/decompress-response-tests.ts new file mode 100644 index 0000000000..f47665cbe0 --- /dev/null +++ b/types/decompress-response/decompress-response-tests.ts @@ -0,0 +1,6 @@ +import decompressResponse = require("decompress-response"); +import http = require("http"); + +http.get("localhost", response => { + response = decompressResponse(response); +}); diff --git a/types/decompress-response/index.d.ts b/types/decompress-response/index.d.ts new file mode 100644 index 0000000000..8e7ec88646 --- /dev/null +++ b/types/decompress-response/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for decompress-response 3.3 +// Project: https://github.com/sindresorhus/decompress-response#readme +// Definitions by: Daniel Rosenwasser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import http = require("http"); + +export = decompress_response; +declare function decompress_response(response: http.IncomingMessage): http.IncomingMessage; diff --git a/types/decompress-response/tsconfig.json b/types/decompress-response/tsconfig.json new file mode 100644 index 0000000000..c7a77a9fd1 --- /dev/null +++ b/types/decompress-response/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "decompress-response-tests.ts" + ] +} diff --git a/types/decompress-response/tslint.json b/types/decompress-response/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/decompress-response/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 9750d12776e36ac88e7fd710ccb4a1886069ab7b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 26 Feb 2018 09:03:51 -0800 Subject: [PATCH 101/128] Added 'json-parse-better-errors'. (#23884) --- types/json-parse-better-errors/index.d.ts | 18 +++++++++++++++ .../json-parse-better-errors-tests.ts | 11 +++++++++ types/json-parse-better-errors/tsconfig.json | 23 +++++++++++++++++++ types/json-parse-better-errors/tslint.json | 1 + 4 files changed, 53 insertions(+) create mode 100644 types/json-parse-better-errors/index.d.ts create mode 100644 types/json-parse-better-errors/json-parse-better-errors-tests.ts create mode 100644 types/json-parse-better-errors/tsconfig.json create mode 100644 types/json-parse-better-errors/tslint.json diff --git a/types/json-parse-better-errors/index.d.ts b/types/json-parse-better-errors/index.d.ts new file mode 100644 index 0000000000..5cf16c38e0 --- /dev/null +++ b/types/json-parse-better-errors/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for json-parse-better-errors 1.0 +// Project: https://github.com/zkat/json-parse-better-errors#readme +// Definitions by: Daniel Rosenwasser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = json_parse_better_errors; + +/** + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + * @param context The number of characters to display in each direction around the position of an error. + */ +declare function json_parse_better_errors( + txt: string, + reviver?: (key: string, value: any) => any, + context?: number): any; diff --git a/types/json-parse-better-errors/json-parse-better-errors-tests.ts b/types/json-parse-better-errors/json-parse-better-errors-tests.ts new file mode 100644 index 0000000000..ec77a01fea --- /dev/null +++ b/types/json-parse-better-errors/json-parse-better-errors-tests.ts @@ -0,0 +1,11 @@ +import parseJson = require("json-parse-better-errors"); + +parseJson(`"hello"`); +parseJson(`trash`); +parseJson(`{ "a": {} }`, k => k.toLowerCase(), 20); +parseJson(`{ + "compilerOptions": { + + } +} +`, undefined, 40); diff --git a/types/json-parse-better-errors/tsconfig.json b/types/json-parse-better-errors/tsconfig.json new file mode 100644 index 0000000000..b7dda9071a --- /dev/null +++ b/types/json-parse-better-errors/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "json-parse-better-errors-tests.ts" + ] +} diff --git a/types/json-parse-better-errors/tslint.json b/types/json-parse-better-errors/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/json-parse-better-errors/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f77d259e80400e34b600b348a4cc08960c492798 Mon Sep 17 00:00:00 2001 From: sgoll <1277035+sgoll@users.noreply.github.com> Date: Mon, 26 Feb 2018 18:10:55 +0100 Subject: [PATCH 102/128] [ramda] Add second type argument to eqBy to allow different codomain (#23926) * Add second type argument to eqBy to allow different codomain * Add test for new type argument * Resolve unreachable function overload --- types/ramda/index.d.ts | 7 +++---- types/ramda/ramda-tests.ts | 8 ++++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 205df9f569..081a62cbd7 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -576,10 +576,9 @@ declare namespace R { * Takes a function and two values in its domain and returns true if the values map to the same value in the * codomain; false otherwise. */ - eqBy(fn: (a: T) => T, a: T, b: T): boolean; - eqBy(fn: (a: T) => T, a: T): (b: T) => boolean; - eqBy(fn: (a: T) => T): (a: T, b: T) => boolean; - eqBy(fn: (a: T) => T): (a: T) => (b: T) => boolean; + eqBy(fn: (a: T) => U, a: T, b: T): boolean; + eqBy(fn: (a: T) => U, a: T): (b: T) => boolean; + eqBy(fn: (a: T) => U): CurriedFunction2; /** * Reports whether two functions have the same value for the specified property. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 8aef1c65fc..c32ab72028 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -2136,6 +2136,14 @@ class Rectangle { const c: (a: any[]) => any[] = R.symmetricDifferenceWith(eqA)(l1); // => [{a: 1}, {a: 2}, {a: 5}, {a: 6}] }; +() => { + const eqL = R.eqBy(s => s.length); + const l1 = ['bb', 'ccc', 'dddd']; + const l2 = ['aaa', 'bb', 'c']; + R.symmetricDifferenceWith(eqL, l1, l2); // => ['dddd', 'c'] + R.symmetricDifferenceWith(eqL)(l1, l2); // => ['dddd', 'c'] +}; + /***************************************************************** * String category */ From c576e544beac58d911fe017a20bf3f2c794b45aa Mon Sep 17 00:00:00 2001 From: Rodrigo Saboya Date: Sat, 17 Feb 2018 22:33:46 -0200 Subject: [PATCH 103/128] Updating catbox to hapi 17 bindings. --- types/catbox/catbox-tests.ts | 24 +- types/catbox/index.d.ts | 102 +++--- types/catbox/tsconfig.json | 5 - types/catbox/v7/catbox-tests.ts | 27 ++ types/catbox/v7/index.d.ts | 310 ++++++++++++++++++ types/catbox/v7/tsconfig.json | 31 ++ types/catbox/v7/tslint.json | 1 + types/h2o2/tsconfig.json | 3 + types/hapi-auth-basic/tsconfig.json | 5 - types/hapi-auth-jwt2/tsconfig.json | 3 + types/hapi-decorators/tsconfig.json | 3 + types/hapi/index.d.ts | 4 +- .../test/server/server-cache-provision.ts | 4 +- types/hapi/test/server/server-cache.ts | 4 +- types/hapi/tsconfig.json | 5 - types/hapi/v16/tsconfig.json | 3 + types/inert/tsconfig.json | 5 - types/inert/v4/tsconfig.json | 3 + types/nes/tsconfig.json | 5 - types/optics-agent/tsconfig.json | 5 - types/swagger-express-mw/tsconfig.json | 3 + types/swagger-hapi/tsconfig.json | 3 + types/swagger-node-runner/tsconfig.json | 3 + types/swagger-restify-mw/tsconfig.json | 3 + types/swagger-sails-hook/tsconfig.json | 3 + types/vision/tsconfig.json | 5 - types/vision/v4/tsconfig.json | 3 + types/yar/tsconfig.json | 5 - 28 files changed, 464 insertions(+), 116 deletions(-) create mode 100644 types/catbox/v7/catbox-tests.ts create mode 100644 types/catbox/v7/index.d.ts create mode 100644 types/catbox/v7/tsconfig.json create mode 100644 types/catbox/v7/tslint.json diff --git a/types/catbox/catbox-tests.ts b/types/catbox/catbox-tests.ts index 565573adad..25d4826d25 100644 --- a/types/catbox/catbox-tests.ts +++ b/types/catbox/catbox-tests.ts @@ -1,26 +1,26 @@ -import Catbox = require("catbox"); +import { CacheItem, Client, Policy, EnginePrototypeOrObject } from "catbox"; -const Memory: Catbox.EnginePrototypeOrObject = { - start(callback: Catbox.CallBackNoResult) {}, - stop() {}, - get() {}, - set() {}, - drop() {}, +const Memory: EnginePrototypeOrObject = { + async start(): Promise {}, + stop(): void {}, + async get(): Promise {}, + async set(): Promise {}, + async drop(): Promise {}, isReady(): boolean { return true; }, validateSegmentName(segment: string): null { return null; }, }; -const client = new Catbox.Client(Memory, { partition: 'cache' }); +const client = new Client(Memory, { partition: 'cache' }); -const cache = new Catbox.Policy({ +const cache = new Policy({ expiresIn: 5000, }, client, 'cache'); -cache.set('foo', 'bar', 5000, () => {}); +cache.set('foo', 'bar', 5000).then(() => {}); -cache.get('foo', () => {}); +cache.get('foo').then(() => {}); -cache.drop('foo', () => {}); +cache.drop('foo').then(() => {}); cache.isReady(); diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 826f1f7369..6d51e48696 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -1,14 +1,11 @@ -// Type definitions for catbox 7.1 +// Type definitions for catbox 10.0 // Project: https://github.com/hapijs/catbox -// Definitions by: Jason Swearingen , AJP +// Definitions by: Jason Swearingen +// AJP +// Rodrigo Saboya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -import * as Boom from 'boom'; - -export type CallBackNoResult = (err?: Boom.BoomError) => void; -export type CallBackWithResult = (err: Boom.BoomError | null | undefined, result: T) => void; - /** * Client * The Client object provides a low-level cache abstraction. The object is constructed using new Client(engine, options) where: @@ -23,34 +20,31 @@ export type CallBackWithResult = (err: Boom.BoomError | null | undefined, res export class Client implements ClientApi { constructor(engine: EnginePrototypeOrObject, options: ClientOptions); - /** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */ - start(callback: CallBackNoResult): void; + /** start() - creates a connection to the cache server. Must be called before any other method is available. */ + start(): Promise; /** stop() - terminates the connection to the cache server. */ stop(): void; /** * get(key, callback) - retrieve an item from the cache engine if found where: * * key - a cache key object (see [ICacheKey]). - * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned */ - get(key: CacheKey, callback: CallBackWithResult): CacheItem; + get(key: CacheKey): Promise; /** * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: * * key - a cache key object (see [ICacheKey]). * * value - the string or object value to be stored. * * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). - * * callback - a function with the signature function(err). */ - set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void; + set(key: CacheKey, value: CacheItem, ttl: number): Promise; /** * drop(key, callback) - remove an item from cache where: * * key - a cache key object (see [ICacheKey]). - * * callback - a function with the signature function(err). */ - drop(key: CacheKey, callback: CallBackNoResult): void; + drop(key: CacheKey): Promise; /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */ isReady(): boolean; /** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */ - validateSegmentName(segment: string): null | Boom.BoomError; + validateSegmentName(segment: string): null | Error; } export type EnginePrototypeOrObject = EnginePrototype | ClientApi; @@ -68,34 +62,31 @@ export interface EnginePrototype { * @see {@link https://github.com/hapijs/catbox#api} */ export interface ClientApi { - /** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */ - start(callback: CallBackNoResult): void; + /** start() - creates a connection to the cache server. Must be called before any other method is available. */ + start(): Promise; /** stop() - terminates the connection to the cache server. */ stop(): void; /** * get(key, callback) - retrieve an item from the cache engine if found where: * * key - a cache key object (see [ICacheKey]). - * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned */ - get(key: CacheKey, callback: CallBackWithResult): CacheItem; + get(key: CacheKey): Promise; /** - * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: + * set(key, value, ttl) - store an item in the cache for a specified length of time, where: * * key - a cache key object (see [ICacheKey]). * * value - the string or object value to be stored. * * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). - * * callback - a function with the signature function(err). */ - set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void; + set(key: CacheKey, value: CacheItem, ttl: number): Promise; /** - * drop(key, callback) - remove an item from cache where: + * drop(key) - remove an item from cache where: * * key - a cache key object (see [ICacheKey]). - * * callback - a function with the signature function(err). */ - drop(key: CacheKey, callback: CallBackNoResult): void; + drop(key: CacheKey): Promise; /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */ isReady(): boolean; /** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */ - validateSegmentName(segment: string): null | Boom.BoomError; + validateSegmentName(segment: string): null | Error; } /** @@ -135,27 +126,24 @@ export interface ClientOptions { export class Policy implements PolicyAPI { constructor(options: PolicyOptions, cache: Client, segment: string); /** - * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * get(id) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. - * * callback - the return function. */ - get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem; + get(id: string | { id: string }): Promise; /** - * set(id, value, ttl, callback) - store an item in the cache where: + * set(id, value, ttl) - store an item in the cache where: * * id - the unique item identifier (within the policy segment). * * value - the string or object value to be stored. * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). * This should be set to 0 in order to use the caching rules configured when creating the Policy object. - * * callback - a function with the signature function(err). */ - set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; + set(id: string | { id: string }, value: CacheItem, ttl: number | null): Promise; /** - * drop(id, callback) - remove the item from cache where: + * drop(id) - remove the item from cache where: * * id - the unique item identifier (within the policy segment). - * * callback - a function with the signature function(err). */ - drop(id: string | {id: string}, callback: CallBackNoResult): void; + drop(id: string | { id: string }): Promise; /** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */ ttl(created: number): number; /** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */ @@ -173,27 +161,24 @@ export class Policy implements PolicyAPI { */ export interface PolicyAPI { /** - * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * get(id) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. - * * callback - the return function. */ - get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem; + get(id: string | { id: string }): Promise; /** - * set(id, value, ttl, callback) - store an item in the cache where: + * set(id, value, ttl) - store an item in the cache where: * * id - the unique item identifier (within the policy segment). * * value - the string or object value to be stored. * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). * This should be set to 0 in order to use the caching rules configured when creating the Policy object. - * * callback - a function with the signature function(err). */ - set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; + set(id: string | { id: string }, value: CacheItem, ttl: number | null): Promise; /** - * drop(id, callback) - remove the item from cache where: + * drop(id) - remove the item from cache where: * * id - the unique item identifier (within the policy segment). - * * callback - a function with the signature function(err). */ - drop(id: string | {id: string}, callback: CallBackNoResult): void; + drop(id: string | { id: string }): Promise; /** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */ ttl(created: number): number; /** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */ @@ -204,16 +189,13 @@ export interface PolicyAPI { stats(): CacheStatisticsObject; } -/** - * The return function. The function signature is function(err, value, cached, report) where: - * @param err - any errors encountered. - * @param value - the fetched or generated value. - * @param cached - null if a valid item was not found in the cache, or IPolicyGetCallbackCachedOptions - * @param report - an object with logging information about the generation operation - */ -export type PolicyGetCallback = (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog) => void; +export interface PolicyGetPromiseResult { + value: CacheItem; + cached: PolicyGetCachedOptions; + report: PolicyGetReportLog; +} -export interface PolicyGetCallbackCachedOptions { +export interface PolicyGetCachedOptions { /** item - the cached value. */ item: CacheItem; /** stored - the timestamp when the item was stored in the cache. */ @@ -262,10 +244,14 @@ export interface PolicyOptions { pendingGenerateTimeout?: number; } +export interface GenerateFuncFlags { + ttl: number; +} + /** * generateFunc * Is used in PolicyOptions - * A function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) + * A function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id) * @param id - the id string or object provided to the get() method. * @param next - the method called when the new item is returned with the signature function(err, value, ttl) where: * * err - an error condition. @@ -273,12 +259,12 @@ export interface PolicyOptions { * * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. * @see {@link https://github.com/hapijs/catbox#policy} */ -export type GenerateFunc = (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)) => void; +export type GenerateFunc = (id: string, flags: GenerateFuncFlags) => Promise; /** * An object with logging information about the generation operation containing the following keys (as relevant): */ -export interface PolicyGetCallbackReportLog { +export interface PolicyGetReportLog { /** msec - the cache lookup time in milliseconds. */ msec: number; /** stored - the timestamp when the item was stored in the cache. */ @@ -288,7 +274,7 @@ export interface PolicyGetCallbackReportLog { /** ttl - the cache ttl value for the record. */ ttl: number; /** error - lookup error. */ - error?: Boom.BoomError; + error?: Error; } /** diff --git a/types/catbox/tsconfig.json b/types/catbox/tsconfig.json index 24e8f7f34e..feb19f81dc 100644 --- a/types/catbox/tsconfig.json +++ b/types/catbox/tsconfig.json @@ -13,11 +13,6 @@ "../" ], "types": [], - "paths": { - "boom": [ - "boom/v4" - ] - }, "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/types/catbox/v7/catbox-tests.ts b/types/catbox/v7/catbox-tests.ts new file mode 100644 index 0000000000..565573adad --- /dev/null +++ b/types/catbox/v7/catbox-tests.ts @@ -0,0 +1,27 @@ +import Catbox = require("catbox"); + +const Memory: Catbox.EnginePrototypeOrObject = { + start(callback: Catbox.CallBackNoResult) {}, + stop() {}, + get() {}, + set() {}, + drop() {}, + isReady(): boolean { return true; }, + validateSegmentName(segment: string): null { return null; }, +}; + +const client = new Catbox.Client(Memory, { partition: 'cache' }); + +const cache = new Catbox.Policy({ + expiresIn: 5000, +}, client, 'cache'); + +cache.set('foo', 'bar', 5000, () => {}); + +cache.get('foo', () => {}); + +cache.drop('foo', () => {}); + +cache.isReady(); + +cache.stats(); diff --git a/types/catbox/v7/index.d.ts b/types/catbox/v7/index.d.ts new file mode 100644 index 0000000000..826f1f7369 --- /dev/null +++ b/types/catbox/v7/index.d.ts @@ -0,0 +1,310 @@ +// Type definitions for catbox 7.1 +// Project: https://github.com/hapijs/catbox +// Definitions by: Jason Swearingen , AJP +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import * as Boom from 'boom'; + +export type CallBackNoResult = (err?: Boom.BoomError) => void; +export type CallBackWithResult = (err: Boom.BoomError | null | undefined, result: T) => void; + +/** + * Client + * The Client object provides a low-level cache abstraction. The object is constructed using new Client(engine, options) where: + * engine - is an object or a prototype function implementing the cache strategy: + * * function - a prototype function with the signature function(options). catbox will call new func(options). + * * object - a pre instantiated client implementation object. Does not support passing options. + * options - the strategy configuration object. Each strategy defines its own configuration options with the following common options: + * * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, + * the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. + * @see {@link https://github.com/hapijs/catbox#client} + */ +export class Client implements ClientApi { + constructor(engine: EnginePrototypeOrObject, options: ClientOptions); + + /** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */ + start(callback: CallBackNoResult): void; + /** stop() - terminates the connection to the cache server. */ + stop(): void; + /** + * get(key, callback) - retrieve an item from the cache engine if found where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned + */ + get(key: CacheKey, callback: CallBackWithResult): CacheItem; + /** + * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: + * * key - a cache key object (see [ICacheKey]). + * * value - the string or object value to be stored. + * * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * * callback - a function with the signature function(err). + */ + set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void; + /** + * drop(key, callback) - remove an item from cache where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err). + */ + drop(key: CacheKey, callback: CallBackNoResult): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */ + isReady(): boolean; + /** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */ + validateSegmentName(segment: string): null | Boom.BoomError; +} + +export type EnginePrototypeOrObject = EnginePrototype | ClientApi; + +/** + * A prototype CatBox engine function + */ +export interface EnginePrototype { + new(settings: ClientOptions): ClientApi; +} + +/** + * Client API + * The Client object provides the following methods: + * @see {@link https://github.com/hapijs/catbox#api} + */ +export interface ClientApi { + /** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */ + start(callback: CallBackNoResult): void; + /** stop() - terminates the connection to the cache server. */ + stop(): void; + /** + * get(key, callback) - retrieve an item from the cache engine if found where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned + */ + get(key: CacheKey, callback: CallBackWithResult): CacheItem; + /** + * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: + * * key - a cache key object (see [ICacheKey]). + * * value - the string or object value to be stored. + * * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * * callback - a function with the signature function(err). + */ + set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void; + /** + * drop(key, callback) - remove an item from cache where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err). + */ + drop(key: CacheKey, callback: CallBackNoResult): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */ + isReady(): boolean; + /** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */ + validateSegmentName(segment: string): null | Boom.BoomError; +} + +/** + * Any method with a key argument takes an object with the following required properties: + */ +export interface CacheKey { + /** segment - a caching segment name string. Enables using a single cache server for storing different sets of items with overlapping ids. */ + segment: string; + /** id - a unique item identifier string (per segment). Can be an empty string. */ + id: string; +} + +/** Cached object contains the following: */ +export interface CachedObject { + /** item - the value stored in the cache using set(). */ + item: any; + /** stored - the timestamp when the item was stored in the cache (in milliseconds). */ + stored: number; + /** ttl - the remaining time-to-live (not the original value used when storing the object). */ + ttl: number; +} + +export type CacheItem = any; + +export interface ClientOptions { + partition: string; +} + +/** + * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. + * The object is constructed using new Policy(options, [cache, segment]) where: + * * options - an object with the IPolicyOptions structure + * * cache - a Client instance (which has already been started). + * * segment - required when cache is provided. The segment name used to isolate cached items within the cache partition. + * @see {@link https://github.com/hapijs/catbox#policy} + */ +export class Policy implements PolicyAPI { + constructor(options: PolicyOptions, cache: Client, segment: string); + /** + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. + * * callback - the return function. + */ + get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem; + /** + * set(id, value, ttl, callback) - store an item in the cache where: + * * id - the unique item identifier (within the policy segment). + * * value - the string or object value to be stored. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * callback - a function with the signature function(err). + */ + set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; + /** + * drop(id, callback) - remove the item from cache where: + * * id - the unique item identifier (within the policy segment). + * * callback - a function with the signature function(err). + */ + drop(id: string | {id: string}, callback: CallBackNoResult): void; + /** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */ + ttl(created: number): number; + /** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */ + rules(options: PolicyOptions): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */ + isReady(): boolean; + /** stats - an object with cache statistics */ + stats(): CacheStatisticsObject; +} + +/** + * Policy API + * The Policy object provides the following methods: + * @see {@link https://github.com/hapijs/catbox#api-1} + */ +export interface PolicyAPI { + /** + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. + * * callback - the return function. + */ + get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem; + /** + * set(id, value, ttl, callback) - store an item in the cache where: + * * id - the unique item identifier (within the policy segment). + * * value - the string or object value to be stored. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * callback - a function with the signature function(err). + */ + set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; + /** + * drop(id, callback) - remove the item from cache where: + * * id - the unique item identifier (within the policy segment). + * * callback - a function with the signature function(err). + */ + drop(id: string | {id: string}, callback: CallBackNoResult): void; + /** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */ + ttl(created: number): number; + /** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */ + rules(options: PolicyOptions): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */ + isReady(): boolean; + /** stats - an object with cache statistics */ + stats(): CacheStatisticsObject; +} + +/** + * The return function. The function signature is function(err, value, cached, report) where: + * @param err - any errors encountered. + * @param value - the fetched or generated value. + * @param cached - null if a valid item was not found in the cache, or IPolicyGetCallbackCachedOptions + * @param report - an object with logging information about the generation operation + */ +export type PolicyGetCallback = (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog) => void; + +export interface PolicyGetCallbackCachedOptions { + /** item - the cached value. */ + item: CacheItem; + /** stored - the timestamp when the item was stored in the cache. */ + stored: number; + /** ttl - the cache ttl value for the record. */ + ttl: number; + /** isStale - true if the item is stale. */ + isStale: boolean; +} + +/** + * @see {@link https://github.com/hapijs/catbox#policy} + */ +export interface PolicyOptions { + /** expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ + expiresIn?: number; + /** expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Uses local time. Cannot be used together with expiresIn. */ + expiresAt?: string; + /** generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: */ + generateFunc?: GenerateFunc; + /** + * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. + * Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: + * * stored - the timestamp when the item was stored in the cache (in milliseconds). + * * ttl - the remaining time-to-live (not the original value used when storing the object). + */ + staleIn?: number | ((stored: number, ttl: number) => number); + /** staleTimeout - number of milliseconds to wait before returning a stale value while generateFunc is generating a fresh value. */ + staleTimeout?: number; + /** + * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. + * When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. + * Set to false to disable timeouts which may cause all get() requests to get stuck forever. + */ + generateTimeout?: number | false; + /** dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. */ + dropOnError?: boolean; + /** generateOnReadError - if false, an upstream cache read error will stop the get() method from calling the generate function and will instead pass back the cache error. Defaults to true. */ + generateOnReadError?: boolean; + /** generateIgnoreWriteError - if false, an upstream cache write error will be passed back with the generated value when calling the get() method. Defaults to true. */ + generateIgnoreWriteError?: boolean; + /** + * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. + * Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. + */ + pendingGenerateTimeout?: number; +} + +/** + * generateFunc + * Is used in PolicyOptions + * A function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) + * @param id - the id string or object provided to the get() method. + * @param next - the method called when the new item is returned with the signature function(err, value, ttl) where: + * * err - an error condition. + * * value - the new value generated. + * * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. + * @see {@link https://github.com/hapijs/catbox#policy} + */ +export type GenerateFunc = (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)) => void; + +/** + * An object with logging information about the generation operation containing the following keys (as relevant): + */ +export interface PolicyGetCallbackReportLog { + /** msec - the cache lookup time in milliseconds. */ + msec: number; + /** stored - the timestamp when the item was stored in the cache. */ + stored: number; + /** isStale - true if the item is stale. */ + isStale: boolean; + /** ttl - the cache ttl value for the record. */ + ttl: number; + /** error - lookup error. */ + error?: Boom.BoomError; +} + +/** + * an object with cache statistics where: + */ +export interface CacheStatisticsObject { + /** sets - number of cache writes. */ + sets: number; + /** gets - number of cache get() requests. */ + gets: number; + /** hits - number of cache get() requests in which the requested id was found in the cache (can be stale). */ + hits: number; + /** stales - number of cache reads with stale requests (only counts the first request in a queued get() operation). */ + stales: number; + /** generates - number of calls to the generate function. */ + generates: number; + /** errors - cache operations errors. TODO check this */ + errors: number; +} diff --git a/types/catbox/v7/tsconfig.json b/types/catbox/v7/tsconfig.json new file mode 100644 index 0000000000..48b4d9f014 --- /dev/null +++ b/types/catbox/v7/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "boom": [ + "boom/v4" + ], + "catbox": [ + "catbox/v7" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "catbox-tests.ts" + ] +} \ No newline at end of file diff --git a/types/catbox/v7/tslint.json b/types/catbox/v7/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/catbox/v7/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/h2o2/tsconfig.json b/types/h2o2/tsconfig.json index eb41a55289..767fa4e7b7 100644 --- a/types/h2o2/tsconfig.json +++ b/types/h2o2/tsconfig.json @@ -17,6 +17,9 @@ "boom": [ "boom/v4" ], + "catbox": [ + "catbox/v7" + ], "hapi": [ "hapi/v16" ], diff --git a/types/hapi-auth-basic/tsconfig.json b/types/hapi-auth-basic/tsconfig.json index 191d992f70..80aa0fbace 100644 --- a/types/hapi-auth-basic/tsconfig.json +++ b/types/hapi-auth-basic/tsconfig.json @@ -13,11 +13,6 @@ "../" ], "types": [], - "paths": { - "boom": [ - "boom/v4" - ] - }, "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/types/hapi-auth-jwt2/tsconfig.json b/types/hapi-auth-jwt2/tsconfig.json index ada8a3f94d..19a6e785ac 100644 --- a/types/hapi-auth-jwt2/tsconfig.json +++ b/types/hapi-auth-jwt2/tsconfig.json @@ -17,6 +17,9 @@ "boom": [ "boom/v4" ], + "catbox": [ + "catbox/v7" + ], "hapi": [ "hapi/v16" ], diff --git a/types/hapi-decorators/tsconfig.json b/types/hapi-decorators/tsconfig.json index a018c33c53..6434d0422e 100644 --- a/types/hapi-decorators/tsconfig.json +++ b/types/hapi-decorators/tsconfig.json @@ -19,6 +19,9 @@ "boom": [ "boom/v4" ], + "catbox": [ + "catbox/v7" + ], "hapi": [ "hapi/v16" ], diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index f65cee14d4..01586dd3bf 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -453,7 +453,7 @@ export interface Request extends Podium { * The response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to * override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects). */ - response: ResponseObject | Boom.BoomError | null; + response: ResponseObject | Boom.Boom | null; /** * Same as pre but represented as the response object created by the pre method. @@ -3847,7 +3847,7 @@ export namespace Lifecycle { type ReturnValueTypes = (null | string | number | boolean) | (Buffer) | - (Error | Boom.BoomError) | + (Error | Boom.Boom) | (stream.Stream) | (object | object[]) | symbol | diff --git a/types/hapi/test/server/server-cache-provision.ts b/types/hapi/test/server/server-cache-provision.ts index f30ce65cd6..1e120348b2 100644 --- a/types/hapi/test/server/server-cache-provision.ts +++ b/types/hapi/test/server/server-cache-provision.ts @@ -9,8 +9,8 @@ server.initialize(); server.cache.provision({engine: require('catbox-memory'), name: 'countries' }); const cache: catbox.Policy = server.cache({segment: 'countries', cache: 'countries', expiresIn: 60 * 60 * 1000 }); -cache.set('norway', 'oslo', 10 * 1000, () => {}); -const value = cache.get('norway', () => {}); +cache.set('norway', 'oslo', 10 * 1000).then(() => {}); +const value = cache.get('norway').then(() => {}); server.start(); diff --git a/types/hapi/test/server/server-cache.ts b/types/hapi/test/server/server-cache.ts index 64f8c85e80..6aa612f3f1 100644 --- a/types/hapi/test/server/server-cache.ts +++ b/types/hapi/test/server/server-cache.ts @@ -11,9 +11,9 @@ const catboxOptions: ServerOptionsCache = { expiresIn: 60 * 60 * 1000 }; const cache: catbox.Policy = server.cache(catboxOptions); -cache.set('norway', 'oslo', 10 * 1000, () => {}); +cache.set('norway', 'oslo', 10 * 1000).then(() => {}); -const value = cache.get('norway', () => {}); +const value = cache.get('norway').then(() => {}); console.log("Value: " + value); server.start(); diff --git a/types/hapi/tsconfig.json b/types/hapi/tsconfig.json index f8db3fc828..c93f0dfc7f 100644 --- a/types/hapi/tsconfig.json +++ b/types/hapi/tsconfig.json @@ -13,11 +13,6 @@ "../" ], "types": [], - "paths": { - "boom": [ - "boom/v4" - ] - }, "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/types/hapi/v16/tsconfig.json b/types/hapi/v16/tsconfig.json index 517d678910..23087e8eff 100644 --- a/types/hapi/v16/tsconfig.json +++ b/types/hapi/v16/tsconfig.json @@ -17,6 +17,9 @@ "boom": [ "boom/v4" ], + "catbox": [ + "catbox/v7" + ], "hapi": [ "hapi/v16" ], diff --git a/types/inert/tsconfig.json b/types/inert/tsconfig.json index 238aa1a3eb..866d1c4884 100644 --- a/types/inert/tsconfig.json +++ b/types/inert/tsconfig.json @@ -13,11 +13,6 @@ "../" ], "types": [], - "paths": { - "boom": [ - "boom/v4" - ] - }, "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/types/inert/v4/tsconfig.json b/types/inert/v4/tsconfig.json index fd468493b4..f742ec35d5 100644 --- a/types/inert/v4/tsconfig.json +++ b/types/inert/v4/tsconfig.json @@ -17,6 +17,9 @@ "boom": [ "boom/v4" ], + "catbox": [ + "catbox/v7" + ], "hapi": [ "hapi/v16" ], diff --git a/types/nes/tsconfig.json b/types/nes/tsconfig.json index 05fc49c647..18fc2712d8 100644 --- a/types/nes/tsconfig.json +++ b/types/nes/tsconfig.json @@ -13,11 +13,6 @@ "../" ], "types": [], - "paths": { - "boom": [ - "boom/v4" - ] - }, "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/types/optics-agent/tsconfig.json b/types/optics-agent/tsconfig.json index 010406be2f..046bfaad81 100644 --- a/types/optics-agent/tsconfig.json +++ b/types/optics-agent/tsconfig.json @@ -13,11 +13,6 @@ "../" ], "types": [], - "paths": { - "boom": [ - "boom/v4" - ] - }, "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/types/swagger-express-mw/tsconfig.json b/types/swagger-express-mw/tsconfig.json index c1db9f10a4..de623e0eca 100644 --- a/types/swagger-express-mw/tsconfig.json +++ b/types/swagger-express-mw/tsconfig.json @@ -17,6 +17,9 @@ "boom": [ "boom/v4" ], + "catbox": [ + "catbox/v7" + ], "hapi": [ "hapi/v16" ], diff --git a/types/swagger-hapi/tsconfig.json b/types/swagger-hapi/tsconfig.json index df8e735e23..0b6f0cf5ed 100644 --- a/types/swagger-hapi/tsconfig.json +++ b/types/swagger-hapi/tsconfig.json @@ -17,6 +17,9 @@ "boom": [ "boom/v4" ], + "catbox": [ + "catbox/v7" + ], "hapi": [ "hapi/v16" ], diff --git a/types/swagger-node-runner/tsconfig.json b/types/swagger-node-runner/tsconfig.json index d8bb8c8f52..43f153e823 100644 --- a/types/swagger-node-runner/tsconfig.json +++ b/types/swagger-node-runner/tsconfig.json @@ -17,6 +17,9 @@ "boom": [ "boom/v4" ], + "catbox": [ + "catbox/v7" + ], "hapi": [ "hapi/v16" ], diff --git a/types/swagger-restify-mw/tsconfig.json b/types/swagger-restify-mw/tsconfig.json index ec732988fc..89ba456bbf 100644 --- a/types/swagger-restify-mw/tsconfig.json +++ b/types/swagger-restify-mw/tsconfig.json @@ -17,6 +17,9 @@ "boom": [ "boom/v4" ], + "catbox": [ + "catbox/v7" + ], "hapi": [ "hapi/v16" ], diff --git a/types/swagger-sails-hook/tsconfig.json b/types/swagger-sails-hook/tsconfig.json index 98768dd651..0fd1188f61 100644 --- a/types/swagger-sails-hook/tsconfig.json +++ b/types/swagger-sails-hook/tsconfig.json @@ -17,6 +17,9 @@ "boom": [ "boom/v4" ], + "catbox": [ + "catbox/v7" + ], "hapi": [ "hapi/v16" ], diff --git a/types/vision/tsconfig.json b/types/vision/tsconfig.json index 8f34e356c5..3c6377bfea 100644 --- a/types/vision/tsconfig.json +++ b/types/vision/tsconfig.json @@ -13,11 +13,6 @@ "../" ], "types": [], - "paths": { - "boom": [ - "boom/v4" - ] - }, "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/types/vision/v4/tsconfig.json b/types/vision/v4/tsconfig.json index 2ab1f666a0..832edc4057 100644 --- a/types/vision/v4/tsconfig.json +++ b/types/vision/v4/tsconfig.json @@ -17,6 +17,9 @@ "boom": [ "boom/v4" ], + "catbox": [ + "catbox/v7" + ], "hapi": [ "hapi/v16" ], diff --git a/types/yar/tsconfig.json b/types/yar/tsconfig.json index 3843d1296e..c2723ded55 100644 --- a/types/yar/tsconfig.json +++ b/types/yar/tsconfig.json @@ -13,11 +13,6 @@ "../" ], "types": [], - "paths": { - "boom": [ - "boom/v4" - ] - }, "noEmit": true, "forceConsistentCasingInFileNames": true }, From 23798c59adf80973f97f7406bb56dcf98c9a8255 Mon Sep 17 00:00:00 2001 From: Tom Wanzek Date: Mon, 26 Feb 2018 13:30:06 -0500 Subject: [PATCH 104/128] refactor(d3-collection): refine and reduce technical debt (mulligan) (#23724) * chore(d3-collection): validate for strictNullChecks * feat(d3-collection) minimum TS 2.3 for object type BREAKING CHANGE: Impose minimum of TypeScript 2.3 to be able to use `object` type and generic defaults. (Possibly also use `keyof`). Replace `any` with `object` where it is too wide. Add `ArrayLike` to some signatures. Update tests. * feat(d3-collection) use generic defaults Use generic defaults and remove some outdated comments. * doc(d3-collection): complete JSDoc comments Completes JSDoc comments. Removes a superfluous signature for `keys`. --- types/d3-collection/d3-collection-tests.ts | 21 +- types/d3-collection/index.d.ts | 442 +++++++++++++++++++-- types/d3-collection/tsconfig.json | 4 +- 3 files changed, 418 insertions(+), 49 deletions(-) diff --git a/types/d3-collection/d3-collection-tests.ts b/types/d3-collection/d3-collection-tests.ts index 91a72479db..b2e6c2f68b 100644 --- a/types/d3-collection/d3-collection-tests.ts +++ b/types/d3-collection/d3-collection-tests.ts @@ -38,6 +38,7 @@ let booleanFlag: boolean; // test keys(...) signatures ------------------------------------------------------ stringArray = d3Collection.keys(keyValueObj); +stringArray = d3Collection.keys([0, 1, 2]); stringArray = d3Collection.keys(document); // purely for the fun of it @@ -48,17 +49,21 @@ anyArray = d3Collection.values(keyValueObj); stringArray = d3Collection.values(keyValueObj2); stringArray = d3Collection.values(keyValueObj2); +// stringArray = d3Collection.values(keyValueObj); // test fails, as values in keyValueObj do not meet generic constraint +stringArray = d3Collection.values(['1', '2']); anyArray = d3Collection.values(document); // purely for the fun of it // test entries(...) signatures ------------------------------------------------------ anyKVArray = d3Collection.entries(keyValueObj); -// stringKVArray = d3Collection.entres(keyValueObj); // test fails, as values in keyValueObj are not all strings +// stringKVArray = d3Collection.entries(keyValueObj); // test fails, as values in keyValueObj are not all strings stringKVArray = d3Collection.entries(keyValueObj2); stringKVArray = d3Collection.entries(keyValueObj2); +// stringKVArray = d3Collection.entries(keyValueObj); // test fails, as values in keyValueObj do not meet generic constraint +stringKVArray = d3Collection.entries(['1', '2']); anyKVArray = d3Collection.entries(document); // purely for the fun of it // --------------------------------------------------------------------- @@ -70,13 +75,15 @@ interface TestObject { val: number; } -let testObject: TestObject; +let testObjectMaybe: TestObject | undefined; let testObjArray: TestObject[]; let testObjKVArray: Array<{ key: string, value: TestObject }>; // Create Map ======================================================== let basicMap: d3Collection.Map; +let anyMap: d3Collection.Map; +anyMap = d3Collection.map(); // empty map basicMap = d3Collection.map(); // empty map // from array with accessor without accessor @@ -107,7 +114,7 @@ booleanFlag = basicMap.has('foo'); // get(...) ------------------------------------------------------------ -testObject = testObjMap.get('foo'); +testObjectMaybe = testObjMap.get('foo'); // set(...) ------------------------------------------------------------ @@ -304,11 +311,11 @@ let testL1NestedMapRollup: TestL1NestedMapRollup; testL2NestedMap = nestL2.map(raw); -num = testL2NestedMap.get('1931').get('Manchuria')[0].yield; // access chain to leaf property +num = testL2NestedMap.get('1931')!.get('Manchuria')![0].yield; // use existence assertion with care for access chain to leaf property testL1NestedMapRollup = nestL1Rollup.map(raw); -num = testL1NestedMapRollup.get('1931'); // get rollup value +num = testL1NestedMapRollup.get('1931')!; // get rollup value (use existence assertion with care) // object(...) -------------------------------------------------------- @@ -345,7 +352,7 @@ type TestL2NestedArray = Array<{ type TestL1NestedArrayRollup = Array<{ key: string; - value: number; + value?: number; // conservatively allow for value to be undefined }>; let testL2NestedArray: TestL2NestedArray; @@ -357,4 +364,4 @@ num = testL2NestedArray[0].values[0].values[0].yield; // access chain to leaf pr testL1NestedArrayRollup = nestL1Rollup.entries(raw); -num = testL1NestedArrayRollup[0].value; // get rollup value +num = testL1NestedArrayRollup[0].value!; // get rollup value use existence assertion with care diff --git a/types/d3-collection/index.d.ts b/types/d3-collection/index.d.ts index e389862394..5e7973e03b 100644 --- a/types/d3-collection/index.d.ts +++ b/types/d3-collection/index.d.ts @@ -2,8 +2,9 @@ // Project: https://github.com/d3/d3-collection/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -// Last module patch version validated against: 1.0.1 +// Last module patch version validated against: 1.0.4 /** * Reference type things that can be coerced to string implicitely @@ -16,106 +17,467 @@ export interface Stringifiable { // Objects // --------------------------------------------------------------------- -export function keys(object: { [key: string]: any }): string[]; -// TODO: When upgrading definitions to use TS 2.2+, use "object" data type in next line -export function keys(object: any): string[]; +/** + * Returns an array containing the property names of the specified object (an associative array). + * The order of the returned array is undefined. + * + * @param obj An object. + */ +export function keys(obj: object): string[]; -export function values(object: { [key: string]: T }): T[]; -// TODO: When upgrading definitions to use TS 2.2+, use "object" data type in next line -export function values(object: any): any[]; +/** + * Returns an array containing the property values of the specified object (an associative array). + * The order of the returned array is undefined. + * + * The generic refers to the data type of the values. + * + * @param obj An object. + */ +export function values(obj: { [key: string]: T } | ArrayLike): T[]; +/** + * Returns an array containing the property values of the specified object (an associative array). + * The order of the returned array is undefined. + * + * @param obj An object. + */ +export function values(obj: object): any[]; -export function entries(object: { [key: string]: T }): Array<{ key: string, value: T }>; -// TODO: When upgrading definitions to use TS 2.2+, use "object" data type in next line -export function entries(object: any): Array<{ key: string, value: any }>; +/** + * Returns an array containing the property keys and values of the specified object (an associative array). + * Each entry is an object with a key and value attribute.The order of the returned array is undefined. + * + * The generic refers to the data type of the values. + * + * @param obj An object. + */ +export function entries(obj: { [key: string]: T } | ArrayLike): Array<{ key: string, value: T }>; +/** + * Returns an array containing the property keys and values of the specified object (an associative array). + * Each entry is an object with a key and value attribute.The order of the returned array is undefined. + * + * @param obj An object. + */ +export function entries(obj: object): Array<{ key: string, value: any }>; // --------------------------------------------------------------------- // map / Map // --------------------------------------------------------------------- +/** + * A datastructure similar to ES6 Maps, but with a few differences: + * - Keys are coerced to strings. + * - map.each, not map.forEach. (Also, no thisArg.) + * - map.remove, not map.delete. + * - map.entries returns an array of {key, value} objects, not an iterator of [key, value]. + * - map.size is a method, not a property; also, there’s map.empty. + * + * The generic refers to the data type of the map entry values. + */ export interface Map { + /** + * Returns true if and only if this map has an entry for the specified key string. + * Note: the value may be null or undefined. + * + * @param key Key of map entry to access. + */ has(key: string): boolean; + /** + * Returns the value for the specified key string. + * If the map does not have an entry for the specified key, returns undefined. + * + * @param key Key of map entry to access. + */ get(key: string): T | undefined; + /** + * Sets the value for the specified key string and returns the updated map. + * If the map previously had an entry for the same key string, the old entry is replaced with the new value. + * + * @param key Key of map entry to access. + * @param value Value to set for entry at key. + */ set(key: string, value: T): this; + /** + * If the map has an entry for the specified key string, removes the entry and returns true. + * Otherwise, this method does nothing and returns false. + * + * @param key Map key for which to remove the entry. + */ remove(key: string): boolean; + /** + * Removes all entries from this map. + */ clear(): void; + /** + * Returns an array of string keys for every entry in this map. + * The order of the returned keys is arbitrary. + */ keys(): string[]; + /** + * Returns an array of values for every entry in this map. + * The order of the returned values is arbitrary. + */ values(): T[]; + /** + * Returns an array of key-value objects for each entry in this map. The order of the returned entries is arbitrary. + * Each entry’s key is a string, but the value can have arbitrary type. + */ entries(): Array<{ key: string, value: T }>; + /** + * Calls the specified function for each entry in this map and returns undefined. + * The iteration order is arbitrary. + * + * @param func Function to call for each entry. The function is passed the entry’s value and key as arguments, + * followed by the map itself. + */ each(func: (value: T, key: string, map: Map) => void): void; + /** + * Returns true if and only if this map has zero entries. + */ empty(): boolean; + /** + * Returns the number of entries in this map. + */ size(): number; } -export function map(): Map; +/** + * Constructs a new empty map. + * + * The generic refers to the data type of the map entry values. + */ +export function map(): Map; +/** + * Constructs a new map by copying another map. + * + * The generic refers to the data type of the map entry values. + * + * @param d3Map A D3 Map. + */ export function map(d3Map: Map): Map; -export function map(object: { [key: string]: T }): Map; -export function map(object: { [key: number]: T }): Map; +/** + * Constructs a new map by copying all enumerable properties from the specified object into this map. + * + * The generic refers to the data type of the map entry values. + * + * @param obj Object to construct the map from. + */ +export function map(obj: { [key: string]: T }): Map; +/** + * Constructs a new map by copying all enumerable properties from the specified object into this map. + * + * The generic refers to the data type of the map entry values. + * + * @param obj Object to construct the map from. + */ +export function map(obj: { [key: number]: T }): Map; +/** + * Constructs a new map from the elements of an array. + * An optional key function may be specified to compute the key for each value in the array. + * + * The generic refers to the data type of the map entry values. + * + * @param array Array to convert into a map + * @param key An optional key function. The functions is invoked for each element in the array being passed + * the element's value , it's zero-based index in the array, and the array itself. The function must return a unique string + * to be used as the map entry's key. + */ export function map(array: T[], key?: (value: T, i?: number, array?: T[]) => string): Map; -export function map(object: any): Map; // TODO: When upgrading definitions to use TS 2.2+, use "object" data type for argument +/** + * Constructs a new map by copying all enumerable properties from the specified object into this map. + * + * @param obj Object to construct the map from. + */ +export function map(obj: object): Map; // --------------------------------------------------------------------- // set / Set // --------------------------------------------------------------------- +/** + * A datastructure similar to ES6 Sets, but with a few differences: + * + * - Values are coerced to strings. + * - set.each, not set.forEach. (Also, no thisArg.) + * - set.remove, not set.delete. + * - set.size is a method, not a property; also, there’s set.empty. + */ export interface Set { + /** + * Returns true if and only if this set has an entry for the specified value string. + * + * @param value Value whose membership in the class to test. + */ has(value: string | Stringifiable): boolean; + /** + * Adds the specified value string to this set and returns the set. + * + * @param value Value to add to set. + */ add(value: string | Stringifiable): this; + /** + * If the set contains the specified value string, removes it and returns true. + * Otherwise, this method does nothing and returns false. + * + * @param value Value to remove from set. + */ remove(value: string | Stringifiable): boolean; + /** + * Removes all values from this set. + */ clear(): void; + /** + * Returns an array of the string values in this set. The order of the returned values is arbitrary. + * Can be used as a convenient way of computing the unique values for a set of strings. + */ values(): string[]; /** - * The first and second parameter of the function are both passed - * the 'value' of the set entry for consistency with map.each(...) - * signature + * Calls the specified function for each value in this set, passing the value as the first two arguments (for symmetry with map.each), + * followed by the set itself. Returns undefined. + * The iteration order is arbitrary. + * + * @param func Function to call for each set element. The first and second argument of the function are both passed + * the 'value' of the set entry for consistency with the map.each(...) signature, as a third argument the entire set is passed in. */ each(func: (value: string, valueRepeat: string, set: Set) => void): void; + /** + * Returns true if and only if this set has zero values. + */ empty(): boolean; + /** + * Returns the number of values in this set. + */ size(): number; } +/** + * Constructs a new empty set. + */ export function set(): Set; +/** + * Constructs a new set by copying an existing set. + * + * @param set A D3 set. + */ export function set(d3Set: Set): Set; +/** + * Constructs a new set by adding the given array of string values to the returned set. + * + * @param array An array of strings of values which can be implicitly converted to strings. + */ export function set(array: Array): Set; -export function set(array: T[], key: (value: T, index?: number, array?: T[]) => string): Set; +/** + * Constructs a new set from an array, adds an array of mapped string values to the returned set. + * The specified accessor function is invoked equivalent to calling array.map(accessor) before constructing the set. + * + * The generic refers to the data type of the array elements. + * + * @param array An Array of values to map and add as set elements. + * @param key An accessor function used to map the original array elements to string elements to be added to the set. + * The function is invoked for each array element, being passed the element's value, it's zero-based index in the array, and the array itself. + */ +export function set(array: T[], key: (value: T, index: number, array: T[]) => string): Set; // --------------------------------------------------------------------- // nest / Nest // --------------------------------------------------------------------- -// NB: the following three interfaces NestedArray, NestedMap and NestedObject provide a more formal definitions -// of the return values provided by Nest.entries(...), Nest.map(...) and Nest.object(...), respectively. However, -// the union types cannot be ex ante simplified without knowledge of the nesting level (number of key(...) operations) -// and whether the data were rolled-up. The latter question also determins whether NestedArray has the 'values' property -// with an array of type Datum at leaf level, or has a rolled-up 'value' property. -// The interfaces are not used as return types, as they are cumbersome to work with on the consuming side (Determining the -// applicable type from the respective union, i. p. for array elements). -// It is preferable to carefully define appropriate use-case-specific interfaces for the variables that -// are assigned the return values of the Nest.entries(...), Nest.map(...) and Nest.object(...) operations. The downside -// is an overly permissive return type. - -// Also note, that the below return types for Nest.entries(...), Nest.map(...) and Nest.object(...) strictly only work, -// if AT LEAST ONE KEY was set. This seems a reasonable constraint in practice, given the intent of the nest operator. -// Otherwise, an additional '| Datum[] | RollupType` would have to be added to the union type. This would cover -// cases (a) without key or rollup (b) without key but with rollup. However, again, the union types make it cumbersome -// without much gain. - +/** + * A more formal defintion of the nested array returned by Nest.entries(...). This data structure is intended as a reference only. + * + * As the union types cannot be ex ante simplified without knowledge + * of the nesting level (number of key(...) operations) and whether the data were rolled-up, this data structure becomes cumbersome + * to use in practice. This is particularly true for discrimiation of array element types. + * The use of the rollup function, or lack thereof, also determines whether NestedArray has the 'values' property + * with an array of type Datum at leaf level, or has a rolled-up 'value' property. + */ // tslint:disable-next-line:no-empty-interface export interface NestedArray extends Array<{ key: string, values: NestedArray | Datum[] | undefined, value: RollupType | undefined }> { } + +/** + * A more formal defintion of the nested array returned by Nest.map(...). This data structure is intended as a reference only. + * + * As the union types cannot be ex ante simplified without knowledge + * of the nesting level (number of key(...) operations) and whether the data were rolled-up, this data structure becomes cumbersome + * to use in practice. + */ // tslint:disable-next-line:no-empty-interface export interface NestedMap extends Map | Datum[] | RollupType> { } + +/** + * A more formal defintion of the nested array returned by Nest.object(...). This data structure is intended as a reference only. + * + * As the union types cannot be ex ante simplified without knowledge + * of the nesting level (number of key(...) operations) and whether the data were rolled-up, this data structure becomes cumbersome + * to use in practice. + */ export interface NestedObject { [key: string]: NestedObject | Datum[] | RollupType; } +/** + * A nest operator for generating nested data structures from arrays. + * + * Nesting allows elements in an array to be grouped into a hierarchical tree structure; + * think of it like the GROUP BY operator in SQL, except you can have multiple levels of grouping, and the resulting output is a tree rather than a flat table. + * The levels in the tree are specified by key functions. The leaf nodes of the tree can be sorted by value, while the internal nodes can be sorted by key. + * An optional rollup function will collapse the elements in each leaf node using a summary function. + * The nest operator is reusable, and does not retain any references to the data that is nested. + * + * The first generic refers to the data type of the array elements on which the nest operator will + * be invoked. + * + * The second generic refers to the data type returned by the roll-up function to be used with the + * nest operator. + */ export interface Nest { + /** + * Registers a new key function and returns this nest operator. + * The key function will be invoked for each element in the input array and must return a string identifier to assign the element to its group. + * Most often, the function is a simple accessor. (Keys functions are not passed the input array index.) + * + * Each time a key is registered, it is pushed onto the end of the internal array of keys, + * and the nest operator applies an additional level of nesting. + * + * @param func A key accessor function being invoked for each element. + */ key(func: (datum: Datum) => string): this; + /** + * Sorts key values for the current key using the specified comparator function, such as d3.ascending or d3.descending. + * + * If no comparator is specified for the current key, the order in which keys will be returned is undefined. + * + * Note that this only affects the result of nest.entries; + * the order of keys returned by nest.map and nest.object is always undefined, regardless of comparator. + * + * @param comparator A comparator function which returns a negative value if, according to the sorting criterion, + * a is less than b, or a positive value if a is greater than b, or 0 if the two values are the same under the sorting criterion. + */ sortKeys(comparator: (a: string, b: string) => number): this; + /** + * Sorts leaf elements using the specified comparator function, such as d3.ascending or d3.descending. + * This is roughly equivalent to sorting the input array before applying the nest operator; + * however it is typically more efficient as the size of each group is smaller. + * + * If no value comparator is specified, elements will be returned in the order they appeared in the input array. + * This applies to nest.map, nest.entries and nest.object. + * + * @param comparator A comparator function which returns a negative value if, according to the sorting criterion, + * a is less than b, or a positive value if a is greater than b, or 0 if the two values are the same under the sorting criterion. + */ sortValues(comparator: (a: Datum, b: Datum) => number): this; + /** + * Specifies a rollup function to be applied on each group of leaf elements and returns this nest operator. + * The return value of the rollup function will replace the array of leaf values in either the associative array returned by nest.map or nest.object; + * for nest.entries, it replaces the leaf entry.values with entry.value. + * + * If a leaf comparator is specified, the leaf elements are sorted prior to invoking the rollup function. + * + * @param func A function computing the rollup value for a group of leaf elements. + */ rollup(func: (values: Datum[]) => RollupType): this; - map(array: Datum[]): Map; // more specifically it returns NestedMap - object(array: Datum[]): { [key: string]: any }; // more specifically it returns NestedObject - entries(array: Datum[]): Array<{ key: string; values: any; value: RollupType | undefined }>; // more specifically it returns NestedArray + /** + * Applies the nest operator to the specified array, returning a nested map. + * + * Each entry in the returned map corresponds to a distinct key value returned by the first key function. + * The entry value depends on the number of registered key functions: if there is an additional key, the value is another map; + * otherwise, the value is the array of elements filtered from the input array that have the given key value. + * + * NOTE: + * + * Strictly speaking the return type of this method is: + * + * (1) NestedMap, if at least one key function was defined, + * + * (2) Datum[], if neither a key nor a rollup function were defined, and + * + * (3) RollupType, if no keys, but a rollup function were defined. + * + * Since (2) and (3) are edge cases with little to no practical relevance, they have been omitted in favour of ease-of-use. + * + * Should you determine that this simplification creates an issue in practice, please file an issue on + * https://github.com/DefinitelyTyped/DefinitelyTyped. + * + * The formal, generalized return type under (1) is cumbersome to work with in practice. The recommended approach + * is to define the type of the variable being assigned the return value using knowledge specific to the use-case at hand. + * I.e. making use of knowing how many keys are applied, and the nature of any roll-up function will make working with + * the variable more meaningful, despite the compromise in type-safety. + * + * @param array An array to create a nested data structure from. + */ + map(array: Datum[]): Map; + /** + * Applies the nest operator to the specified array, returning a nested object. + * Each entry in the returned associative array corresponds to a distinct key value returned by the first key function. + * The entry value depends on the number of registered key functions: if there is an additional key, the value is another associative array; + * otherwise, the value is the array of elements filtered from the input array that have the given key value. + * + * WARNING: this method is unsafe if any of the keys conflict with built-in JavaScript properties, such as __proto__. + * If you cannot guarantee that the keys will be safe, you should use nest.map instead. + * + * NOTE: + * + * Strictly speaking the return type of this method is: + * + * (1) NestedObject, if at least one key function was defined, + * + * (2) Datum[], if neither a key nor a rollup function were defined, and + * + * (3) RollupType, if no keys, but a rollup function were defined. + * + * Since (2) and (3) are edge cases with little to no practical relevance, they have been omitted in favour of ease-of-use. + * + * Should you determine that this simplification creates an issue in practice, please file an issue on + * https://github.com/DefinitelyTyped/DefinitelyTyped. + * + * The formal, generalized return type under (1) is cumbersome to work with in practice. The recommended approach + * is to define the type of the variable being assigned the return value using knowledge specific to the use-case at hand. + * I.e. making use of knowing how many keys are applied, and the nature of any roll-up function will make working with + * the variable more meaningful, despite the compromise in type-safety. + * + * @param array An array to create a nested data structure from. + */ + object(array: Datum[]): { [key: string]: any }; + /** + * Applies the nest operator to the specified array, returning an array of key-values entries. + * Conceptually, this is similar to applying map.entries to the associative array returned by nest.map, + * but it applies to every level of the hierarchy rather than just the first (outermost) level. + * Each entry in the returned array corresponds to a distinct key value returned by the first key function. + * The entry value depends on the number of registered key functions: if there is an additional key, the value is another nested array of entries; + * otherwise, the value is the array of elements filtered from the input array that have the given key value. + * + * NOTE: + * + * Strictly speaking the return type of this method is: + * + * (1) NestedArray, if at least one key function was defined, + * + * (2) Datum[], if neither a key nor a rollup function were defined, and + * + * (3) RollupType, if no keys, but a rollup function were defined. + * + * Since (2) and (3) are edge cases with little to no practical relevance, they have been omitted in favour of ease-of-use. + * + * Should you determine that this simplification creates an issue in practice, please file an issue on + * https://github.com/DefinitelyTyped/DefinitelyTyped. + * + * The formal, generalized return type under (1) is cumbersome to work with in practice. The recommended approach + * is to define the type of the variable being assigned the return value using knowledge specific to the use-case at hand. + * I.e. making use of knowing how many keys are applied, and the nature of any roll-up function will make working with + * the variable more meaningful, despite the compromise in type-safety. + * + * @param array An array to create a nested data structure from. + */ + entries(array: Datum[]): Array<{ key: string; values: any; value: RollupType | undefined }>; } -export function nest(): Nest; -export function nest(): Nest; +/** + * Creates a new nest operator. + * + * The first generic refers to the data type of the array elements on which the nest operator will + * be invoked. + * + * The second generic refers to the data type returned by the roll-up function to be used with the + * nest operator. If not explicitly set, this generic parameter defaults to undefined, implying that + * no rollup function will be applied. + */ +export function nest(): Nest; diff --git a/types/d3-collection/tsconfig.json b/types/d3-collection/tsconfig.json index c2ae30cdbd..7d3824f371 100644 --- a/types/d3-collection/tsconfig.json +++ b/types/d3-collection/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "d3-collection-tests.ts" ] -} \ No newline at end of file +} From 1a3679e14cd0e4fe2092c7eb9cbe3a9bfeae8168 Mon Sep 17 00:00:00 2001 From: Justin Simms <526791+jhsimms@users.noreply.github.com> Date: Mon, 26 Feb 2018 13:28:41 -0600 Subject: [PATCH 105/128] Hapi 17: Fix inability to augment server.plugins type (#23855) * Fix inability to augment server.plugins type * Replacing more 'any' types and other misc fixes * Change server.inject to use ApplicationState --- types/hapi/index.d.ts | 37 +++++++++++++++++++---- types/hapi/test/request/query.ts | 13 ++++---- types/hapi/test/route/route-options.ts | 12 +++++++- types/hapi/test/server/server-app.ts | 2 +- types/hapi/test/server/server-expose.ts | 14 +++++++++ types/hapi/test/server/server-inject.ts | 13 ++++++++ types/hapi/test/server/server-method.ts | 3 +- types/hapi/test/server/server-options.ts | 8 +++++ types/hapi/test/server/server-plugins.ts | 9 ++++++ types/hapi/test/server/server-settings.ts | 6 ++++ 10 files changed, 101 insertions(+), 16 deletions(-) diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 01586dd3bf..aebef5e5d8 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -334,6 +334,10 @@ export interface RequestLog { channel: string; } +export interface RequestQuery { + [key: string]: string | string[]; +} + /** * The request object is created internally for each incoming request. It is not the same object received from the node * HTTP server callback (which is available via [request.raw.req](https://github.com/hapijs/hapi/blob/master/API.md#request.raw)). The request properties change throughout @@ -464,7 +468,7 @@ export interface Request extends Podium { * By default the object outputted from node's URL parse() method. Might also be set indirectly via request.setUrl in which case it may be a string (if url is set to an object with the query * attribute as an unparsed string). */ - readonly query: any; + readonly query: RequestQuery | string; /** * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended. @@ -1629,6 +1633,13 @@ export interface RouteOptionsValidate { */ export type RouteCompressionEncoderSettings = object; +/** + * Empty interface to allow for user-defined augmentations. + */ +/* tslint:disable-next-line:no-empty-interface */ +export interface RouteOptionsApp { +} + /** * Each route can be customized to change the default behavior of the request lifecycle. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#route-options) @@ -1638,7 +1649,7 @@ export interface RouteOptions { * Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) */ - app?: any; + app?: RouteOptionsApp; /** * Route authentication configuration. Value can be: @@ -2574,7 +2585,7 @@ export interface ServerInjectOptions extends Shot.RequestOptions { /** * sets the initial value of request.app, defaults to {}. */ - app?: any; + app?: ApplicationState; /** * sets the initial value of request.plugins, defaults to {}. */ @@ -2656,7 +2667,7 @@ export interface ServerMethodOptions { * unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which * takes the same arguments as the function and returns a unique string (or null if no key can be generated). */ - generateKey?: (...args: any[]) => any; + generateKey?: (...args: any[]) => string | null; } /** @@ -2710,6 +2721,13 @@ export interface ServerOptionsCompression { minBytes: number; } +/** + * Empty interface to allow for custom augmentation. + */ +/* tslint:disable-next-line:no-empty-interface */ +export interface ServerOptionsApp { +} + /** * The server options control the behavior of the server object. Note that the options object is deeply cloned * (with the exception of listener which is shallowly copied) and should not contain any values that are unsafe to perform deep copy on. @@ -2732,7 +2750,7 @@ export interface ServerOptions { * state. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsapp) */ - app?: any; + app?: ServerOptionsApp; /** * Default value: true. @@ -3212,6 +3230,13 @@ export interface HandlerDecorationMethod { */ export type DecorationMethod = (this: T, ...args: any[]) => any; +/** + * An empty interface to allow typings of custom plugin properties. + */ +/* tslint:disable-next-line:no-empty-interface */ +export interface PluginProperties { +} + /** * The server object is the main application container. The server manages all incoming requests along with all * the facilities provided by the framework. Each server supports a single connection (e.g. listen to port 80). @@ -3363,7 +3388,7 @@ export class Server extends Podium { * the server.plugins[name] object directly or via the server.expose() method. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins) */ - plugins: any; + plugins: PluginProperties; /** * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When diff --git a/types/hapi/test/request/query.ts b/types/hapi/test/request/query.ts index c67381f1b9..090ab3ae8d 100644 --- a/types/hapi/test/request/query.ts +++ b/types/hapi/test/request/query.ts @@ -1,14 +1,17 @@ // Added test in addition to docs, for request.query -import { Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; +import { Lifecycle, Request, RequestQuery, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; const options: ServerOptions = { port: 8000, }; const handlerFn: Lifecycle.Method = (request, h) => { - const query = request.query as GetThingQuery; + const query1 = request.query as string; + console.log(query1); + + const query2 = request.query as RequestQuery; // http://localhost:8000/?name=test - return `You asked for ${query.name}`; + return `You asked for ${query2.name}`; }; const serverRoute: ServerRoute = { @@ -17,10 +20,6 @@ const serverRoute: ServerRoute = { handler: handlerFn }; -interface GetThingQuery { - name: string; -} - const server = new Server(options); server.route(serverRoute); server.start(); diff --git a/types/hapi/test/route/route-options.ts b/types/hapi/test/route/route-options.ts index 96237debd8..d114154e60 100644 --- a/types/hapi/test/route/route-options.ts +++ b/types/hapi/test/route/route-options.ts @@ -102,8 +102,18 @@ const routeOptionsValidate: RouteOptionsValidate = { query: true, }; +declare module 'hapi' { + interface RouteOptionsApp { + one: number; + two: string; + } +} + const routeOptions: RouteOptions = { - app: {}, + app: { + one: 1, + two: "2" + }, auth: routeOptionsAccess, bind: null, cache: { diff --git a/types/hapi/test/server/server-app.ts b/types/hapi/test/server/server-app.ts index f51ad7ca12..8e9cff88b0 100644 --- a/types/hapi/test/server/server-app.ts +++ b/types/hapi/test/server/server-app.ts @@ -8,7 +8,7 @@ const options: ServerOptions = { declare module "hapi" { // Demonstrate augmenting the application state. interface ApplicationState { - key: string; + key?: string; } } diff --git a/types/hapi/test/server/server-expose.ts b/types/hapi/test/server/server-expose.ts index c1a698b6c7..43d6cfdaa6 100644 --- a/types/hapi/test/server/server-expose.ts +++ b/types/hapi/test/server/server-expose.ts @@ -1,6 +1,17 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins import { Plugin, Server, ServerRegisterOptions } from "hapi"; +declare module 'hapi' { + interface PluginProperties { + example1: { + util(): void; + }; + example2: { + util(): void; + }; + } +} + const plugin1: Plugin = { name: 'example1', async register(server: Server, options: ServerRegisterOptions) { @@ -22,3 +33,6 @@ const server = new Server({ server.start(); server.register(plugin1); server.register(plugin2); + +server.plugins.example1.util(); +server.plugins.example2.util(); diff --git a/types/hapi/test/server/server-inject.ts b/types/hapi/test/server/server-inject.ts index 5c7942c16a..a2ae777a71 100644 --- a/types/hapi/test/server/server-inject.ts +++ b/types/hapi/test/server/server-inject.ts @@ -17,3 +17,16 @@ server.route(serverRoute); server.start(); server.inject('/').then(res => console.log(res.result)); + +declare module 'hapi' { + interface ApplicationState { + injectState?: number; + } +} + +server.inject({ + url: "test", + app: { + injectState: 1 + } +}); diff --git a/types/hapi/test/server/server-method.ts b/types/hapi/test/server/server-method.ts index 2d2b3bdf58..bb729516b7 100644 --- a/types/hapi/test/server/server-method.ts +++ b/types/hapi/test/server/server-method.ts @@ -17,7 +17,8 @@ const methodObject: ServerMethodConfigurationObject = { cache: { expiresIn: 2000, generateTimeout: 100 - } + }, + generateKey: (a: string | undefined) => a === undefined ? null : a } }; diff --git a/types/hapi/test/server/server-options.ts b/types/hapi/test/server/server-options.ts index ce487bbb20..030c721103 100644 --- a/types/hapi/test/server/server-options.ts +++ b/types/hapi/test/server/server-options.ts @@ -54,6 +54,14 @@ const routeOptions: RouteOptions = { }, }; +declare module 'hapi' { + interface ServerOptionsApp { + key1?: string; + key2?: string; + any_thing?: string; + } +} + const options: ServerOptions = { address: '0.0.0.0', app: { diff --git a/types/hapi/test/server/server-plugins.ts b/types/hapi/test/server/server-plugins.ts index 970b53fb6d..7f3d194f84 100644 --- a/types/hapi/test/server/server-plugins.ts +++ b/types/hapi/test/server/server-plugins.ts @@ -13,6 +13,15 @@ interface Plugin3 { three: 3; } +declare module 'hapi' { + interface PluginProperties { + example: { + other: string; + key: string; + }; + } +} + const plugin1: Plugin = { name: 'plugin1', register: async (server: Server, options: Plugin1) => { diff --git a/types/hapi/test/server/server-settings.ts b/types/hapi/test/server/server-settings.ts index 488e31629b..f0619d95da 100644 --- a/types/hapi/test/server/server-settings.ts +++ b/types/hapi/test/server/server-settings.ts @@ -1,6 +1,12 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-serversettings import { Server } from "hapi"; +declare module 'hapi' { + interface ServerOptionsApp { + key?: string; + } +} + const server = new Server({ port: 8000, app: { From 1ac7e292449bff6b2547915a23e77b1744974f84 Mon Sep 17 00:00:00 2001 From: Alexander Marks Date: Mon, 26 Feb 2018 11:28:57 -0800 Subject: [PATCH 106/128] Add EOL to WriteOptions. (#23831) Added in 4.0.2: https://github.com/jprichardson/node-fs-extra/blob/master/CHANGELOG.md#402--2017-09-12 Documented here: https://github.com/jprichardson/node-fs-extra/blob/master/docs/writeJson.md --- types/fs-extra/index.d.ts | 1 + types/fs-extra/v4/index.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/types/fs-extra/index.d.ts b/types/fs-extra/index.d.ts index f556afa82f..6183dce393 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -290,6 +290,7 @@ export interface WriteOptions extends WriteFileOptions { fs?: object; replacer?: any; spaces?: number | string; + EOL?: string; } export interface ReadResult { diff --git a/types/fs-extra/v4/index.d.ts b/types/fs-extra/v4/index.d.ts index 575df86b4d..e5180a7a94 100644 --- a/types/fs-extra/v4/index.d.ts +++ b/types/fs-extra/v4/index.d.ts @@ -290,6 +290,7 @@ export interface WriteOptions extends WriteFileOptions { fs?: object; replacer?: any; spaces?: number | string; + EOL?: string; } export interface ReadResult { From eac2d77cbb4684c24408e14f3fa5c8adfa1407bc Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 26 Feb 2018 11:31:09 -0800 Subject: [PATCH 107/128] fix version --- types/react-truncate/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-truncate/index.d.ts b/types/react-truncate/index.d.ts index 54618a9a8e..15c72616c0 100644 --- a/types/react-truncate/index.d.ts +++ b/types/react-truncate/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-truncate 2.3.0 +// Type definitions for react-truncate 2.3 // Project: https://github.com/One-com/react-truncate // Definitions by: Matt Perry // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From bf37dfddd26c24b50d846b1a58bb7ea15a1ef212 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 26 Feb 2018 11:32:59 -0800 Subject: [PATCH 108/128] web-animations-js: Make compatible with TypeScript@2.7 (#23793) --- types/web-animations-js/index.d.ts | 66 ++++++++++++++++++++++-------- 1 file changed, 48 insertions(+), 18 deletions(-) diff --git a/types/web-animations-js/index.d.ts b/types/web-animations-js/index.d.ts index 2424e93e92..54c0b8c01b 100644 --- a/types/web-animations-js/index.d.ts +++ b/types/web-animations-js/index.d.ts @@ -5,13 +5,12 @@ type AnimationEffectTimingFillMode = "none" | "forwards" | "backwards" | "both" | "auto"; type AnimationEffectTimingPlaybackDirection = "normal" | "reverse" | "alternate" | "alternate-reverse"; -type AnimationPlayState = "idle" | "pending" | "running" | "paused" | "finished"; +type AnimationPlayState = "idle" | "running" | "paused" | "finished"; -declare class AnimationPlaybackEvent { - constructor(target: Animation, currentTime: number, timelineTime: number); +interface AnimationPlaybackEvent { target: Animation; - currentTime: number; - timelineTime: number; + readonly currentTime: number | null; + readonly timelineTime: number | null; type: string; bubbles: boolean; cancelable: boolean; @@ -21,14 +20,26 @@ declare class AnimationPlaybackEvent { timeStamp: number; } +interface AnimationPlaybackEventInit extends EventInit { + currentTime?: number | null; + timelineTime?: number | null; +} + +declare var AnimationPlaybackEvent: { + prototype: AnimationPlaybackEvent; + new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; +}; + interface AnimationKeyFrame { - easing?: string; - offset?: number; - [key: string]: string | number | [string | number, string | number] | undefined; + easing?: string | string[]; + offset?: number | Array | null; + opacity?: number | number[]; + transform?: string | string[]; + // [key: string]: string | number | [string | number, string | number] | undefined; (duplicate string indexer in TypeScript 2.7+) } interface AnimationTimeline { - currentTime: number; + readonly currentTime: number | null; getAnimations(): Animation[]; play(effect: KeyframeEffect): Animation; } @@ -43,21 +54,35 @@ interface AnimationEffectTiming { iterations?: number; playbackRate?: number; } -declare class KeyframeEffect { + +interface AnimationEffectReadOnly { + readonly timing: number; + getComputedTiming(): ComputedTimingProperties; +} + +interface ComputedTimingProperties { + endTime: number; + activeDuration: number; + localTime: number | null; + progress: number | null; + currentIteration: number | null; +} + +declare class KeyframeEffect implements AnimationEffectReadOnly { constructor(target: HTMLElement, effect: AnimationKeyFrame | AnimationKeyFrame[], timing: number | AnimationEffectTiming, id?: string); activeDuration: number; onsample: (timeFraction: number | null, effect: KeyframeEffect, animation: Animation) => void | undefined; parent: KeyframeEffect | null; target: HTMLElement; - timing: AnimationEffectTiming; + timing: number; + getComputedTiming(): ComputedTimingProperties; getFrames(): AnimationKeyFrame[]; remove(): void; } -type AnimationEventListener = (evt: AnimationPlaybackEvent) => void; +type AnimationEventListener = (this: Animation, evt: AnimationPlaybackEvent) => any; -declare class Animation { - constructor(effect: KeyframeEffect, timeline?: AnimationTimeline); - currentTime: number; +interface Animation extends EventTarget { + currentTime: number | null; id: string; oncancel: AnimationEventListener; onfinish: AnimationEventListener; @@ -69,14 +94,19 @@ declare class Animation { pause(): void; play(): void; reverse(): void; - addEventListener(type: "finish" | "cancel", handler: AnimationEventListener): void; - removeEventListener(type: "finish" | "cancel", handler: AnimationEventListener): void; - effect: KeyframeEffect; + addEventListener(type: "finish" | "cancel", handler: EventListener): void; + removeEventListener(type: "finish" | "cancel", handler: EventListener): void; + effect: AnimationEffectReadOnly; readonly finished: Promise; readonly ready: Promise; timeline: AnimationTimeline; } +declare var Animation: { + prototype: Animation; + new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; +}; + declare class SequenceEffect extends KeyframeEffect { constructor(effects: KeyframeEffect[]); } From 317dfc327ab3c90da8ee6501b96a46d35bb06da0 Mon Sep 17 00:00:00 2001 From: Muhammad Fawwaz Orabi Date: Mon, 26 Feb 2018 21:41:38 +0200 Subject: [PATCH 109/128] Add type definitions for react-redux-epic (#23823) * Add type definitions for react-redux-epic * Require TS 2.6 * Add package.json * Trigger CI * Address feedback * Add tests * Remove unnecessary type paramerters * Fix lint issues * Re-add generics --- types/react-redux-epic/client.d.ts | 7 +++++ types/react-redux-epic/index.d.ts | 22 ++++++++++++++++ types/react-redux-epic/package.json | 7 +++++ .../react-redux-epic-tests.tsx | 26 +++++++++++++++++++ types/react-redux-epic/tsconfig.json | 17 ++++++++++++ types/react-redux-epic/tslint.json | 3 +++ 6 files changed, 82 insertions(+) create mode 100644 types/react-redux-epic/client.d.ts create mode 100644 types/react-redux-epic/index.d.ts create mode 100644 types/react-redux-epic/package.json create mode 100644 types/react-redux-epic/react-redux-epic-tests.tsx create mode 100644 types/react-redux-epic/tsconfig.json create mode 100644 types/react-redux-epic/tslint.json diff --git a/types/react-redux-epic/client.d.ts b/types/react-redux-epic/client.d.ts new file mode 100644 index 0000000000..54535f59ec --- /dev/null +++ b/types/react-redux-epic/client.d.ts @@ -0,0 +1,7 @@ +import * as React from 'react'; +import { Observable } from 'rxjs/Observable'; + +export function render( + element: React.ReactElement, + container: Element +): Observable; diff --git a/types/react-redux-epic/index.d.ts b/types/react-redux-epic/index.d.ts new file mode 100644 index 0000000000..f9bba811f8 --- /dev/null +++ b/types/react-redux-epic/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for react-redux-epic 1.1 +// Project: https://github.com/BerkeleyTrue/react-redux-epic#readme +// Definitions by: forabi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; +import { Observable } from 'rxjs/Observable'; +import { Epic } from 'redux-observable'; + +export interface Action { + type: string; +} + +export function wrapRootEpic( + epic: Epic +): Epic; + +export function renderToString( + element: React.ReactElement, + wrappedEpic: Epic +): Observable<{ markup: string }>; diff --git a/types/react-redux-epic/package.json b/types/react-redux-epic/package.json new file mode 100644 index 0000000000..807e511de4 --- /dev/null +++ b/types/react-redux-epic/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "rxjs": "^5.5.5", + "redux-observable": "^0.18.0" + } +} diff --git a/types/react-redux-epic/react-redux-epic-tests.tsx b/types/react-redux-epic/react-redux-epic-tests.tsx new file mode 100644 index 0000000000..fa1d4f9c77 --- /dev/null +++ b/types/react-redux-epic/react-redux-epic-tests.tsx @@ -0,0 +1,26 @@ +import * as React from 'react'; +import { Epic } from 'redux-observable'; +import { renderToString, wrapRootEpic } from 'react-redux-epic'; +import 'rxjs/add/operator/do'; +import 'rxjs/add/operator/ignoreElements'; + +interface Action { + type: string; + payload: any; +} + +const rootEpic: Epic = action$ => { + return action$ + .do(action => { + // Action dispatched + }) + .ignoreElements(); +}; + +const wrappedRootEpic = wrapRootEpic(rootEpic); + +renderToString(
Hello, world
, wrappedRootEpic).subscribe({ + next({ markup }) { + // Done + } +}); diff --git a/types/react-redux-epic/tsconfig.json b/types/react-redux-epic/tsconfig.json new file mode 100644 index 0000000000..64657de53c --- /dev/null +++ b/types/react-redux-epic/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "jsx": "React", + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "client.d.ts", "react-redux-epic-tests.tsx"] +} diff --git a/types/react-redux-epic/tslint.json b/types/react-redux-epic/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/react-redux-epic/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From cc7370ac0e68f3a629341d9c067496bb0f533de2 Mon Sep 17 00:00:00 2001 From: Fernando Alex Helwanger Date: Mon, 26 Feb 2018 16:44:12 -0300 Subject: [PATCH 110/128] [react-native-loading-spinner-overlay] Add react-native-loading-spinner-overlay typings (#23829) * Add react-native-loading-spinner-overlay typings * Match `react` typescript version --- .../index.d.ts | 21 ++++++++++++++++ ...t-native-loading-spinner-overlay-tests.tsx | 19 +++++++++++++++ .../tsconfig.json | 24 +++++++++++++++++++ .../tslint.json | 1 + 4 files changed, 65 insertions(+) create mode 100644 types/react-native-loading-spinner-overlay/index.d.ts create mode 100644 types/react-native-loading-spinner-overlay/react-native-loading-spinner-overlay-tests.tsx create mode 100644 types/react-native-loading-spinner-overlay/tsconfig.json create mode 100644 types/react-native-loading-spinner-overlay/tslint.json diff --git a/types/react-native-loading-spinner-overlay/index.d.ts b/types/react-native-loading-spinner-overlay/index.d.ts new file mode 100644 index 0000000000..93d511d863 --- /dev/null +++ b/types/react-native-loading-spinner-overlay/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for react-native-loading-spinner-overlay 0.5 +// Project: https://github.com/joinspontaneous/react-native-loading-spinner-overlay +// Definitions by: fhelwanger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from "react"; +import * as ReactNative from "react-native"; + +export interface SpinnerProps { + cancelable?: boolean; + color?: string; + animation?: "none" | "slide" | "fade"; + overlayColor?: string; + size?: "normal" | "small" | "large"; + textContent?: string; + textStyle?: ReactNative.StyleProp; + visible?: boolean; +} + +export default class Spinner extends React.Component {} diff --git a/types/react-native-loading-spinner-overlay/react-native-loading-spinner-overlay-tests.tsx b/types/react-native-loading-spinner-overlay/react-native-loading-spinner-overlay-tests.tsx new file mode 100644 index 0000000000..2b507ccb12 --- /dev/null +++ b/types/react-native-loading-spinner-overlay/react-native-loading-spinner-overlay-tests.tsx @@ -0,0 +1,19 @@ +import * as React from "react"; +import Spinner from "react-native-loading-spinner-overlay"; + +() => { + ; +}; + +() => { + ; +}; diff --git a/types/react-native-loading-spinner-overlay/tsconfig.json b/types/react-native-loading-spinner-overlay/tsconfig.json new file mode 100644 index 0000000000..ef459656dc --- /dev/null +++ b/types/react-native-loading-spinner-overlay/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-native-loading-spinner-overlay-tests.tsx" + ] +} diff --git a/types/react-native-loading-spinner-overlay/tslint.json b/types/react-native-loading-spinner-overlay/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-loading-spinner-overlay/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 22662d514f87a4a1ac64676977997a8c910f9c6d Mon Sep 17 00:00:00 2001 From: scarletsky Date: Tue, 27 Feb 2018 03:46:40 +0800 Subject: [PATCH 111/128] playcanvas: update typings (#23867) --- .../engine/asset/asset-registry.d.ts | 2 +- types/playcanvas/engine/asset/asset.d.ts | 24 +++- types/playcanvas/engine/core/events.d.ts | 8 +- types/playcanvas/engine/core/path.d.ts | 2 +- types/playcanvas/engine/core/platform.d.ts | 2 - .../engine/framework/application.d.ts | 38 ++--- .../components/animation/component.d.ts | 9 +- .../framework/components/component.d.ts | 8 +- .../framework/components/model/component.d.ts | 2 +- .../components/script/component.d.ts | 2 + .../framework/components/sound/component.d.ts | 2 +- types/playcanvas/engine/framework/entity.d.ts | 5 +- types/playcanvas/engine/graphics/device.d.ts | 8 +- types/playcanvas/engine/graphics/texture.d.ts | 3 +- .../engine/graphics/vertex-format.d.ts | 4 +- .../engine/graphics/vertex-iterator.d.ts | 2 + types/playcanvas/engine/input/input.d.ts | 12 +- types/playcanvas/engine/input/mouse.d.ts | 7 +- types/playcanvas/engine/input/touch.d.ts | 7 +- types/playcanvas/engine/math/mat3.d.ts | 2 + types/playcanvas/engine/math/mat4.d.ts | 2 + types/playcanvas/engine/math/vec2.d.ts | 5 +- types/playcanvas/engine/math/vec3.d.ts | 1 + types/playcanvas/engine/math/vec4.d.ts | 2 + .../engine/resources/animation.d.ts | 7 + .../playcanvas/engine/resources/cubemap.d.ts | 7 + types/playcanvas/engine/resources/loader.d.ts | 10 +- .../playcanvas/engine/resources/material.d.ts | 10 ++ types/playcanvas/engine/resources/model.d.ts | 3 + types/playcanvas/engine/resources/script.d.ts | 6 +- .../playcanvas/engine/resources/texture.d.ts | 9 ++ .../engine/scene/basic-material.d.ts | 3 + types/playcanvas/engine/scene/graph-node.d.ts | 11 +- types/playcanvas/engine/scene/material.d.ts | 3 + types/playcanvas/engine/scene/mesh.d.ts | 28 +++- types/playcanvas/engine/scene/model.d.ts | 2 + types/playcanvas/engine/scene/morph.d.ts | 131 ++++++++++++++++++ types/playcanvas/engine/scene/procedural.d.ts | 16 +-- types/playcanvas/engine/scene/scene.d.ts | 4 +- types/playcanvas/engine/script/script.d.ts | 32 ++--- types/playcanvas/engine/scriptype.d.ts | 6 +- .../playcanvas/engine/shape/bounding-box.d.ts | 6 +- .../engine/shape/bounding-sphere.d.ts | 2 +- .../playcanvas/engine/shape/oriented-box.d.ts | 2 +- types/playcanvas/engine/shape/plane.d.ts | 7 +- types/playcanvas/engine/vr/vr-display.d.ts | 6 +- types/playcanvas/index.d.ts | 8 +- 47 files changed, 373 insertions(+), 105 deletions(-) create mode 100644 types/playcanvas/engine/resources/animation.d.ts create mode 100644 types/playcanvas/engine/resources/cubemap.d.ts create mode 100644 types/playcanvas/engine/resources/material.d.ts create mode 100644 types/playcanvas/engine/resources/texture.d.ts create mode 100644 types/playcanvas/engine/scene/morph.d.ts diff --git a/types/playcanvas/engine/asset/asset-registry.d.ts b/types/playcanvas/engine/asset/asset-registry.d.ts index 47dede11a3..f4722ee490 100644 --- a/types/playcanvas/engine/asset/asset-registry.d.ts +++ b/types/playcanvas/engine/asset/asset-registry.d.ts @@ -166,4 +166,4 @@ declare namespace pc { */ find(name: string, type?: string): pc.Asset; } -} +} \ No newline at end of file diff --git a/types/playcanvas/engine/asset/asset.d.ts b/types/playcanvas/engine/asset/asset.d.ts index 3a5e514a6c..bfc51ff99f 100644 --- a/types/playcanvas/engine/asset/asset.d.ts +++ b/types/playcanvas/engine/asset/asset.d.ts @@ -1,5 +1,19 @@ declare namespace pc { + const ASSET_ANIMATION = 'animation'; + const ASSET_AUDIO = 'audio'; + const ASSET_IMAGE = 'image'; + const ASSET_JSON = 'json'; + const ASSET_MODEL = 'model'; + const ASSET_MATERIAL = 'material'; + const ASSET_TEXT = 'text'; + const ASSET_TEXTURE = 'texture'; + const ASSET_CUBEMAP = 'cubemap'; + const ASSET_SHADER = 'shader'; + const ASSET_CSS = 'css'; + const ASSET_HTML = 'html'; + const ASSET_SCRIPT = 'script'; + /** * @name pc.Asset * @class An asset record of a file or data resource that can be loaded by the engine. @@ -77,7 +91,7 @@ declare namespace pc { * }); * app.assets.load(asset); */ - ready(callback: (...args: any[]) => {}, scope: any): void; + ready(callback: (...args: any[]) => void, scope?: any): void; /** * @function @@ -106,7 +120,7 @@ declare namespace pc { * }); * obj.fire('test', 1, 2); // prints 3 to the console */ - on(name: string, callback: (...args: any[]) => void, scope: any): any; + on(name: string, callback: (...args: any[]) => void, scope?: any): any; /** * @function @@ -126,7 +140,7 @@ declare namespace pc { * obj.off('test', handler); // Removes all handler functions, called 'test' * obj.off('test', handler, this); // Removes all hander functions, called 'test' with scope this */ - off(name: string, callback: (...args: any[]) => void, scope: any): any; + off(name: string, callback: (...args: any[]) => void, scope?: any): any; /** * @function @@ -137,7 +151,7 @@ declare namespace pc { * @example * obj.fire('test', 'This is the message'); */ - fire(name: string, arg1: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): any; + fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): any; /** * @function @@ -153,7 +167,7 @@ declare namespace pc { * obj.fire('test', 1, 2); // prints 3 to the console * obj.fire('test', 1, 2); // not going to get handled */ - once(name: string, callback: (...args: any[]) => void, scope: any): any; + once(name: string, callback: (...args: any[]) => void, scope?: any): any; /** * @function diff --git a/types/playcanvas/engine/core/events.d.ts b/types/playcanvas/engine/core/events.d.ts index 21fc207840..7bf4f8b567 100644 --- a/types/playcanvas/engine/core/events.d.ts +++ b/types/playcanvas/engine/core/events.d.ts @@ -43,7 +43,7 @@ declare namespace pc { * }); * obj.fire('test', 1, 2); // prints 3 to the console */ - function on(name: string, callback: (...args: any[]) => void, scope: any): any; + function on(name: string, callback: (...args: any[]) => void, scope?: any): void; /** * @function @@ -63,7 +63,7 @@ declare namespace pc { * obj.off('test', handler); // Removes all handler functions, called 'test' * obj.off('test', handler, this); // Removes all hander functions, called 'test' with scope this */ - function off(name: string, callback: (...args: any[]) => void, scope: any): any; + function off(name: string, callback?: (...args: any[]) => void, scope?: any): void; /** * @function @@ -74,7 +74,7 @@ declare namespace pc { * @example * obj.fire('test', 'This is the message'); */ - function fire(name: string, arg1: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): any; + function fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): void; /** * @function @@ -90,7 +90,7 @@ declare namespace pc { * obj.fire('test', 1, 2); // prints 3 to the console * obj.fire('test', 1, 2); // not going to get handled */ - function once(name: string, callback: (...args: any[]) => void, scope: any): any; + function once(name: string, callback: (...args: any[]) => void, scope?: any): void; /** * @function diff --git a/types/playcanvas/engine/core/path.d.ts b/types/playcanvas/engine/core/path.d.ts index d6fa94abad..e94d8c7133 100644 --- a/types/playcanvas/engine/core/path.d.ts +++ b/types/playcanvas/engine/core/path.d.ts @@ -10,7 +10,7 @@ declare namespace pc { * The character that separates path segments * @name pc.path.delimiter */ - const delimiter = "/", + const delimiter = "/"; /** * Join two sections of file path together, insert a delimiter if needed. * @param {String} one First part of path to join diff --git a/types/playcanvas/engine/core/platform.d.ts b/types/playcanvas/engine/core/platform.d.ts index 15d1995415..f1522c2b90 100644 --- a/types/playcanvas/engine/core/platform.d.ts +++ b/types/playcanvas/engine/core/platform.d.ts @@ -1,5 +1,3 @@ -import { platform } from "os"; - declare namespace pc { /** diff --git a/types/playcanvas/engine/framework/application.d.ts b/types/playcanvas/engine/framework/application.d.ts index 404ce2e71f..6ef4d996d1 100644 --- a/types/playcanvas/engine/framework/application.d.ts +++ b/types/playcanvas/engine/framework/application.d.ts @@ -32,6 +32,8 @@ declare namespace pc { class Application { constructor(canvas: HTMLCanvasElement, options?: pc.ApplicationOptions) + static getApplication(id?: string): Application; + // PROPERTIES /** @@ -207,23 +209,23 @@ declare namespace pc { loadSceneSettings(url: string, callback: (...args: any[]) => {}): void; /** - * @function - * @name pc.Application#loadScene - * @description Load a scene file. - * @param {String} url The URL of the scene file. Usually this will be "scene_id.json" - * @param {Function} callback The function to call after loading, passed (err, entity) where err is null if no errors occurred. - * @example - * - * app.loadScene("1000.json", function (err, entity) { - * if (!err) { - * var e = app.root.find("My New Entity"); - * } else { - * // error - * } - * } - * }); - */ - loadScene(url: string, callback: (...args: any[]) => {}): void; + * @function + * @name pc.Application#loadScene + * @description Load a scene file. + * @param {String} url The URL of the scene file. Usually this will be "scene_id.json" + * @param {Function} callback The function to call after loading, passed (err, entity) where err is null if no errors occurred. + * @example + * + * app.loadScene("1000.json", function (err, entity) { + * if (!err) { + * var e = app.root.find("My New Entity"); + * } else { + * // error + * } + * } + * }); + */ + loadScene(url: string, callback: (...args: any[]) => {}): void; /** * @function @@ -497,7 +499,7 @@ declare namespace pc { * @example * obj.fire('test', 'This is the message'); */ - fire(name: string, arg1: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): any; + fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): any; /** * @function diff --git a/types/playcanvas/engine/framework/components/animation/component.d.ts b/types/playcanvas/engine/framework/components/animation/component.d.ts index 5060499b3d..ca0547b6fe 100644 --- a/types/playcanvas/engine/framework/components/animation/component.d.ts +++ b/types/playcanvas/engine/framework/components/animation/component.d.ts @@ -20,9 +20,14 @@ declare namespace pc { speed: number; loop: boolean; activate: boolean; - assets: pc.Asset[]; + assets: number[]; currentTime: number; duration: number; + playing: boolean; + currAnim: string; + + animations: any; + animationsIndex: any; /** * @function @@ -32,7 +37,7 @@ declare namespace pc { * @param {Number} [blendTime] The time in seconds to blend from the current * animation state to the start of the animation being set. */ - play(name: string, blendTime: number): void; + play(name: string, blendTime?: number): void; /** * @function diff --git a/types/playcanvas/engine/framework/components/component.d.ts b/types/playcanvas/engine/framework/components/component.d.ts index 5b47908106..113c5e6e80 100644 --- a/types/playcanvas/engine/framework/components/component.d.ts +++ b/types/playcanvas/engine/framework/components/component.d.ts @@ -41,7 +41,7 @@ declare namespace pc { * }); * obj.fire('test', 1, 2); // prints 3 to the console */ - on(name: string, callback: (...args: any[]) => void, scope: any): any; + on(name: string, callback: (...args: any[]) => void, scope?: any): void; /** * @function @@ -61,7 +61,7 @@ declare namespace pc { * obj.off('test', handler); // Removes all handler functions, called 'test' * obj.off('test', handler, this); // Removes all hander functions, called 'test' with scope this */ - off(name: string, callback: (...args: any[]) => void, scope: any): any; + off(name: string, callback?: (...args: any[]) => void, scope?: any): void; /** * @function @@ -72,7 +72,7 @@ declare namespace pc { * @example * obj.fire('test', 'This is the message'); */ - fire(name: string, arg1: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): any; + fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): void; /** * @function @@ -88,7 +88,7 @@ declare namespace pc { * obj.fire('test', 1, 2); // prints 3 to the console * obj.fire('test', 1, 2); // not going to get handled */ - once(name: string, callback: (...args: any[]) => void, scope: any): any; + once(name: string, callback: (...args: any[]) => void, scope?: any): void; /** * @function diff --git a/types/playcanvas/engine/framework/components/model/component.d.ts b/types/playcanvas/engine/framework/components/model/component.d.ts index b89d52721c..c6f5679dd3 100644 --- a/types/playcanvas/engine/framework/components/model/component.d.ts +++ b/types/playcanvas/engine/framework/components/model/component.d.ts @@ -34,7 +34,7 @@ declare namespace pc { constructor(system: pc.ModelComponentSystem, entity: pc.Entity) type: string; - asset: pc.Asset; + asset: pc.Asset | number; castShadows: boolean; receiveShadows: boolean; materialAsset: number; diff --git a/types/playcanvas/engine/framework/components/script/component.d.ts b/types/playcanvas/engine/framework/components/script/component.d.ts index dbaf70b569..1084b904ef 100644 --- a/types/playcanvas/engine/framework/components/script/component.d.ts +++ b/types/playcanvas/engine/framework/components/script/component.d.ts @@ -70,5 +70,7 @@ declare namespace pc { * entity.script.move('playerController', 0); */ move(name: string, ind: number): boolean; + + [prop: string]: any; } } diff --git a/types/playcanvas/engine/framework/components/sound/component.d.ts b/types/playcanvas/engine/framework/components/sound/component.d.ts index 0363d61a8f..d5be560773 100644 --- a/types/playcanvas/engine/framework/components/sound/component.d.ts +++ b/types/playcanvas/engine/framework/components/sound/component.d.ts @@ -87,7 +87,7 @@ declare namespace pc { * this.entity.sound.slot('beep').volume = 0.5; * */ - slot(name: string): pc.Slot; + slot(name: string): pc.SoundSlot; /** * @function diff --git a/types/playcanvas/engine/framework/entity.d.ts b/types/playcanvas/engine/framework/entity.d.ts index 0b1f12ae55..4fd31d0013 100644 --- a/types/playcanvas/engine/framework/entity.d.ts +++ b/types/playcanvas/engine/framework/entity.d.ts @@ -54,6 +54,8 @@ declare namespace pc { constructor(name?: string, app?: pc.Application) constructor(app?: pc.Application) + private _app: pc.Application; + /** * @function * @name pc.Entity#addComponent @@ -102,13 +104,12 @@ declare namespace pc { removeComponent(type: pc.ComponentTypes): void; /** - * @private * @function * @name pc.Entity#getGuid * @description Get the GUID value for this Entity * @returns {String} The GUID of the Entity */ - private getGuid(): string; + public getGuid(): string; /** * @private diff --git a/types/playcanvas/engine/graphics/device.d.ts b/types/playcanvas/engine/graphics/device.d.ts index 188de0b1a3..fc0be6df09 100644 --- a/types/playcanvas/engine/graphics/device.d.ts +++ b/types/playcanvas/engine/graphics/device.d.ts @@ -45,6 +45,10 @@ declare namespace pc { */ readonly maxVolumeSize: number; + readonly canvas: HTMLCanvasElement; + + maxPixelRatio: number; + /** * @function * @name pc.GraphicsDevice#setViewport @@ -68,13 +72,13 @@ declare namespace pc { setScissor(x: number, y: number, w: number, h: number): void; /** - * @private + * @public * @function * @name pc.GraphicsDevice#getProgramLibrary * @description Retrieves the program library assigned to the specified graphics device. * @returns {pc.ProgramLibrary} The program library assigned to the device. */ - private getProgramLibrary(): pc.ProgramLibrary; + getProgramLibrary(): pc.ProgramLibrary; /** * @private diff --git a/types/playcanvas/engine/graphics/texture.d.ts b/types/playcanvas/engine/graphics/texture.d.ts index ac637117bf..ed468ba5e6 100644 --- a/types/playcanvas/engine/graphics/texture.d.ts +++ b/types/playcanvas/engine/graphics/texture.d.ts @@ -85,7 +85,7 @@ declare namespace pc { * @author Will Eastcott */ class Texture { - constructor(graphicsDevice: pc.GraphicsDevice, options: { + constructor(graphicsDevice: pc.GraphicsDevice, options?: { width: number, height: number, depth: number, @@ -95,6 +95,7 @@ declare namespace pc { anisotropy: number, addressU: number, addressV: number, + addressW: number, mipmaps: boolean, cubemap: boolean, volume: boolean, diff --git a/types/playcanvas/engine/graphics/vertex-format.d.ts b/types/playcanvas/engine/graphics/vertex-format.d.ts index 13052e2a8a..f787f3a448 100644 --- a/types/playcanvas/engine/graphics/vertex-format.d.ts +++ b/types/playcanvas/engine/graphics/vertex-format.d.ts @@ -58,10 +58,10 @@ declare namespace pc { */ class VertexFormat { constructor(graphicsDevice: pc.GraphicsDevice, description: { - semantic: number, + semantic: string, components: number, type: number, - normalize: boolean + normalize?: boolean }[]) } } \ No newline at end of file diff --git a/types/playcanvas/engine/graphics/vertex-iterator.d.ts b/types/playcanvas/engine/graphics/vertex-iterator.d.ts index bc9b23d59b..8f56ff6b87 100644 --- a/types/playcanvas/engine/graphics/vertex-iterator.d.ts +++ b/types/playcanvas/engine/graphics/vertex-iterator.d.ts @@ -10,6 +10,8 @@ declare namespace pc { class VertexIterator { constructor(vertexBuffer: pc.VertexBuffer) + element: any; + /** * @function * @name pc.VertexIterator#next diff --git a/types/playcanvas/engine/input/input.d.ts b/types/playcanvas/engine/input/input.d.ts index d132539b36..97f51d4158 100644 --- a/types/playcanvas/engine/input/input.d.ts +++ b/types/playcanvas/engine/input/input.d.ts @@ -41,19 +41,19 @@ declare namespace pc { * @name pc.EVENT_TOUCHSTART * @description Name of event fired when a new touch occurs. For example, a finger is placed on the device. */ - const VENT_TOUCHSTART = 'touchstart'; + const EVENT_TOUCHSTART = 'touchstart'; /** * @enum pc.EVENT * @name pc.EVENT_TOUCHEND * @description Name of event fired when touch ends. For example, a finger is lifted off the device. */ - const VENT_TOUCHEND = 'touchend'; + const EVENT_TOUCHEND = 'touchend'; /** * @enum pc.EVENT * @name pc.EVENT_TOUCHMOVE * @description Name of event fired when a touch moves. */ - const VENT_TOUCHMOVE = 'touchmove'; + const EVENT_TOUCHMOVE = 'touchmove'; /** * @enum pc.EVENT * @name pc.EVENT_TOUCHCANCEL @@ -62,18 +62,18 @@ declare namespace pc { * For example, a modal alert pops up during the interaction; the touch point leaves the document area; * or there are more touch points than the device supports, in which case the earliest touch point is canceled. */ - const VENT_TOUCHCANCEL = 'touchcancel'; + const EVENT_TOUCHCANCEL = 'touchcancel'; /** * @enum pc.KEY * @name pc.KEY_BACKSPACE */ - const EY_BACKSPACE = 8; + const KEY_BACKSPACE = 8; /** * @enum pc.KEY * @name pc.KEY_TAB */ - const EY_TAB = 9; + const KEY_TAB = 9; /** * @enum pc.KEY * @name pc.KEY_RETURN diff --git a/types/playcanvas/engine/input/mouse.d.ts b/types/playcanvas/engine/input/mouse.d.ts index 524e2c40c6..a614d57d15 100644 --- a/types/playcanvas/engine/input/mouse.d.ts +++ b/types/playcanvas/engine/input/mouse.d.ts @@ -1,4 +1,4 @@ -type BrowserMouseEvent = typeof MouseEvent; +type BrowserMouseEvent = MouseEvent; declare namespace pc { /** @@ -45,16 +45,15 @@ declare namespace pc { * @param {Element} [element] The Element that the mouse events are attached to */ class Mouse { - constructor(element?: Element) - /** * @function * @name pc.Mouse.isPointerLocked * @description Check if the mouse pointer has been locked, using {@link pc.Mouse#enabledPointerLock} * @returns {Boolean} True if locked */ - isPointerLocked(): void; + static isPointerLocked(): void; + constructor(element?: Element) /** * @function diff --git a/types/playcanvas/engine/input/touch.d.ts b/types/playcanvas/engine/input/touch.d.ts index d94f8167b7..bc56e87894 100644 --- a/types/playcanvas/engine/input/touch.d.ts +++ b/types/playcanvas/engine/input/touch.d.ts @@ -1,5 +1,5 @@ -type BrowserTouchEvent = typeof TouchEvent; -type BrowserTouch = typeof Touch; +type BrowserTouchEvent = TouchEvent; +type BrowserTouch = Touch; declare namespace pc { @@ -18,6 +18,7 @@ declare namespace pc { constructor(device: pc.TouchDevice, event: BrowserTouchEvent) element: Element; + event: BrowserTouchEvent; touches: pc.Touch[]; changedTouches: pc.Touch[]; @@ -166,4 +167,4 @@ declare namespace pc { */ hasEvent(name: string): boolean; } -} \ No newline at end of file +} diff --git a/types/playcanvas/engine/math/mat3.d.ts b/types/playcanvas/engine/math/mat3.d.ts index d84f39d124..1ed5afed3e 100644 --- a/types/playcanvas/engine/math/mat3.d.ts +++ b/types/playcanvas/engine/math/mat3.d.ts @@ -15,6 +15,8 @@ declare namespace pc { * @param {Number} [v8] The value in row 2, column 2. */ class Mat3 { + data: Float32Array; + constructor(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number) constructor(v0: [number, number, number, number, number, number, number, number, number]) diff --git a/types/playcanvas/engine/math/mat4.d.ts b/types/playcanvas/engine/math/mat4.d.ts index 73306d52c7..d6fb0e75e9 100644 --- a/types/playcanvas/engine/math/mat4.d.ts +++ b/types/playcanvas/engine/math/mat4.d.ts @@ -22,6 +22,8 @@ declare namespace pc { * @param {Number} [v15] The value in row 3, column 3. */ class Mat4 { + data: Float32Array; + constructor( v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number diff --git a/types/playcanvas/engine/math/vec2.d.ts b/types/playcanvas/engine/math/vec2.d.ts index ec02347f46..2fc8bef234 100644 --- a/types/playcanvas/engine/math/vec2.d.ts +++ b/types/playcanvas/engine/math/vec2.d.ts @@ -8,7 +8,10 @@ declare namespace pc { * @param {Number} [y] The y value */ class Vec2 { - constructor(x: number, y: number) + data: Float32Array; + + constructor(x: number, y: number); + constructor(); /** * @function diff --git a/types/playcanvas/engine/math/vec3.d.ts b/types/playcanvas/engine/math/vec3.d.ts index cc298d6a4e..30ea7a5758 100644 --- a/types/playcanvas/engine/math/vec3.d.ts +++ b/types/playcanvas/engine/math/vec3.d.ts @@ -10,6 +10,7 @@ declare namespace pc { * var v = new pc.Vec3(1,2,3); */ class Vec3 { + data: Float32Array; constructor(x: number, y: number, z: number) constructor(x: [number, number, number]) diff --git a/types/playcanvas/engine/math/vec4.d.ts b/types/playcanvas/engine/math/vec4.d.ts index f562eeb6bc..919c65f56c 100644 --- a/types/playcanvas/engine/math/vec4.d.ts +++ b/types/playcanvas/engine/math/vec4.d.ts @@ -10,6 +10,8 @@ declare namespace pc { * @param {Number} [w] The w value */ class Vec4 { + data: Float32Array; + constructor(x: number, y: number, z: number, w: number) constructor(x: [number, number, number, number]) constructor(); diff --git a/types/playcanvas/engine/resources/animation.d.ts b/types/playcanvas/engine/resources/animation.d.ts new file mode 100644 index 0000000000..18a51950c4 --- /dev/null +++ b/types/playcanvas/engine/resources/animation.d.ts @@ -0,0 +1,7 @@ +declare namespace pc { + class AnimationHandler { + load(url: string, callback: Function): void; + open(url: string, data: any): any; + patch(asset: pc.Asset, assets: pc.AssetRegistry): void; + } +} diff --git a/types/playcanvas/engine/resources/cubemap.d.ts b/types/playcanvas/engine/resources/cubemap.d.ts new file mode 100644 index 0000000000..157f62c456 --- /dev/null +++ b/types/playcanvas/engine/resources/cubemap.d.ts @@ -0,0 +1,7 @@ +declare namespace pc { + class CubemapHandler { + load(url: string, callback: Function): void; + open(url: string, data: any): any; + patch(asset: pc.Asset, assets: pc.AssetRegistry): void; + } +} diff --git a/types/playcanvas/engine/resources/loader.d.ts b/types/playcanvas/engine/resources/loader.d.ts index 61e99b179a..632886242f 100644 --- a/types/playcanvas/engine/resources/loader.d.ts +++ b/types/playcanvas/engine/resources/loader.d.ts @@ -1,8 +1,9 @@ declare namespace pc { interface ResourceHandler { - load: (url: 'string', callback: (...args: any[]) => {}) => {}; - open: (url: 'string', date: any) => {}; + load(url: 'string', callback: (...args: any[]) => {}): void; + open(url: 'string', data: any): any; + patch(asset: pc.Asset, assets: pc.AssetRegistry): void; } /** @@ -25,6 +26,11 @@ declare namespace pc { */ addHandler(type: string, handler: pc.ResourceHandler): void; + getHandler(type: string): any; + + removeHandler(type: string): void; + + /** * @function * @name pc.ResourceLoader#load diff --git a/types/playcanvas/engine/resources/material.d.ts b/types/playcanvas/engine/resources/material.d.ts new file mode 100644 index 0000000000..7259655759 --- /dev/null +++ b/types/playcanvas/engine/resources/material.d.ts @@ -0,0 +1,10 @@ +declare namespace pc { + + function getMaterialParamType(name: string): string; + + class MaterialHandler { + load(url: string, callback: Function): void; + open(url: string, data: any): void; + patch(asset: pc.Asset, assets: pc.AssetRegistry): void; + } +} diff --git a/types/playcanvas/engine/resources/model.d.ts b/types/playcanvas/engine/resources/model.d.ts index a5d7dbd8e7..116c83c6ac 100644 --- a/types/playcanvas/engine/resources/model.d.ts +++ b/types/playcanvas/engine/resources/model.d.ts @@ -7,6 +7,9 @@ declare namespace pc { * @param {pc.GraphicsDevice} device The graphics device that will be rendering */ class ModelHandler { + + static DEFAULT_MATERIAL: pc.StandardMaterial; + constructor(device: pc.GraphicsDevice) /** diff --git a/types/playcanvas/engine/resources/script.d.ts b/types/playcanvas/engine/resources/script.d.ts index 3f7fd26292..2299dfc3e9 100644 --- a/types/playcanvas/engine/resources/script.d.ts +++ b/types/playcanvas/engine/resources/script.d.ts @@ -8,7 +8,11 @@ declare namespace pc { * @param {pc.Application} app The running {pc.Application} */ class ScriptHandler { - constructor(app: pc.Application) + static _push(Type: ScriptType): void; + constructor(app: pc.Application) + load(url: string, callback: Function): void; + open(url: string, data: any): any; + patch(asset: pc.Asset, assets: pc.AssetRegistry): void; } } diff --git a/types/playcanvas/engine/resources/texture.d.ts b/types/playcanvas/engine/resources/texture.d.ts new file mode 100644 index 0000000000..d5073290e6 --- /dev/null +++ b/types/playcanvas/engine/resources/texture.d.ts @@ -0,0 +1,9 @@ +declare namespace pc { + class TextureHandler { + crossOrigin: boolean | string; + + load(url: string, callback: Function): void; + open(url: string, data: any): any; + patch(asset: pc.Asset, assets: pc.AssetRegistry): void; + } +} diff --git a/types/playcanvas/engine/scene/basic-material.d.ts b/types/playcanvas/engine/scene/basic-material.d.ts index 6bca34dfd5..f6c4404b39 100644 --- a/types/playcanvas/engine/scene/basic-material.d.ts +++ b/types/playcanvas/engine/scene/basic-material.d.ts @@ -23,6 +23,9 @@ declare namespace pc { */ class BasicMaterial extends pc.Material { + color: pc.Color; + colorMap: pc.Texture; + /** * @function * @name pc.BasicMaterial#clone diff --git a/types/playcanvas/engine/scene/graph-node.d.ts b/types/playcanvas/engine/scene/graph-node.d.ts index f9d587f8af..b5baf6579b 100644 --- a/types/playcanvas/engine/scene/graph-node.d.ts +++ b/types/playcanvas/engine/scene/graph-node.d.ts @@ -8,6 +8,8 @@ declare namespace pc { */ class GraphNode { constructor(name?: string) + name: string; + tags: pc.Tags; /** * @readonly @@ -64,7 +66,7 @@ declare namespace pc { * @type pc.GraphNode[] * @description A read-only property to get the children of this graph node. */ - readonly children: pc.GraphNode; + readonly children: pc.GraphNode[]; /** * @function @@ -378,6 +380,7 @@ declare namespace pc { * this.entity.setLocalEulerAngles(0, 90, 0); // Set rotation of 90 degrees around y-axis. */ setLocalEulerAngles(x: number, y: number, z: number): void; + setLocalEulerAngles(...args: number[]): void; /** * @function @@ -402,6 +405,7 @@ declare namespace pc { * this.entity.setLocalPosition(0, 10, 0); */ setLocalPosition(x: number, y: number, z: number): void; + setLocalPosition(...args: number[]): void; /** * @function @@ -437,6 +441,7 @@ declare namespace pc { * this.entity.setLocalRotation(0, 0, 0, 1); */ setLocalRotation(x: number, y: number, z: number, w: number): void; + setLocalRotation(...args: number[]): void; /** * @function @@ -449,6 +454,7 @@ declare namespace pc { * this.entity.setLocalScale(10, 10, 10); */ setLocalScale(x: number, y: number, z: number): void; + setLocalScale(...args: number[]): void; /** * @function @@ -484,6 +490,7 @@ declare namespace pc { * this.entity.setPosition(0, 10, 0); */ setPosition(x: number, y: number, z: number): void; + setPosition(...args: number[]): void; /** * @function @@ -521,6 +528,7 @@ declare namespace pc { * this.entity.setRotation(0, 0, 0, 1); */ setRotation(x: number, y: number, z: number, w: number): void; + setRotation(...args: number[]): void; /** * @function @@ -534,6 +542,7 @@ declare namespace pc { * this.entity.setEulerAngles(0, 90, 0); */ setEulerAngles(x: number, y: number, z: number): void; + setEulerAngles(...args: number[]): void; /** * @function diff --git a/types/playcanvas/engine/scene/material.d.ts b/types/playcanvas/engine/scene/material.d.ts index 1cb8d487f7..7d387cc0a0 100644 --- a/types/playcanvas/engine/scene/material.d.ts +++ b/types/playcanvas/engine/scene/material.d.ts @@ -57,6 +57,9 @@ declare namespace pc { alphaTest: number; alphaToCoverage: boolean; alphaWrite: boolean; + blend: boolean; + blendSrc: number; + blendDst: number; blendType: number; blueWrite: boolean; cull: number; diff --git a/types/playcanvas/engine/scene/mesh.d.ts b/types/playcanvas/engine/scene/mesh.d.ts index 6a0dca71e6..b9ecd12591 100644 --- a/types/playcanvas/engine/scene/mesh.d.ts +++ b/types/playcanvas/engine/scene/mesh.d.ts @@ -1,5 +1,12 @@ declare namespace pc { + type MeshPrimitive = { + type: number; + base: number; + count: number; + indexed?: boolean; + } + /** * @name pc.Mesh * @class A graphical primitive. The mesh is defined by a {@link pc.VertexBuffer} and an optional @@ -19,8 +26,10 @@ declare namespace pc { class Mesh { vertexBuffer: pc.VertexBuffer; indexBuffer: pc.IndexBuffer; - primitive: {}[]; + primitive: MeshPrimitive[]; aabb: pc.BoundingBox; + skin: pc.Skin; + morph: pc.Morph; } /** @@ -65,11 +74,8 @@ declare namespace pc { class MeshInstance { constructor(node: pc.GraphNode, mesh: pc.Mesh, material: pc.Material) - aabb: pc.BoundingBox; castShadow: boolean; visible: boolean; - layer: number; - material: pc.Material; renderStyle: number; cull: boolean; @@ -80,7 +86,21 @@ declare namespace pc { * To ignore all dynamic lights, set mask to 0. Defaults to 1. */ mask: number; + node: pc.GraphNode; + mesh: pc.Mesh; + aabb: pc.BoundingBox; + material: pc.Material; + layer: number; + receiveShadow: boolean; + skinInstance: pc.SkinInstance; + screenSpace: boolean; + key: number; + } + class Command { + constructor(layer: number, blendType: number, command: Function); + key: number; + conmand: Function; } } \ No newline at end of file diff --git a/types/playcanvas/engine/scene/model.d.ts b/types/playcanvas/engine/scene/model.d.ts index 0961d443af..f11ebf80fa 100644 --- a/types/playcanvas/engine/scene/model.d.ts +++ b/types/playcanvas/engine/scene/model.d.ts @@ -38,6 +38,8 @@ declare namespace pc { */ destroy(): void; + getMaterials(): pc.StandardMaterial[]; + /** * @function * @name pc.Model#generateWireframe diff --git a/types/playcanvas/engine/scene/morph.d.ts b/types/playcanvas/engine/scene/morph.d.ts new file mode 100644 index 0000000000..58e971ebec --- /dev/null +++ b/types/playcanvas/engine/scene/morph.d.ts @@ -0,0 +1,131 @@ +declare namespace pc { + + interface MorphTargetOptions { + deltaPositions: number[]; + deltaNormals?: number[]; + deltaTangents?: number[]; + indices?: number[]; + name?: string; + aabb?: pc.BoundingBox; + } + + /** + * @private + * @name pc.MorphTarget + * @class A Morph Target (also known as Blend Shape) contains deformation data to apply to existing mesh. + * Multiple morph targets can be blended together on a mesh. This is useful for effects that are hard to achieve with conventional animation and skinning. + * @param {Object} options Object for passing optional arguments. + * @param {Number[]} deltaPositions An array of 3-dimensional vertex position offsets. + * @param {Number[]} [deltaNormals] An array of 3-dimensional vertex normal offsets. + * @param {Number[]} [deltaTangents] An array of 4-dimensional vertex normal tangents. + * @param {Number[]} [options.indices] A morph target doesn't have to contain a full copy of the original mesh with added deformations. + * Instead, only deformed vertices can be stored. This array contains indices to the original mesh's vertices and must be of the same size + * as other arrays. + * @param {String} [name] Name + * @param {pc.BoundingBox} [aabb] Bounding box. Will be automatically generated, if undefined. + */ + class MorphTarget { + constructor(optionsi: MorphTargetOptions); + deltaPositions: number[]; + deltaNormals: number[]; + deltaTangents: number[]; + indices: number[]; + name: string; + aabb: pc.BoundingBox; + } + + /** + * @private + * @name pc.Morph + * @class Contains a list of pc.MorphTarget, a combined AABB and some associated data. + * @param {pc.MoprhTarget[]} targets A list of morph targets + */ + class Morph { + constructor(targets: pc.MorphTarget[]); + + aabb: pc.BoundingBox; + + /** + * @private + * @function + * @name pc.Morph#addTarget + * @description Adds a new morph target to the list + * @param {pc.MoprhTarget} target A new morph target + */ + addTarget(target: pc.MorphTarget): void; + + /** + * @private + * @function + * @name pc.Morph#removeTarget + * @description Remove the specified morph target from the list + * @param {pc.MoprhTarget} target A morph target to delete + */ + removeTarget(target: pc.MorphTarget): void; + + /** + * @private + * @function + * @name pc.Morph#getTarget + * @description Gets the morph target by index + * @param {Number} index An index of morph target. + * @returns {pc.MorphTarget} A morph target object + */ + getTarget(index: number): pc.MorphTarget; + } + + /** + * @private + * @name pc.MorphInstance + * @class An instance of pc.Morph. Contains weights to assign to every pc.MorphTarget, holds morphed buffer and associated data. + * @param {pc.Morph} morph The pc.Morph to instance. + */ + class MorphInstance { + constructor(morph: pc.Morph); + + morph: pc.Morph; + + /** + * @function + * @name pc.MorphInstance#destroy + * @description Frees video memory allocated by this object. + */ + destroy(): void; + + /** + * @private + * @function + * @name pc.MorphInstance#getWeight + * @description Gets current weight of the specified morph target. + * @param {Number} index An index of morph target. + * @returns {Number} Weight + */ + getWeight(index: number): number; + + /** + * @private + * @function + * @name pc.MorphInstance#setWeight + * @description Sets weight of the specified morph target. + * @param {Number} index An index of morph target. + * @param {Number} weight Weight + */ + setWeight(index: number, weight: number): void; + + /** + * @private + * @function + * @name pc.MorphInstance#updateBounds + * @description Calculates AABB for this morph instance. Called automatically by renderer. + */ + updateBounds(): void; + + /** + * @private + * @function + * @name pc.MorphInstance#update + * @description Performs morphing. Called automatically by renderer. + */ + update(mesh: pc.Mesh): void; + } +} \ No newline at end of file diff --git a/types/playcanvas/engine/scene/procedural.d.ts b/types/playcanvas/engine/scene/procedural.d.ts index 9b1f3e66d6..8254952918 100644 --- a/types/playcanvas/engine/scene/procedural.d.ts +++ b/types/playcanvas/engine/scene/procedural.d.ts @@ -59,7 +59,7 @@ declare namespace pc { * }); * @author Will Eastcott */ - function createMesh(device: pc.GraphicsDevice, positions: number[], opts: { + function createMesh(device: pc.GraphicsDevice, positions: number[], opts?: { normals: number[], tangents: number[], colors: number[], @@ -86,7 +86,7 @@ declare namespace pc { * @returns {pc.Mesh} A new torus-shaped mesh. * @author Will Eastcott */ - function createTorus(device: pc.GraphicsDevice, opts: { + function createTorus(device: pc.GraphicsDevice, opts?: { tubeRadius: number, ringRadius: number, segments: number, @@ -111,7 +111,7 @@ declare namespace pc { * @returns {pc.Mesh} A new cylinder-shaped mesh. * @author Will Eastcott */ - function createCylinder(device: pc.GraphicsDevice, opts: { + function createCylinder(device: pc.GraphicsDevice, opts?: { radius: number, height: number, heightSegments: number, @@ -136,7 +136,7 @@ declare namespace pc { * @returns {pc.Mesh} A new cylinder-shaped mesh. * @author Will Eastcott */ - function createCapsule(device: pc.GraphicsDevice, opts: { + function createCapsule(device: pc.GraphicsDevice, opts?: { radius: number, height: number, heightSegments: number, @@ -162,7 +162,7 @@ declare namespace pc { * @returns {pc.Mesh} A new cone-shaped mesh. * @author Will Eastcott */ - function createCone(device: pc.GraphicsDevice, opts: { + function createCone(device: pc.GraphicsDevice, opts?: { baseRadius: number, peakRadius: number, height: number, @@ -186,7 +186,7 @@ declare namespace pc { * @returns {pc.Mesh} A new sphere-shaped mesh. * @author Will Eastcott */ - function createSphere(device: pc.GraphicsDevice, opts: { + function createSphere(device: pc.GraphicsDevice, opts?: { radius: number, segments: number }): pc.Mesh; @@ -209,7 +209,7 @@ declare namespace pc { * @returns {pc.Mesh} A new plane-shaped mesh. * @author Will Eastcott */ - function createPlane(device: pc.GraphicsDevice, opts: { + function createPlane(device: pc.GraphicsDevice, opts?: { halfExtents: pc.Vec2, widthSegments: number, lenghtSegments: number @@ -233,7 +233,7 @@ declare namespace pc { * @return {pc.Mesh} A new box-shaped mesh. * @author Will Eastcott */ - function createBox(device: pc.GraphicsDevice, opts: { + function createBox(device: pc.GraphicsDevice, opts?: { halfExtents: pc.Vec3, widthSegments: number, lengthSegments: number, diff --git a/types/playcanvas/engine/scene/scene.d.ts b/types/playcanvas/engine/scene/scene.d.ts index 87bf620a9e..c73e3c61ee 100644 --- a/types/playcanvas/engine/scene/scene.d.ts +++ b/types/playcanvas/engine/scene/scene.d.ts @@ -326,5 +326,7 @@ declare namespace pc { * @author Will Eastcott */ update(): void; + + setSkybox(cubemaps: pc.Texture[]): void; } -} \ No newline at end of file +} diff --git a/types/playcanvas/engine/script/script.d.ts b/types/playcanvas/engine/script/script.d.ts index 21cd5540d9..f1565d1c47 100644 --- a/types/playcanvas/engine/script/script.d.ts +++ b/types/playcanvas/engine/script/script.d.ts @@ -144,6 +144,9 @@ declare namespace pc { * }; */ function createScript>(name: string, app?: pc.Application): Class; + namespace createScript { + export let reservedAttributes: any; + } /** * @name ScriptType @@ -172,7 +175,7 @@ declare namespace pc { * @type String * @description Name of a Script Type. */ - _name: string; + __name: string; /** * @field @@ -220,9 +223,6 @@ declare namespace pc { interface ScriptType { [key: string]: any; - app: pc.Application; - entity: pc.Entity; - enabled: boolean; /** * initialize is called if defined when script is about to run for the first time. @@ -231,7 +231,7 @@ declare namespace pc { initialize?(): void; /** - * postInitialize will run after all initialize methods are executed in the + * postInitialize will run after all initialize methods are executed in the * same tick or enabling chain of actions. * @memberof ScriptType */ @@ -239,22 +239,22 @@ declare namespace pc { /** * update is called if defined for enabled (running state) scripts on each tick. - * @param {number} dt + * @param {number} dt * @memberof ScriptType */ update?(dt: number): void; /** - * postUpdate is called if defined for enabled (running state) scripts on each tick, + * postUpdate is called if defined for enabled (running state) scripts on each tick, * after update. * @memberof ScriptType */ postUpdate?(): void; /** - * This method will be called when a ScriptType that already exists in the registry - * gets redefined. If the new ScriptType has a `swap` method in its prototype, - * then it will be executed to perform hot-reload at runtime. + * This method will be called when a ScriptType that already exists in the registry + * gets redefined. If the new ScriptType has a `swap` method in its prototype, + * then it will be executed to perform hot-reload at runtime. * @memberof ScriptType */ swap?(): void; @@ -274,7 +274,7 @@ declare namespace pc { * }); * obj.fire('test', 1, 2); // prints 3 to the console */ - on(name: string, callback: (...args: any[]) => void, scope: any): any; + on?(name: string, callback: (...args: any[]) => void, scope: any): any; /** * @function @@ -294,7 +294,7 @@ declare namespace pc { * obj.off('test', handler); // Removes all handler functions, called 'test' * obj.off('test', handler, this); // Removes all hander functions, called 'test' with scope this */ - off(name: string, callback: (...args: any[]) => void, scope: any): any; + off?(name: string, callback: (...args: any[]) => void, scope: any): any; /** * @function @@ -305,7 +305,7 @@ declare namespace pc { * @example * obj.fire('test', 'This is the message'); */ - fire(name: string, arg1: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): any; + fire?(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): any; /** * @function @@ -321,7 +321,7 @@ declare namespace pc { * obj.fire('test', 1, 2); // prints 3 to the console * obj.fire('test', 1, 2); // not going to get handled */ - once(name: string, callback: (...args: any[]) => void, scope: any): any; + once?(name: string, callback: (...args: any[]) => void, scope: any): any; /** * @function @@ -332,7 +332,7 @@ declare namespace pc { * obj.on('test', function () { }); // bind an event to 'test' * obj.hasEvent('test'); // returns true */ - hasEvent(name: string): boolean; + hasEvent?(name: string): boolean; } -} \ No newline at end of file +} diff --git a/types/playcanvas/engine/scriptype.d.ts b/types/playcanvas/engine/scriptype.d.ts index 89fb94c5c4..bd9dc5dfc0 100644 --- a/types/playcanvas/engine/scriptype.d.ts +++ b/types/playcanvas/engine/scriptype.d.ts @@ -1,5 +1,5 @@ interface ScriptType { - name: string; + name?: string; /** * Interface to define public script attributes available in the editor. @@ -13,7 +13,7 @@ interface ScriptType { * @memberof ScriptType */ initialize?(): void; - + /** * postInitialize will run after all initialize methods are executed in the * same tick or enabling chain of actions. @@ -42,4 +42,4 @@ interface ScriptType { * @memberof ScriptType */ swap?(): void; -} \ No newline at end of file +} diff --git a/types/playcanvas/engine/shape/bounding-box.d.ts b/types/playcanvas/engine/shape/bounding-box.d.ts index 67340a2246..b91183b607 100644 --- a/types/playcanvas/engine/shape/bounding-box.d.ts +++ b/types/playcanvas/engine/shape/bounding-box.d.ts @@ -21,6 +21,10 @@ declare namespace pc { */ add(other: pc.BoundingBox): void; + copy(src: pc.BoundingBox): void; + + clone(): pc.BoundingBox; + /** * @function * @name pc.BoundingBox#intersects @@ -38,7 +42,7 @@ declare namespace pc { * @param {pc.Vec3} [point] If there is an intersection, the intersection point will be copied into here. * @returns {Boolean} True if there is an intersection. */ - intersectsRay(ray: pc.Ray, point: pc.Vec3): boolean; + intersectsRay(ray: pc.Ray, point?: pc.Vec3): boolean; /** * @function diff --git a/types/playcanvas/engine/shape/bounding-sphere.d.ts b/types/playcanvas/engine/shape/bounding-sphere.d.ts index 5fd1c3503f..f25c92072b 100644 --- a/types/playcanvas/engine/shape/bounding-sphere.d.ts +++ b/types/playcanvas/engine/shape/bounding-sphere.d.ts @@ -24,7 +24,7 @@ declare namespace pc { * @param {pc.Vec3} [point] If there is an intersection, the intersection point will be copied into here. * @returns {Boolean} True if there is an intersection. */ - intersectsRay(ray: pc.Ray, point: pc.Vec3): boolean; + intersectsRay(ray: pc.Ray, point?: pc.Vec3): boolean; /** * @function diff --git a/types/playcanvas/engine/shape/oriented-box.d.ts b/types/playcanvas/engine/shape/oriented-box.d.ts index 47ca9df330..aeff67f2e8 100644 --- a/types/playcanvas/engine/shape/oriented-box.d.ts +++ b/types/playcanvas/engine/shape/oriented-box.d.ts @@ -21,7 +21,7 @@ declare namespace pc { * @param {pc.Vec3} [point] If there is an intersection, the intersection point will be copied into here. * @returns {Boolean} True if there is an intersection. */ - intersectsRay(ray: pc.Ray, point: pc.Vec3): boolean; + intersectsRay(ray: pc.Ray, point?: pc.Vec3): boolean; /** * @function diff --git a/types/playcanvas/engine/shape/plane.d.ts b/types/playcanvas/engine/shape/plane.d.ts index a7ce142fd6..fcb8a557dc 100644 --- a/types/playcanvas/engine/shape/plane.d.ts +++ b/types/playcanvas/engine/shape/plane.d.ts @@ -9,7 +9,10 @@ declare namespace pc { * @param {pc.Vec3} [normal] Normal of the plane. The constructor takes a reference of this parameter. */ class Plane { - constructor(point: pc.Vec3, normal: pc.Vec3) + constructor(point?: pc.Vec3, normal?: pc.Vec3) + + point: pc.Vec3; + normal: pc.Vec3; /** * @function @@ -30,6 +33,6 @@ declare namespace pc { * @param {pc.Vec3} [point] If there is an intersection, the intersection point will be copied into here * @returns {Boolean} True if there is an intersection */ - intersectsRay(ray: pc.Ray, point: pc.Vec3): boolean; + intersectsRay(ray: pc.Ray, point?: pc.Vec3): boolean; } } diff --git a/types/playcanvas/engine/vr/vr-display.d.ts b/types/playcanvas/engine/vr/vr-display.d.ts index a39562c143..c0d23fc944 100644 --- a/types/playcanvas/engine/vr/vr-display.d.ts +++ b/types/playcanvas/engine/vr/vr-display.d.ts @@ -1,5 +1,5 @@ -type NativeVRDisplay = typeof VRDisplay; -type NativeVRDisplayCapabilities = typeof VRDisplayCapabilities; +type NativeVRDisplay = VRDisplay; +type NativeVRDisplayCapabilities = VRDisplayCapabilities; declare namespace pc { @@ -96,6 +96,6 @@ declare namespace pc { * @description Return the current frame data that is updated during polling. * @returns {VRFrameData} The frame data object */ - getFrameData(): void; + getFrameData(): void; } } diff --git a/types/playcanvas/index.d.ts b/types/playcanvas/index.d.ts index 03899cd1b9..24fe7ec6ee 100644 --- a/types/playcanvas/index.d.ts +++ b/types/playcanvas/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Philippe Vaillancourt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// /// /// /// @@ -52,10 +53,14 @@ /// /// /// +/// /// +/// /// -/// +/// /// +/// +/// /// /// /// @@ -72,6 +77,7 @@ /// /// /// +/// /// /// /// From 574ea0954ec287413f4beb5233e06bca21899b24 Mon Sep 17 00:00:00 2001 From: Damian Senn Date: Mon, 26 Feb 2018 20:47:25 +0100 Subject: [PATCH 112/128] jQuery offset method might return undefined (#23821) --- types/jquery/v1/index.d.ts | 2 +- types/jquery/v2/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/jquery/v1/index.d.ts b/types/jquery/v1/index.d.ts index ee66781019..8cbc9c5789 100644 --- a/types/jquery/v1/index.d.ts +++ b/types/jquery/v1/index.d.ts @@ -1771,7 +1771,7 @@ interface JQuery { * Get the current coordinates of the first element in the set of matched elements, relative to the document. * @see {@link https://api.jquery.com/offset/#offset} */ - offset(): JQueryCoordinates; + offset(): JQueryCoordinates | undefined; /** * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. * diff --git a/types/jquery/v2/index.d.ts b/types/jquery/v2/index.d.ts index 9d30f12c38..2f9a79adf4 100644 --- a/types/jquery/v2/index.d.ts +++ b/types/jquery/v2/index.d.ts @@ -1771,7 +1771,7 @@ interface JQuery { * Get the current coordinates of the first element in the set of matched elements, relative to the document. * @see {@link https://api.jquery.com/offset/#offset} */ - offset(): JQueryCoordinates; + offset(): JQueryCoordinates | undefined; /** * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. * From fe309837c42f5ac261488e706600f0fafab87d39 Mon Sep 17 00:00:00 2001 From: Jesse Pinho Date: Mon, 26 Feb 2018 20:49:30 +0100 Subject: [PATCH 113/128] Add typing for `hrefTo` in @storybook/addon-links (#23811) * Add typing for `hrefTo` See [the documentation for `hrefTo`](https://github.com/storybooks/storybook/blob/1a550e912b0c484ae787dc44809add30f6291dc4/addons/links/README.md#hrefto-function). * Addd definition author * Add type usage to tests * Update the package version --- types/storybook__addon-links/index.d.ts | 7 +++++-- .../storybook__addon-links-tests.tsx | 4 +++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/types/storybook__addon-links/index.d.ts b/types/storybook__addon-links/index.d.ts index 141072aa2a..72ec6aa296 100644 --- a/types/storybook__addon-links/index.d.ts +++ b/types/storybook__addon-links/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for @storybook/addon-links 3.0 +// Type definitions for @storybook/addon-links 3.3 // Project: https://github.com/storybooks/storybook -// Definitions by: Joscha Feth +// Definitions by: Joscha Feth , +// Jesse Pinho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -9,3 +10,5 @@ import * as React from 'react'; export type LinkToFunction = (...args: any[]) => string; export function linkTo(book: string | LinkToFunction, kind?: string | LinkToFunction): React.MouseEventHandler; + +export function hrefTo(kind: string, story: string): Promise; diff --git a/types/storybook__addon-links/storybook__addon-links-tests.tsx b/types/storybook__addon-links/storybook__addon-links-tests.tsx index 2f138daf20..e922b0fc00 100644 --- a/types/storybook__addon-links/storybook__addon-links-tests.tsx +++ b/types/storybook__addon-links/storybook__addon-links-tests.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; import { storiesOf } from '@storybook/react'; -import { linkTo } from '@storybook/addon-links'; +import { hrefTo, linkTo } from '@storybook/addon-links'; storiesOf('Button', module) .add('First', () => ( @@ -12,3 +12,5 @@ storiesOf('Button', module) .add('With function', () => ( )); + +hrefTo('Button', 'First').then(link => link); From d2afdde5ba6bd8de808178a863a1614dc3feae0b Mon Sep 17 00:00:00 2001 From: Jan Lohage Date: Mon, 26 Feb 2018 20:52:21 +0100 Subject: [PATCH 114/128] @feathersjs/feathers + @feathersjs/socketio: Minor fixes (#23822) * [@feathersjs] add @feathersjs/socket-commons import to @feathersjs/socketio and @feathersjs/primus packages * [@feathersjs] fix ts version in @feathersjs/socketio and @feathersjs/primus packages * [@feathersjs] really fix ts version in @feathersjs/socketio and @feathersjs/primus packages * add express reexports * @feathersjs/feathers: add generic default type to `Application` interface @feathersjs/feathers: make Params.paginate optional @feathersjs/socketio: make callback optional * change Hook return type from undefined to void * Update index.d.ts * disable tslint rule 'void-return' for specific callback * Update index.d.ts * Update index.d.ts --- types/feathersjs__feathers/index.d.ts | 15 ++++++++------- types/feathersjs__socket-commons/index.d.ts | 6 ++++-- types/feathersjs__socketio/index.d.ts | 2 +- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/types/feathersjs__feathers/index.d.ts b/types/feathersjs__feathers/index.d.ts index c10a173f06..6ae7b22238 100644 --- a/types/feathersjs__feathers/index.d.ts +++ b/types/feathersjs__feathers/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jan Lohage , Abraao Alves // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /// @@ -30,7 +30,7 @@ export type ServerSideParams = Params; export interface Params { query?: Query; - paginate: false | Pick; + paginate?: false | Pick; [key: string]: any; // (JL) not sure if we want this } @@ -42,10 +42,11 @@ export interface Paginated { data: T[]; } -export type Hook = (hook: HookContext) => (Promise> | undefined); +// tslint:disable-next-line void-return +export type Hook = (hook: HookContext) => (Promise> | void); export interface HookContext { - app?: Application; + app?: Application; data?: T; error?: any; id?: string | number; @@ -89,7 +90,7 @@ export interface ServiceMethods { } export interface SetupMethod { - setup(app: Application, path: string): void; + setup(app: Application, path: string): void; } export interface ServiceOverloads { @@ -106,7 +107,7 @@ export interface ServiceAddons extends EventEmitter { export type Service = ServiceOverloads & ServiceAddons & ServiceMethods; -export interface Application extends EventEmitter { +export interface Application extends EventEmitter { get(name: string): any; set(name: string, value: any): this; @@ -129,7 +130,7 @@ export interface Application extends EventEmitter { service(location: string): Service; - use(path: string, service: Partial & SetupMethod> | Application, options?: any): this; + use(path: string, service: Partial & SetupMethod> | Application, options?: any): this; version: string; } diff --git a/types/feathersjs__socket-commons/index.d.ts b/types/feathersjs__socket-commons/index.d.ts index fca658bf76..043009fd5e 100644 --- a/types/feathersjs__socket-commons/index.d.ts +++ b/types/feathersjs__socket-commons/index.d.ts @@ -28,8 +28,10 @@ declare module '@feathersjs/feathers' { interface Application { channel(...names: string[]): Channel; - publish(callback: (data: T, hook: HookContext) => Channel | Channel[]): Application; + // tslint:disable-next-line void-return + publish(callback: (data: T, hook: HookContext) => Channel | Channel[] | void): Application; - publish(event: string, callback: (data: T, hook: HookContext) => Channel | Channel[]): Application; + // tslint:disable-next-line void-return + publish(event: string, callback: (data: T, hook: HookContext) => Channel | Channel[] | void): Application; } } diff --git a/types/feathersjs__socketio/index.d.ts b/types/feathersjs__socketio/index.d.ts index 34b78eb749..7ba889dfbe 100644 --- a/types/feathersjs__socketio/index.d.ts +++ b/types/feathersjs__socketio/index.d.ts @@ -7,6 +7,6 @@ /// /// -export default function feathersSocketIO(callback: (io: SocketIO.Server) => void): () => void; +export default function feathersSocketIO(callback?: (io: SocketIO.Server) => void): () => void; export default function feathersSocketIO(options: number | SocketIO.ServerOptions, callback?: (io: SocketIO.Server) => void): () => void; export default function feathersSocketIO(port: number, options?: SocketIO.ServerOptions, callback?: (io: SocketIO.Server) => void): () => void; From 8617cbac9c3e11bcd0ce233bbca9a5d2220a9474 Mon Sep 17 00:00:00 2001 From: Thomas Gossmann Date: Mon, 26 Feb 2018 20:52:58 +0100 Subject: [PATCH 115/128] Make options hash optional on `DS.Model.destroyRecord()` (#23820) --- types/ember-data/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/ember-data/index.d.ts b/types/ember-data/index.d.ts index f0bb87a00d..7b78770489 100644 --- a/types/ember-data/index.d.ts +++ b/types/ember-data/index.d.ts @@ -491,7 +491,7 @@ declare module 'ember-data' { /** * Same as `deleteRecord`, but saves the record immediately. */ - destroyRecord(options: {}): RSVP.Promise; + destroyRecord(options?: {}): RSVP.Promise; /** * Unloads the record from the store. This will cause the record to be destroyed and freed up for garbage collection. */ From 61c2fa61d96857f4ee78fb48a6094e10dd1d9e3f Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Mon, 26 Feb 2018 20:53:18 +0100 Subject: [PATCH 116/128] fix: `awaitWriteFinish` can also be a `boolean` (#23818) https://www.npmjs.com/package/chokidar --- types/chokidar/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/chokidar/index.d.ts b/types/chokidar/index.d.ts index 396ad10e0a..6acc9af265 100644 --- a/types/chokidar/index.d.ts +++ b/types/chokidar/index.d.ts @@ -149,7 +149,7 @@ export interface WatchOptions { /** * can be set to an object in order to adjust timing params: */ - awaitWriteFinish?: AwaitWriteFinishOptions; + awaitWriteFinish?: AwaitWriteFinishOptions | boolean; } export interface AwaitWriteFinishOptions { From 940de815c698e8f56ae8fcea39f6b18c4c3f80c0 Mon Sep 17 00:00:00 2001 From: Florian Keller Date: Sun, 18 Feb 2018 17:05:40 +0100 Subject: [PATCH 117/128] Add yauzl --- types/yauzl/index.d.ts | 97 ++++++++++++++++++++++++++++++++++++++ types/yauzl/tsconfig.json | 23 +++++++++ types/yauzl/tslint.json | 1 + types/yauzl/yauzl-tests.ts | 28 +++++++++++ 4 files changed, 149 insertions(+) create mode 100644 types/yauzl/index.d.ts create mode 100644 types/yauzl/tsconfig.json create mode 100644 types/yauzl/tslint.json create mode 100644 types/yauzl/yauzl-tests.ts diff --git a/types/yauzl/index.d.ts b/types/yauzl/index.d.ts new file mode 100644 index 0000000000..c0e8b5dc88 --- /dev/null +++ b/types/yauzl/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for yauzl 2.9 +// Project: https://github.com/thejoshwolfe/yauzl +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { EventEmitter } from 'events'; +import { Readable } from 'stream'; + +export abstract class RandomAccessReader extends EventEmitter { + _readStreamForRange(start: number, end: number): void; + createReadStream(options: { start: number; end: number }): void; + read(buffer: Buffer, offset: number, length: number, position: number, callback: (err?: Error) => void): void; + close(callback: (err?: Error) => void): void; +} + +export class Entry { + comment: string; + compressedSize: number; + compressionMethod: number; + crc32: number; + externalFileAttributes: number; + extraFieldLength: number; + extraFields: Array<{ id: number; data: Buffer }>; + fileCommentLength: number; + fileName: string; + fileNameLength: number; + generalPurposeBitFlag: number; + internalFileAttributes: number; + lastModFileDate: number; + lastModFileTime: number; + relativeOffsetOfLocalHeader: number; + uncompressedSize: number; + versionMadeBy: number; + versionNeededToExtract: number; + + getLastModDate(): Date; + isEncrypted(): boolean; + isCompressed(): boolean; +} + +export interface ZipFileOptions { + decompress: boolean | null; + decrypt: boolean | null; + start: number | null; + end: number | null; +} + +export class ZipFile extends EventEmitter { + autoClose: boolean; + comment: string; + decodeStrings: boolean; + emittedError: boolean; + entriesRead: number; + entryCount: number; + fileSize: number; + isOpen: boolean; + lazyEntries: boolean; + readEntryCursor: boolean; + validateEntrySizes: boolean; + + constructor( + reader: RandomAccessReader, + centralDirectoryOffset: number, + fileSize: number, + entryCount: number, + comment: string, + autoClose: boolean, + lazyEntries: boolean, + decodeStrings: boolean, + validateEntrySizes: boolean, + ); + + openReadStream(entry: Entry, options: ZipFileOptions, callback: (err?: Error, stream?: Readable) => void): void; + openReadStream(entry: Entry, callback: (err?: Error, stream?: Readable) => void): void; + close(): void; + readEntry(): void; +} + +export interface Options { + autoClose?: boolean; + lazyEntries?: boolean; + decodeStrings?: boolean; + validateEntrySizes?: boolean; +} + +export function open(path: string, options: Options, callback?: (err?: Error, zipfile?: ZipFile) => void): void; +export function open(path: string, callback?: (err?: Error, zipfile?: ZipFile) => void): void; +export function fromFd(fd: number, options: Options, callback?: (err?: Error, zipfile?: ZipFile) => void): void; +export function fromFd(fd: number, callback?: (err?: Error, zipfile?: ZipFile) => void): void; +export function fromBuffer(buffer: Buffer, options: Options, callback?: (err?: Error, zipfile?: ZipFile) => void): void; +export function fromBuffer(buffer: Buffer, callback?: (err?: Error, zipfile?: ZipFile) => void): void; +export function fromRandomAccessReader(reader: RandomAccessReader, totalSize: number, options: Options, callback: (err?: Error, zipfile?: ZipFile) => void): void; +export function fromRandomAccessReader(reader: RandomAccessReader, totalSize: number, callback: (err?: Error, zipfile?: ZipFile) => void): void; +export function dosDateTimeToDate(date: number, time: number): Date; +export function validateFileName(fileName: string): string | null; diff --git a/types/yauzl/tsconfig.json b/types/yauzl/tsconfig.json new file mode 100644 index 0000000000..4ed78c552b --- /dev/null +++ b/types/yauzl/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "yauzl-tests.ts" + ] +} diff --git a/types/yauzl/tslint.json b/types/yauzl/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/yauzl/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/yauzl/yauzl-tests.ts b/types/yauzl/yauzl-tests.ts new file mode 100644 index 0000000000..89dc69df30 --- /dev/null +++ b/types/yauzl/yauzl-tests.ts @@ -0,0 +1,28 @@ +import * as yauzl from 'yauzl'; +import { Writable } from 'stream'; + +yauzl.open('path/to/file.zip', {lazyEntries: true}, (err, zipfile) => { + if (err) { + throw err; + } + if (zipfile) { + zipfile.readEntry(); + zipfile.on('entry', entry => { + if (/\/$/.test(entry.fileName)) { + zipfile.readEntry(); + } else { + zipfile.openReadStream(entry, (err, readStream) => { + if (err) { + throw err; + } + if (readStream) { + readStream.on('end', () => { + zipfile.readEntry(); + }); + readStream.pipe(new Writable()); + } + }); + } + }); + } +}); From 28cc2b953d08944f872b5a06114932d9282282af Mon Sep 17 00:00:00 2001 From: Konstantin Kai Date: Mon, 26 Feb 2018 21:54:24 +0200 Subject: [PATCH 118/128] [expo] update definitions to expo-sdk@25.0 (#23812) * Fix LinearGradient props * [expo] update definitions to expo-sdk@25.0 * [expo] add changes from PRs * [expo] add test for BarcodeScanner s barCodeTypes prop * [expo] fix conflict with fhelwanger:camera constants * [expo] merge fhelwanger PR s (for conflict avoid) --- types/expo/expo-tests.tsx | 138 ++- types/expo/index.d.ts | 698 ++++++++++- types/expo/v24/expo-tests.tsx | 554 +++++++++ types/expo/v24/index.d.ts | 2101 +++++++++++++++++++++++++++++++++ types/expo/v24/tsconfig.json | 32 + types/expo/v24/tslint.json | 7 + 6 files changed, 3479 insertions(+), 51 deletions(-) create mode 100644 types/expo/v24/expo-tests.tsx create mode 100644 types/expo/v24/index.d.ts create mode 100644 types/expo/v24/tsconfig.json create mode 100644 types/expo/v24/tslint.json diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 6a1f17ae3f..187d62b2ee 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -27,7 +27,10 @@ import { LinearGradient, Permissions, registerRootComponent, - ScreenOrientation + ScreenOrientation, + SQLite, + Calendar, + MailComposer } from 'expo'; Accelerometer.addListener((obj) => { @@ -207,7 +210,7 @@ const barcodeReadCallback = () => {}; ); @@ -515,9 +518,13 @@ KeepAwake.deactivate(); () => ( + start={[1, 1]} /> +); + +() => ( + ); Permissions.CAMERA === 'camera'; @@ -548,3 +555,124 @@ class __TestEntry__ extends React.Component { } } registerRootComponent(__TestEntry__); + +Calendar.EntityTypes.EVENT === 'event'; +Calendar.EntityTypes.REMINDER === 'reminder'; + +Calendar.CalendarType.LOCAL === 'local'; +Calendar.CalendarType.CALDAV === 'caldav'; +Calendar.CalendarType.EXCHANGE === 'exchange'; +Calendar.CalendarType.SUBSCRIBED === 'subscribed'; +Calendar.CalendarType.BIRTHDAYS === 'birthdays'; + +async () => { + const result = await Calendar.getCalendarsAsync(Calendar.EntityTypes.EVENT); + result.length; + + const calendar = result[0]; + calendar.id === ''; + calendar.title === ''; + calendar.sourceId === ''; + calendar.type === Calendar.CalendarType.BIRTHDAYS; + calendar.color === ''; + calendar.entityType === Calendar.EntityTypes.EVENT; + calendar.allowsModifications === true; + calendar.allowedAvailabilities === ['']; + calendar.isPrimary === true; + calendar.name === ''; + calendar.ownerAccount === ''; + calendar.timeZone === ''; + calendar.allowedReminders === ['']; + calendar.allowedAttendeeTypes === ['']; + calendar.isVisible === false; + calendar.isSynced === false; + calendar.accessLevel === Calendar.CalendarAccessLevel.CONTRIBUTOR; + + if (calendar.source) { + calendar.source.id === ''; + calendar.source.type === ''; + calendar.source.name === ''; + calendar.source.isLocalAccount === false; + } + + const id1 = await Calendar.createCalendarAsync({ + accessLevel: Calendar.CalendarAccessLevel.EDITOR + }); + + id1 === ''; + + const id2 = await Calendar.updateCalendarAsync('1234', { + isVisible: false + }); + + id2 === ''; + + const id3 = await Calendar.updateCalendarAsync('1234', null); + + await Calendar.deleteCalendarAsync('1234'); + + const events = await Calendar.getEventsAsync( + ['123', '124'], + new Date(), + new Date() + ); + + const event1 = events[0]; + + event1.accessLevel === Calendar.EventAccessLevel.CONFIDENTIAL; + event1.alarms === []; + event1.allDay === true; + event1.availability === Calendar.Availability.FREE; + event1.calendarId === ''; + event1.creationDate === ''; + event1.endDate === ''; + event1.endTimeZone === ''; + event1.guestsCanInviteOthers === true; + event1.guestsCanModify === true; + event1.guestsCanSeeGuests === false; + event1.id === ''; + event1.instanceId === ''; + event1.isDetached === false; + + const event2 = await Calendar.getEventAsync('123', { + futureEvents: true + }); + + const eventId1 = await Calendar.createEventAsync('123'); + + const eventId2 = await Calendar.updateEventAsync('1234'); + + await Calendar.deleteEventAsync('1234'); + + const attendees = await Calendar.getAttendeesForEventAsync('123'); + + const aId1 = await Calendar.createAttendeeAsync('123'); + + const aId2 = await Calendar.updateAttendeeAsync('123'); + + await Calendar.deleteAttendeeAsync('123'); + + const reminders = await Calendar.getRemindersAsync(['123']); + + const reminder = await Calendar.getReminderAsync('123'); + + const remId1 = await Calendar.createReminderAsync('123'); + + const remId2 = await Calendar.updateReminderAsync('123'); + + await Calendar.deleteReminderAsync('123'); + + const sources = await Calendar.getSourcesAsync(); + + const source = await Calendar.getSourceAsync('123'); + + Calendar.openEventInCalendar('123'); +}; + +async () => { + const result = await MailComposer.composeAsync({ + subject: 'sss' + }); + + result.status === 'saved'; +}; diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index ae7e45841d..a747a881e6 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for expo 24.0 +// Type definitions for expo 25.0 // Project: https://github.com/expo/expo-sdk // Definitions by: Konstantin Kai // Martynas Kadiša // Jan Aagaard // Sergio Sánchez +// Fernando Helwanger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -632,7 +633,14 @@ export interface BarCodeScannerProps extends ViewProperties { onBarCodeRead?: BarCodeReadCallback; } -export class BarCodeScanner extends Component { } +export class BarCodeScanner extends Component { + static Constants: { + TorchMode: { + on: string; + off: string + } + } & CameraConstants; +} // #endregion // #region BlurView @@ -686,17 +694,21 @@ export class CameraObject { } export interface CameraProps extends ViewProperties { - flashMode?: string | number; - type?: string | number; - ratio?: string; - autoFocus?: string | number | boolean; - focusDepth?: FloatFromZeroToOne; zoom?: FloatFromZeroToOne; - whiteBalance?: string | number; - barCodeTypes?: string[]; + ratio?: string; + focusDepth?: FloatFromZeroToOne; + type?: string | number; onCameraReady?: () => void; - onMountError?: () => void; onBarCodeRead?: BarCodeReadCallback; + faceDetectionMode?: number; + flashMode?: string | number; + barCodeTypes?: Array; + whiteBalance?: string | number; + faceDetectionLandmarks?: number; + autoFocus?: string | number | boolean; + faceDetectionClassifications?: number; + onMountError?: () => void; + onFacesDetected?: (options: { faces: TrackedFaceFeature[] }) => void; ref?: Ref; } @@ -706,7 +718,28 @@ export interface CameraConstants { readonly AutoFocus: string; readonly WhiteBalance: string; readonly VideoQuality: string; - readonly BarCodeType: string; + readonly BarCodeType: { + aztec: string; + codabar: string; + code39: string; + code93: string; + code128: string; + code138: string; + code39mod43: string; + datamatrix: string; + ean13: string; + ean8: string; + interleaved2of5: string; + itf14: string; + maxicode: string; + pdf417: string; + rss14: string; + rssexpanded: string; + upc_a: string; + upc_e: string; + upc_ean: string; + qr: string; + }; } export class Camera extends Component { @@ -726,10 +759,14 @@ export namespace Constants { const isDevice: boolean; interface Platform { - ios: { + ios?: { platform: string; model: string; userInterfaceIdiom: string; + buildNumber: string; + }; + android?: { + versionCode: string; }; } const platform: Platform; @@ -1088,36 +1125,42 @@ export namespace FacebookAds { /** * FaceDetector */ +export interface Point { + x: Axis; + y: Axis; +} + +export interface FaceFeature { + bounds: { + size: { + width: number; + height: number; + }, + origin: Point; + }; + smilingProbability?: number; + leftEarPosition?: Point; + rightEarPosition?: Point; + leftEyePosition?: Point; + leftEyeOpenProbability?: number; + rightEyePosition?: Point; + rightEyeOpenProbability?: number; + leftCheekPosition?: Point; + rightCheekPosition?: Point; + leftMouthPosition?: Point; + mouthPosition?: Point; + rightMouthPosition?: Point; + bottomMouthPosition?: Point; + noseBasePosition?: Point; + yawAngle?: number; + rollAngle?: number; +} + +export interface TrackedFaceFeature extends FaceFeature { + faceID?: number; +} + export namespace FaceDetector { - interface Point { - x: Axis; - y: Axis; - } - interface FaceFeature { - bounds: { - size: { - width: number; - height: number; - }, - origin: Point; - }; - smilingProbability?: number; - leftEarPosition?: Point; - rightEarPosition?: Point; - leftEyePosition?: Point; - leftEyeOpenProbability?: number; - rightEyePosition?: Point; - rightEyeOpenProbability?: number; - leftCheekPosition?: Point; - rightCheekPosition?: Point; - leftMouthPosition?: Point; - mouthPosition?: Point; - rightMouthPosition?: Point; - bottomMouthPosition?: Point; - noseBasePosition?: Point; - yawAngle?: number; - rollAngle?: number; - } interface DetectFaceResult { faces: FaceFeature[]; image: { @@ -1153,7 +1196,6 @@ export namespace FaceDetector { function detectFaces(uri: string, options?: DetectionOptions): Promise; } - /** * FileSystem */ @@ -1509,11 +1551,11 @@ export class KeepAwake extends Component { /** * LinearGradient */ -export interface LinearGradientProps { +export interface LinearGradientProps extends ViewProperties { colors: string[]; - start: [number, number]; - end: [number, number]; - locations: number[]; + start?: [number, number]; + end?: [number, number]; + locations?: number[]; } export class LinearGradient extends Component { } @@ -1764,6 +1806,12 @@ export namespace Speech { function speak(text: string, options?: SpeechOptions): void; function stop(): void; function isSpeakingAsync(): Promise; + + /** Available on iOS only */ + function pause(): void; + + /** Available on iOS only */ + function resume(): void; } /** @@ -2070,3 +2118,561 @@ export namespace WebBrowser { function openAuthSessionAsync(url: string, redirectUrl?: string): Promise<{ type: 'cancelled' | 'dismissed' }>; function dismissBrowser(): Promise<{ type: 'dismissed' }>; } + +// #region Calendar +/** + * Calendar + * + * Provides an API for interacting with the device’s system calendars, events, reminders, and associated records. + */ +export namespace Calendar { + interface Calendar { + /** Internal ID that represents this calendar on the device */ + id?: string; + + /** Visible name of the calendar */ + title?: string; + + sourceId?: string; // iOS + + /** Object representing the source to be used for the calendar */ + source?: Source; + + /** Type of calendar this object represents */ + type?: CalendarType; // iOS + + /** Color used to display this calendar’s events */ + color?: string; + + /** Whether the calendar is used in the Calendar or Reminders OS app */ + entityType?: EntityTypes; // iOS + + /** Boolean value that determines whether this calendar can be modified */ + allowsModifications?: boolean; + + /** Availability types that this calendar supports */ + allowedAvailabilities?: Availability[]; + + /** Boolean value indicating whether this is the device’s primary calendar */ + isPrimary?: boolean; // Android + + /** Internal system name of the calendar */ + name?: string; // Android + + /** Name for the account that owns this calendar */ + ownerAccount?: string; // Android + + /** Time zone for the calendar */ + timeZone?: string; // Android + + /** Alarm methods that this calendar supports */ + allowedReminders?: AlarmMethod[]; // Android + + /** Attendee types that this calendar supports */ + allowedAttendeeTypes?: AttendeeType[]; // Android + + /** Indicates whether the OS displays events on this calendar */ + isVisible?: boolean; // Android + + /** Indicates whether this calendar is synced and its events stored on the device */ + isSynced?: boolean; // Android + + /** Level of access that the user has for the calendar */ + accessLevel?: CalendarAccessLevel; // Android + } + + interface Source { + /** Internal ID that represents this source on the device */ + id?: string; // iOS only ?? + + /** Type of account that owns this calendar */ + type?: string; + + /** Name for the account that owns this calendar */ + name?: string; + + /** Whether this source is the local phone account */ + isLocalAccount?: boolean; // Android + } + + interface Event { + /** Internal ID that represents this event on the device */ + id?: string; + + /** ID of the calendar that contains this event */ + calendarId?: string; + + /** Visible name of the event */ + title?: string; + + /** Location field of the event */ + location?: string; + + /** Date when the event record was created */ + creationDate?: string; // iOS + + /** Date when the event record was last modified */ + lastModifiedDate?: string; // iOS + + /** Time zone the event is scheduled in */ + timeZone?: string; + + /** Time zone for the event end time */ + endTimeZone?: string; // Android + + /** URL for the event */ + url?: string; // iOS + + /** Description or notes saved with the event */ + notes?: string; + + /** Array of Alarm objects which control automated reminders to the user */ + alarms?: Alarm[]; + + /** Object representing rules for recurring or repeating events. Null for one-time events. */ + recurrenceRule?: RecurrenceRule; + + /** Date object or string representing the time when the event starts */ + startDate?: string; + + /** Date object or string representing the time when the event ends */ + endDate?: string; + + /** For recurring events, the start date for the first (original) instance of the event */ + originalStartDate?: string; // iOS + + /** Boolean value indicating whether or not the event is a detached (modified) instance of a recurring event */ + isDetached?: boolean; // iOS + + /** Whether the event is displayed as an all-day event on the calendar */ + allDay?: boolean; + + /** The availability setting for the event */ + availability?: Availability; // Availability + + /** Status of the event */ + status?: EventStatus; // Status + + /** Organizer of the event, as an Attendee object */ + organizer?: string; // Organizer - iOS + + /** Email address of the organizer of the event */ + organizerEmail?: string; // Android + + /** User’s access level for the event */ + accessLevel?: EventAccessLevel; // Android, + + /** Whether invited guests can modify the details of the event */ + guestsCanModify?: boolean; // Android, + + /** Whether invited guests can invite other guests */ + guestsCanInviteOthers?: boolean; // Android + + /** Whether invited guests can see other guests */ + guestsCanSeeGuests?: boolean; // Android + + /** For detached (modified) instances of recurring events, the ID of the original recurring event */ + originalId?: string; // Android + + /** For instances of recurring events, volatile ID representing this instance; not guaranteed to always refer to the same instance */ + instanceId?: string; // Android + } + + interface Attendee { + /** Internal ID that represents this attendee on the device */ + id?: string; // Android + + /** Indicates whether or not this attendee is the current OS user */ + isCurrentUser?: boolean; // iOS + + /** Displayed name of the attendee */ + name?: string; + + /** Role of the attendee at the event */ + role?: AttendeeRole; + + /** Status of the attendee in relation to the event */ + status?: AttendeeStatus; + + /** Type of the attendee */ + type?: AttendeeType; + + /** URL for the attendee */ + url?: string; // iOS + + /** Email address of the attendee */ + email?: string; // Android + } + + interface Reminder { + /** Internal ID that represents this reminder on the device */ + id?: string; + + /** ID of the calendar that contains this reminder */ + calendarId?: string; + + /** Visible name of the reminder */ + title?: string; + + /** Location field of the reminder */ + location?: string; + + /** Date when the reminder record was created */ + creationDate?: string; + + /** Date when the reminder record was last modified */ + lastModifiedDate?: string; + + /** Time zone the reminder is scheduled in */ + timeZone?: string; + + /** URL for the reminder */ + url?: string; + + /** Description or notes saved with the reminder */ + notes?: string; + + /** Array of Alarm objects which control automated alarms to the user about the task */ + alarms?: Alarm[]; + + /** Object representing rules for recurring or repeated reminders. Null for one-time tasks. */ + recurrenceRule?: RecurrenceRule; + + /** Date object or string representing the start date of the reminder task */ + startDate?: string; + + /** Date object or string representing the time when the reminder task is due */ + dueDate?: string; + + /** Indicates whether or not the task has been completed */ + completed?: boolean; + + /** Date object or string representing the date of completion, if completed is true */ + completionDate?: string; + } + + interface Alarm { + /** Date object or string representing an absolute time the alarm should occur; overrides relativeOffset and structuredLocation if specified alongside either */ + absoluteDate?: string; // iOS + + /** Number of minutes from the startDate of the calendar item that the alarm should occur; use negative values to have the alarm occur before the startDate */ + relativeOffset?: string; + structuredLocation?: { + // iOS + title?: string; + proximity?: string; // Proximity + radius?: number; + coords?: { + latitude?: number; + longitude?: number; + }; + }; + + /** Method of alerting the user that this alarm should use; on iOS this is always a notification */ + method?: AlarmMethod; // Method, Android + } + + interface RecurrenceRule { + /** How often the calendar item should recur */ + frequency: Frequency; // Frequency + + /** Interval at which the calendar item should recur. For example, an interval: 2 with frequency: DAILY would yield an event that recurs every other day. Defaults to 1 . */ + interval?: number; + + /** Date on which the calendar item should stop recurring; overrides occurrence if both are specified */ + endDate?: string; + + /** Number of times the calendar item should recur before stopping */ + occurrence?: number; + } + + enum EntityTypes { + EVENT = 'event', + REMINDER = 'reminder', + } + + enum CalendarType { + LOCAL = 'local', + CALDAV = 'caldav', + EXCHANGE = 'exchange', + SUBSCRIBED = 'subscribed', + BIRTHDAYS = 'birthdays' + } + + enum Availability { + NOT_SUPPORTED = 'notSupported', // iOS + BUSY = 'busy', + FREE = 'free', + TENTATIVE = 'tentative', + UNAVAILABLE = 'unavailable' // iOS + } + + enum AlarmMethod { + ALARM = 'alarm', + ALERT = 'alert', + EMAIL = 'email', + SMS = 'sms', + DEFAULT = 'default', + } + + enum AttendeeType { + UNKNOWN = 'unknown', // iOS + PERSON = 'person', // iOS + ROOM = 'room', // iOS + GROUP = 'group', // iOS + RESOURCE = 'resource', + OPTIONAL = 'optional', // Android + REQUIRED = 'required', // Android + NONE = 'none' // Android + } + + enum CalendarAccessLevel { + CONTRIBUTOR = 'contributor', + EDITOR = 'editor', + FREEBUSY = 'freebusy', + OVERRIDE = 'override', + OWNER = 'owner', + READ = 'read', + RESPOND = 'respond', + ROOT = 'root', + NONE = 'none' + } + + enum EventAccessLevel { + CONFIDENTIAL = 'confidential', + PRIVATE = 'private', + PUBLIC = 'public', + DEFAULT = 'default' + } + + enum EventStatus { + NONE = 'none', + CONFIRMED = 'confirmed', + TENTATIVE = 'tentative', + CANCELED = 'canceled' + } + + enum AttendeeRole { + UNKNOWN = 'unknown', // iOS + REQUIRED = 'required', // iOS + OPTIONAL = 'optional', // iOS + CHAIR = 'chair', // iOS + NON_PARTICIPANT = 'nonParticipant', // iOS + ATTENDEE = 'attendee', // Android + ORGANIZER = 'organizer', // Android + PERFORMER = 'performer', // Android + SPEAKER = 'speaker', // Android + NONE = 'none' // Android + } + + enum AttendeeStatus { + UNKNOWN = 'unknown', // iOS + PENDING = 'pending', // iOS + ACCEPTED = 'accepted', + DECLINED = 'declined', + TENTATIVE = 'tentative', + DELEGATED = 'delegated', // iOS + COMPLETED = 'completed', // iOS + IN_PROCESS = 'inProcess', // iOS + INVITED = 'invited', // Android + NONE = 'none' // Android + } + + enum Frequency { + DAILY = 'daily', + WEEKLY = 'weekly', + MONTHLY = 'monthly', + YEARLY = 'yearly' + } + + enum ReminderStatus { + COMPLETED = 'completed', + INCOMPLETE = 'incomplete' + } + + interface RecurringEventOptions { + futureEvents?: boolean; + instanceStartDate?: string; + } + + /** Gets an array of calendar objects with details about the different calendars stored on the device. */ + function getCalendarsAsync( + /** (iOS only) Not required, but if defined, filters the returned calendars to a specific entity type. */ + entityType?: EntityTypes + ): Promise; + + /** Creates a new calendar on the device, allowing events to be added later and displayed. */ + function createCalendarAsync(details: Calendar): Promise; + + /** Updates the provided details of an existing calendar stored on the device. To remove a property, explicitly set it to null in details */ + function updateCalendarAsync(id: string, details?: Calendar | null): Promise; + + /** Deletes an existing calendar and all associated events/reminders/attendees from the device. Use with caution. */ + function deleteCalendarAsync(id: string): Promise; + + /** Returns all events in a given set of calendars over a specified time period. */ + function getEventsAsync( + /** Array of IDs of calendars to search for events in. Required. */ + calendarIds: string[], + + /** Beginning of time period to search for events in. Required. */ + startDate: Date, + + /** End of time period to search for events in. Required. */ + endDate: Date + ): Promise; + + /** Returns a specific event selected by ID. If a specific instance of a recurring event is desired, the start date of this instance must also be provided, as instances of recurring events do not have their own unique and stable IDs on either iOS or Android. */ + function getEventAsync( + /** ID of the event to return. Required. */ + id: string, + + /** A map of options for recurring events */ + recurringEventOptions?: RecurringEventOptions + ): Promise; + + /** Creates a new event on the specified calendar. */ + function createEventAsync( + /** ID of the calendar to create this event in. Required. */ + calendarId: string, + details?: Event + ): Promise; + + /** Updates the provided details of an existing calendar stored on the device. To remove a property, explicitly set it to null in details */ + function updateEventAsync( + /** ID of the event to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Event | null, + + /** A map of options for recurring events */ + recurrentEventOptions?: RecurringEventOptions + ): Promise; + + /** Deletes an existing event from the device. Use with caution. */ + function deleteEventAsync( + /** ID of the event to be deleted. Required. */ + id: string, + + /** A map of options for recurring events */ + recurringEventOptions?: RecurringEventOptions + ): Promise; + + /** Gets all attendees for a given event (or instance of a recurring event). */ + function getAttendeesForEventAsync( + /** ID of the event to return attendees for. Required. */ + eventId: string, + + /** A map of options for recurring events */ + recurrentEventOptions?: RecurringEventOptions + ): Promise; + + /** Available on Android only. Creates a new attendee record and adds it to the specified event. Note that if eventId specifies a recurring event, this will add the attendee to every instance of the event. */ + function createAttendeeAsync( + /** ID of the event to add this attendee to. Required. */ + eventId: string, + + /** A map of details for the attendee to be created */ + details?: Attendee + ): Promise; + + /** Available on Android only. Updates an existing attendee record. To remove a property, explicitly set it to null in details. */ + function updateAttendeeAsync( + /** ID of the attendee record to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Attendee | null + ): Promise; + + /** Available on Android only. Deletes an existing attendee record from the device. Use with caution. */ + function deleteAttendeeAsync(id: string): Promise; + + /** Available on iOS only. Returns a list of reminders matching the provided criteria. */ + function getRemindersAsync( + /** Array of IDs of calendars to search for reminders in. Required. */ + calendarIds: string[], + + status?: ReminderStatus, + + /** Beginning of time period to search for reminders in. Required if status is defined. */ + startDate?: Date, + + /** End of time period to search for reminders in. Required if status is defined. */ + endDate?: Date + ): Promise; + + /** Available on iOS only. Returns a specific reminder selected by ID. */ + function getReminderAsync(id: string): Promise; + + /** Available on iOS only. Creates a new reminder on the specified calendar. */ + function createReminderAsync( + /** ID of the calendar to create this reminder in. Required. */ + calendarId: string, + + /** A map of details for the reminder to be created */ + details?: Reminder + ): Promise; + + /** Available on iOS only. Updates the provided details of an existing reminder stored on the device. To remove a property, explicitly set it to null in details. */ + function updateReminderAsync( + /** ID of the reminder to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Reminder | null + ): Promise; + + /** Available on iOS only. Deletes an existing reminder from the device. Use with caution. */ + function deleteReminderAsync(id: string): Promise; + + /** Available on iOS only. */ + function getSourcesAsync(): Promise; + + /** Available on iOS only. Returns a specific source selected by ID. */ + function getSourceAsync(id: string): Promise; + + /** Available on Android only. Sends an intent to open the specified event in the OS Calendar app. */ + function openEventInCalendar( + /** ID of the event to open. Required. */ + id: string + ): void; +} +// #endregion + +// #region Calendar +/** + * An API to compose mails using OS specific UI. + */ +export namespace MailComposer { + interface ComposeOptions { + /** An array of e-mail addressess of the recipients. */ + recipients?: string[]; + + /** An array of e-mail addressess of the CC recipients. */ + ccRecipients?: string[]; + + /** An array of e-mail addressess of the BCC recipients. */ + bccRecipients?: string[]; + + /** Subject of the mail. */ + subject?: string; + + /** Body of the mail. */ + body?: string; + + /** Whether the body contains HTML tags so it could be formatted properly. Not working perfectly on Android. */ + isHtml?: boolean; + + /** An array of app’s internal file uris to attach. */ + attachments?: string[]; + } + + /** Resolves to a promise with object containing status field that could be either sent, saved or cancelled. Android does not provide such info so it always resolves to sent. */ + function composeAsync( + /** A map defining the data to fill the mail */ + options: ComposeOptions + ): Promise<{ status: 'sent' | 'saved' | 'cancelled' }>; +} +// #endregion diff --git a/types/expo/v24/expo-tests.tsx b/types/expo/v24/expo-tests.tsx new file mode 100644 index 0000000000..77f9bbba87 --- /dev/null +++ b/types/expo/v24/expo-tests.tsx @@ -0,0 +1,554 @@ +import * as React from 'react'; +import { Text } from 'react-native'; + +import { + Accelerometer, + Amplitude, + Asset, + AuthSession, + Audio, + AppLoading, + BarCodeScanner, + BlurViewProps, + BlurView, + Brightness, + Camera, + CameraObject, + DocumentPicker, + Facebook, + FacebookAds, + FileSystem, + ImagePicker, + ImageManipulator, + FaceDetector, + Svg, + IntentLauncherAndroid, + KeepAwake, + LinearGradient, + Permissions, + registerRootComponent, + ScreenOrientation +} from 'expo'; + +Accelerometer.addListener((obj) => { + obj.x; + obj.y; + obj.z; +}); +Accelerometer.removeAllListeners(); +Accelerometer.setUpdateInterval(1000); + +Amplitude.initialize('key'); +Amplitude.setUserId('userId'); +Amplitude.setUserProperties({key: 1}); +Amplitude.clearUserProperties(); +Amplitude.logEvent('name'); +Amplitude.logEventWithProperties('event', {key: 'value'}); +Amplitude.setGroup('type', ['value']); + +const asset = Asset.fromModule(1); +asset.downloadAsync(); +Asset.loadAsync(1); +Asset.loadAsync([1, 2, 3]); +const asset1 = new Asset({ + uri: 'uri', + type: 'type', + name: 'name', + hash: 'hash', + width: 122, + height: 122 +}); + +const url = AuthSession.getRedirectUrl(); +AuthSession.dismiss(); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: 'url2' +}).then(result => { + switch (result.type) { + case 'success': + result.event; + result.params; + break; + case 'error': + result.errorCode; + result.params; + result.event; + break; + case 'dismissed': + case 'cancel': + result.type; + break; + } +}); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: undefined +}); + +Audio.setAudioModeAsync({ + shouldDuckAndroid: false, + playsInSilentModeIOS: true, + interruptionModeIOS: 2, + interruptionModeAndroid: 1, + allowsRecordingIOS: true +}); +Audio.setIsEnabledAsync(true); + +Audio.INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS === 0; +Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX === 1; +Audio.INTERRUPTION_MODE_IOS_DUCK_OTHERS === 2; + +Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX === 1; +Audio.INTERRUPTION_MODE_ANDROID_DUCK_OTHERS === 2; + +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT === 0; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_THREE_GPP === 1; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4 === 2; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_NB === 3; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_WB === 4; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADIF === 5; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADTS === 6; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_RTP_AVP === 7; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG2TS === 8; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_WEBM === 9; + +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT === 0; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB === 1; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_WB === 2; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC === 3; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_HE_AAC === 4; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC_ELD === 5; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_VORBIS === 6; + +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_LINEARPCM === 'lpcm'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AC3 === 'ac-3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_60958AC3 === 'cac3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLEIMA4 === 'ima4'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC === 'aac '; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4CELP === 'celp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4HVXC === 'hvxc'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4TWINVQ === 'twvq'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE3 === 'MAC3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE6 === 'MAC6'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ULAW === 'ulaw'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ALAW === 'alaw'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN === 'QDMC'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN2 === 'QDM2'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QUALCOMM === 'Qclp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER1 === '.mp1'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER2 === '.mp2'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER3 === '.mp3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLELOSSLESS === 'alac'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE === 'aach'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_LD === 'aacl'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD === 'aace'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_SBR === 'aacf'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_V2 === 'aacg'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE_V2 === 'aacp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_SPATIAL === 'aacs'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR === 'samr'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR_WB === 'sawb'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AUDIBLE === 'AUDB'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ILBC === 'ilbc'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_DVIINTELIMA === 0x6d730011; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MICROSOFTGSM === 0x6d730031; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AES3 === 'aes3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ENHANCEDAC3 === 'ec-3'; + +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN === 0; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_LOW === 0x20; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MEDIUM === 0x40; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH === 0x60; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MAX === 0x7f; + +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_CONSTANT === 0; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_LONG_TERM_AVERAGE === 1; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE_CONSTRAINED === 2; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE === 3; + +Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY; +Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY; +async () => { + const result = await Audio.Sound.create({uri: 'uri'}, { + volume: 0.5, + rate: 0.6 + }, null, true); + + const sound = result.sound; + const status = result.status; + + if (!status.isLoaded) { + status.error; + } else { + status.didJustFinish; + // etc. + } + + const _status = await sound.getStatusAsync(); + await sound.loadAsync({uri: 'uri'}); +}; + +() => ( + Promise.resolve()} + onFinish={() => {}} + onError={(error) => console.log(error)} /> +); +() => ( + +); + +const barcodeReadCallback = () => {}; +() => ( + +); + +() => ( + +); + +async () => { + await Brightness.setBrightnessAsync(.6); + await Brightness.setSystemBrightnessAsync(.7); + const br1 = await Brightness.getBrightnessAsync(); + const br2 = await Brightness.getSystemBrightnessAsync(); +}; + +Camera.Constants.AutoFocus; +Camera.Constants.Type; +Camera.Constants.FlashMode; +Camera.Constants.WhiteBalance; +Camera.Constants.VideoQuality; +Camera.Constants.BarCodeType; +() => { + return( { + if (component) { + component.recordAsync(); + } + }} />); +}; + +async () => { + const result = await DocumentPicker.getDocumentAsync(); + + if (result.type === 'success') { + result.name; + result.uri; + result.size; + } +}; + +async () => { + const { type, expires, token } = await Facebook.logInWithReadPermissionsAsync("appId"); +}; + +() => ( + {}} + onError={() => {}} /> +); + +async () => { + const info = await FileSystem.getInfoAsync('file'); + + info.exists; + info.isDirectory; + + if (info.exists) { + info.md5; + info.uri; + info.size; + info.modificationTime; + } + + const string: string = await FileSystem.readAsStringAsync('file'); + await FileSystem.writeAsStringAsync('file', 'content'); + await FileSystem.deleteAsync('file'); + await FileSystem.moveAsync({ from: 'from', to: 'to'}); + await FileSystem.copyAsync({ from: 'from', to: 'to' }); + await FileSystem.makeDirectoryAsync('dir'); + const dirs: string[] = await FileSystem.readDirectoryAsync('dir'); + const result = await FileSystem.downloadAsync('from', 'to'); + + result.headers; + result.status; + result.uri; + result.md5; +}; + +async () => { + const result = await ImagePicker.launchImageLibraryAsync({ + mediaTypes: ImagePicker.MediaTypeOptions.Videos + }); + + if (!result.cancelled) { + result.uri; + result.width; + result.height; + } +}; + +async () => { + const result = await ImageManipulator.manipulate('url', { + rotate: 90 + }, { + compress: 0.5 + }); + + result.height; + result.uri; + result.width; +}; + +FaceDetector.Constants.Mode.fast; +FaceDetector.Constants.Mode.accurate; +FaceDetector.Constants.Landmarks.all; +FaceDetector.Constants.Landmarks.none; +FaceDetector.Constants.Classifications.all; +FaceDetector.Constants.Classifications.none; +async () => { + const result = await FaceDetector.detectFaces('url', { + mode: FaceDetector.Constants.Mode.fast, + detectLandmarks: FaceDetector.Constants.Landmarks.all, + runClassifications: FaceDetector.Constants.Classifications.none + }); + + result.faces[0]; +}; + +() => ( + + + + + + + + + STROKED TEXT + + + + + + + + We go up and down, + then up again + + + + + + + + + + + + + + + + + + + + + +); + +IntentLauncherAndroid.ACTION_ACCESSIBILITY_SETTINGS === 'android.settings.ACCESSIBILITY_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_NOTIFICATION_REDACTION === 'android.settings.ACTION_APP_NOTIFICATION_REDACTION'; +IntentLauncherAndroid.ACTION_CONDITION_PROVIDER_SETTINGS === 'android.settings.ACTION_CONDITION_PROVIDER_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_LISTENER_SETTINGS === 'android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS'; +IntentLauncherAndroid.ACTION_PRINT_SETTINGS === 'android.settings.ACTION_PRINT_SETTINGS'; +IntentLauncherAndroid.ACTION_ADD_ACCOUNT_SETTINGS === 'android.settings.ADD_ACCOUNT_SETTINGS'; +IntentLauncherAndroid.ACTION_AIRPLANE_MODE_SETTINGS === 'android.settings.AIRPLANE_MODE_SETTINGS'; +IntentLauncherAndroid.ACTION_APN_SETTINGS === 'android.settings.APN_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_DETAILS_SETTINGS === 'android.settings.APPLICATION_DETAILS_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_DEVELOPMENT_SETTINGS === 'android.settings.APPLICATION_DEVELOPMENT_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_SETTINGS === 'android.settings.APPLICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_NOTIFICATION_SETTINGS === 'android.settings.APP_NOTIFICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_OPS_SETTINGS === 'android.settings.APP_OPS_SETTINGS'; +IntentLauncherAndroid.ACTION_BATTERY_SAVER_SETTINGS === 'android.settings.BATTERY_SAVER_SETTINGS'; +IntentLauncherAndroid.ACTION_BLUETOOTH_SETTINGS === 'android.settings.BLUETOOTH_SETTINGS'; +IntentLauncherAndroid.ACTION_CAPTIONING_SETTINGS === 'android.settings.CAPTIONING_SETTINGS'; +IntentLauncherAndroid.ACTION_CAST_SETTINGS === 'android.settings.CAST_SETTINGS'; +IntentLauncherAndroid.ACTION_DATA_ROAMING_SETTINGS === 'android.settings.DATA_ROAMING_SETTINGS'; +IntentLauncherAndroid.ACTION_DATE_SETTINGS === 'android.settings.DATE_SETTINGS'; +IntentLauncherAndroid.ACTION_DEVICE_INFO_SETTINGS === 'android.settings.DEVICE_INFO_SETTINGS'; +IntentLauncherAndroid.ACTION_DEVICE_NAME === 'android.settings.DEVICE_NAME'; +IntentLauncherAndroid.ACTION_DISPLAY_SETTINGS === 'android.settings.DISPLAY_SETTINGS'; +IntentLauncherAndroid.ACTION_DREAM_SETTINGS === 'android.settings.DREAM_SETTINGS'; +IntentLauncherAndroid.ACTION_HARD_KEYBOARD_SETTINGS === 'android.settings.HARD_KEYBOARD_SETTINGS'; +IntentLauncherAndroid.ACTION_HOME_SETTINGS === 'android.settings.HOME_SETTINGS'; +IntentLauncherAndroid.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS === 'android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS === 'android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS'; +IntentLauncherAndroid.ACTION_INPUT_METHOD_SETTINGS === 'android.settings.INPUT_METHOD_SETTINGS'; +IntentLauncherAndroid.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS === 'android.settings.INPUT_METHOD_SUBTYPE_SETTINGS'; +IntentLauncherAndroid.ACTION_INTERNAL_STORAGE_SETTINGS === 'android.settings.INTERNAL_STORAGE_SETTINGS'; +IntentLauncherAndroid.ACTION_LOCALE_SETTINGS === 'android.settings.LOCALE_SETTINGS'; +IntentLauncherAndroid.ACTION_LOCATION_SOURCE_SETTINGS === 'android.settings.LOCATION_SOURCE_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS === 'android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_APPLICATIONS_SETTINGS === 'android.settings.MANAGE_APPLICATIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_DEFAULT_APPS_SETTINGS === 'android.settings.MANAGE_DEFAULT_APPS_SETTINGS'; +IntentLauncherAndroid.ACTION_MEMORY_CARD_SETTINGS === 'android.settings.MEMORY_CARD_SETTINGS'; +IntentLauncherAndroid.ACTION_MONITORING_CERT_INFO === 'android.settings.MONITORING_CERT_INFO'; +IntentLauncherAndroid.ACTION_NETWORK_OPERATOR_SETTINGS === 'android.settings.NETWORK_OPERATOR_SETTINGS'; +IntentLauncherAndroid.ACTION_NFCSHARING_SETTINGS === 'android.settings.NFCSHARING_SETTINGS'; +IntentLauncherAndroid.ACTION_NFC_PAYMENT_SETTINGS === 'android.settings.NFC_PAYMENT_SETTINGS'; +IntentLauncherAndroid.ACTION_NFC_SETTINGS === 'android.settings.NFC_SETTINGS'; +IntentLauncherAndroid.ACTION_NIGHT_DISPLAY_SETTINGS === 'android.settings.NIGHT_DISPLAY_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS === 'android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_SETTINGS === 'android.settings.NOTIFICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_PAIRING_SETTINGS === 'android.settings.PAIRING_SETTINGS'; +IntentLauncherAndroid.ACTION_PRIVACY_SETTINGS === 'android.settings.PRIVACY_SETTINGS'; +IntentLauncherAndroid.ACTION_QUICK_LAUNCH_SETTINGS === 'android.settings.QUICK_LAUNCH_SETTINGS'; +IntentLauncherAndroid.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS === 'android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS'; +IntentLauncherAndroid.ACTION_SECURITY_SETTINGS === 'android.settings.SECURITY_SETTINGS'; +IntentLauncherAndroid.ACTION_SETTINGS === 'android.settings.SETTINGS'; +IntentLauncherAndroid.ACTION_SHOW_ADMIN_SUPPORT_DETAILS === 'android.settings.SHOW_ADMIN_SUPPORT_DETAILS'; +IntentLauncherAndroid.ACTION_SHOW_INPUT_METHOD_PICKER === 'android.settings.SHOW_INPUT_METHOD_PICKER'; +IntentLauncherAndroid.ACTION_SHOW_REGULATORY_INFO === 'android.settings.SHOW_REGULATORY_INFO'; +IntentLauncherAndroid.ACTION_SHOW_REMOTE_BUGREPORT_DIALOG === 'android.settings.SHOW_REMOTE_BUGREPORT_DIALOG'; +IntentLauncherAndroid.ACTION_SOUND_SETTINGS === 'android.settings.SOUND_SETTINGS'; +IntentLauncherAndroid.ACTION_STORAGE_MANAGER_SETTINGS === 'android.settings.STORAGE_MANAGER_SETTINGS'; +IntentLauncherAndroid.ACTION_SYNC_SETTINGS === 'android.settings.SYNC_SETTINGS'; +IntentLauncherAndroid.ACTION_SYSTEM_UPDATE_SETTINGS === 'android.settings.SYSTEM_UPDATE_SETTINGS'; +IntentLauncherAndroid.ACTION_TETHER_PROVISIONING_UI === 'android.settings.TETHER_PROVISIONING_UI'; +IntentLauncherAndroid.ACTION_TRUSTED_CREDENTIALS_USER === 'android.settings.TRUSTED_CREDENTIALS_USER'; +IntentLauncherAndroid.ACTION_USAGE_ACCESS_SETTINGS === 'android.settings.USAGE_ACCESS_SETTINGS'; +IntentLauncherAndroid.ACTION_USER_DICTIONARY_INSERT === 'android.settings.USER_DICTIONARY_INSERT'; +IntentLauncherAndroid.ACTION_USER_DICTIONARY_SETTINGS === 'android.settings.USER_DICTIONARY_SETTINGS'; +IntentLauncherAndroid.ACTION_USER_SETTINGS === 'android.settings.USER_SETTINGS'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_AIRPLANE_MODE === 'android.settings.VOICE_CONTROL_AIRPLANE_MODE'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE === 'android.settings.VOICE_CONTROL_BATTERY_SAVER_MODE'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE === 'android.settings.VOICE_CONTROL_DO_NOT_DISTURB_MODE'; +IntentLauncherAndroid.ACTION_VOICE_INPUT_SETTINGS === 'android.settings.VOICE_INPUT_SETTINGS'; +IntentLauncherAndroid.ACTION_VPN_SETTINGS === 'android.settings.VPN_SETTINGS'; +IntentLauncherAndroid.ACTION_VR_LISTENER_SETTINGS === 'android.settings.VR_LISTENER_SETTINGS'; +IntentLauncherAndroid.ACTION_WEBVIEW_SETTINGS === 'android.settings.WEBVIEW_SETTINGS'; +IntentLauncherAndroid.ACTION_WIFI_IP_SETTINGS === 'android.settings.WIFI_IP_SETTINGS'; +IntentLauncherAndroid.ACTION_WIFI_SETTINGS === 'android.settings.WIFI_SETTINGS'; +IntentLauncherAndroid.ACTION_WIRELESS_SETTINGS === 'android.settings.WIRELESS_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_AUTOMATION_SETTINGS === 'android.settings.ZEN_MODE_AUTOMATION_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_EVENT_RULE_SETTINGS === 'android.settings.ZEN_MODE_EVENT_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS === 'android.settings.ZEN_MODE_EXTERNAL_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_PRIORITY_SETTINGS === 'android.settings.ZEN_MODE_PRIORITY_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS === 'android.settings.ZEN_MODE_SCHEDULE_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_SETTINGS === 'android.settings.ZEN_MODE_SETTINGS'; + +KeepAwake.activate(); +KeepAwake.deactivate(); + +() => ( + +); + +() => ( + +); + +Permissions.CAMERA === 'camera'; +Permissions.CAMERA_ROLL === 'cameraRoll'; +Permissions.AUDIO_RECORDING === 'audioRecording'; +Permissions.CONTACTS === 'contacts'; +Permissions.NOTIFICATIONS === 'remoteNotifications'; +Permissions.REMOTE_NOTIFICATIONS === 'remoteNotifications'; +Permissions.SYSTEM_BRIGHTNESS === 'systemBrightness'; +async () => { + const result = await Permissions.askAsync(Permissions.CAMERA); + + result.status === 'granted'; + result.status === 'denied'; + result.status === 'undetermined'; + + result.expires === 'never'; +}; + +ScreenOrientation.Orientation.ALL; +ScreenOrientation.allow(ScreenOrientation.Orientation.ALL); + +class __TestEntry__ extends React.Component { + render() { + return( + test + ); + } +} +registerRootComponent(__TestEntry__); diff --git a/types/expo/v24/index.d.ts b/types/expo/v24/index.d.ts new file mode 100644 index 0000000000..4bf5e48dc9 --- /dev/null +++ b/types/expo/v24/index.d.ts @@ -0,0 +1,2101 @@ +// Type definitions for expo 24.0 +// Project: https://github.com/expo/expo-sdk +// Definitions by: Konstantin Kai +// Martynas Kadiša +// Jan Aagaard +// Sergio Sánchez +// Fernando Helwanger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { EventSubscription } from 'fbemitter'; +import { Component, ComponentClass, Ref, ComponentType } from 'react'; +import { + ColorPropType, + ImageRequireSource, + ImageURISource, + NativeEventEmitter, + ViewProperties, + ViewStyle, + Permission +} from 'react-native'; + +export type Axis = number; +export type BarCodeReadCallback = (params: { type: string; data: string; }) => void; +export type FloatFromZeroToOne = 0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1; +export type Md5 = string; +export type Orientation = 'portrait' | 'landscape'; +export type RequireSource = ImageRequireSource; +export type ResizeModeContain = 'contain'; +export type ResizeModeCover = 'cover'; +export type ResizeModeStretch = 'stretch'; +export type URISource = ImageURISource; + +export interface HashMap { [key: string]: any; } + +/** Access the device accelerometer sensor(s) to respond to changes in acceleration in 3d space. */ +export namespace Accelerometer { + interface AccelerometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + /** + * Subscribe for updates to the accelerometer. + * @param listener A callback that is invoked when an accelerometer update is available. When invoked, the listener is provided a single argumument that is an object containing keys x, y, z. + * @returns An EventSubscription object that you can call remove() on when you would like to unsubscribe the listener. + */ + function addListener(listener: (obj: AccelerometerObject) => any): EventSubscription; + + /** Remove all listeners. */ + function removeAllListeners(): void; + + /** + * Subscribe for updates to the accelerometer. + * @param intervalMs Desired interval in milliseconds between accelerometer updates. + */ + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Provides access to Amplitude mobile analytics which basically lets you log various events to the Cloud. This module wraps Amplitude’s iOS and Android SDKs. + * + * Note: Session tracking may not work correctly when running Experiences in the main Expo app. It will work correctly if you create a standalone app. + */ +export namespace Amplitude { + /** Initializes Amplitude with your Amplitude API key. */ + function initialize(apiKey: string): void; + + /** Assign a user ID to the current user. If you don’t have a system for user IDs you don’t need to call this. */ + function setUserId(userId: string): void; + + /** Set properties for the current user. */ + function setUserProperties(userProperties: HashMap): void; + + /** Clear properties set by `setUserProperties()`. */ + function clearUserProperties(): void; + + /** Log an event to Amplitude. */ + function logEvent(eventName: string): void; + + /** Log an event to Amplitude with custom properties. */ + function logEventWithProperties( + eventName: string, + + /** A map of custom properties. */ + properties: HashMap + ): void; + + /** Add the current user to a group. */ + function setGroup( + /** The group name, e.g. `'sports'`. */ + groupType: string, + + /** An array of group names, e.g. `['tennis', 'soccer']`. */ + groupNames: string[] + ): void; +} + +// #region AppLoading +/** The following props are recommended, but optional for the sake of backwards compatibility (they were introduced in SDK21). If you do not provide any props, you are responsible for coordinating loading assets, handling errors, and updating state to unmount the `AppLoading` component. */ +export type AppLoadingProps = { + /** A `function` that returns a `Promise`. The `Promise` should resolve when the app is done loading data and assets. */ + startAsync: () => Promise; + + /** Required if you provide `startAsync`. Called when `startAsync` resolves or rejects. This should be used to set state and unmount the `AppLoading` component. */ + onFinish: () => void; + + /** If `startAsync` throws an error, it is caught and passed into the function provided to `onError`. */ + onError?: (error: Error) => void; +} | { + startAsync: null; + onFinish: null; + onError?: null; +}; + +/** + * A React component that tells Expo to keep the app loading screen open if it is the first and only component rendered in your app. When it is removed, the loading screen will disappear and your app will be visible. + * + * This is incredibly useful to let you download and cache fonts, logo and icon images and other assets that you want to be sure the user has on their device for an optimal experience before rendering they start using the app. + */ +export class AppLoading extends Component { } +// #endregion AppLoading + +/** This module provides an interface to Expo’s asset system. An asset is any file that lives alongside the source code of your app that the app needs at runtime. Examples include images, fonts and sounds. Expo’s asset system integrates with React Native’s, so that you can refer to files with require('path/to/file'). This is how you refer to static image files in React Native for use in an Image component, for example. */ +export class Asset { + constructor({ name, type, hash, uri, width, height }: { + name: string; + type: string; + hash: string; + uri: string; + width?: number; + height?: number; + }); + + /** The MD5 hash of the asset’s data. */ + hash: Md5; + + /** The name of the asset file without the extension. Also without the part from @ onward in the filename (used to specify scale factor for images). */ + name: string; + + /** The extension of the asset filename. */ + type: string; + + /** A URI that points to the asset’s data on the remote server. When running the published version of your app, this refers to the the location on Expo’s asset server where Expo has stored your asset. When running the app from XDE during development, this URI points to XDE’s server running on your computer and the asset is served directly from your computer. */ + uri: string; + + /** If the asset has been downloaded (by calling `downloadAsync()`), the `file://` URI pointing to the local file on the device that contains the asset data. */ + localUri: string; + + /** If the asset is an image, the width of the image data divided by the scale factor. The scale factor is the number after `@` in the filename, or `1` if not present. */ + width?: number; + + /** If the asset is an image, the height of the image data divided by the scale factor. The scale factor is the number after `@` in the filename, or `1` if not present. */ + height?: number; + + downloading: boolean; + downloaded: boolean; + downloadCallbacks: Array<{ resolve: () => any, reject: (e?: any) => any }>; + + /** Downloads the asset data to a local file in the device’s cache directory. Once the returned promise is fulfilled without error, the localUri field of this asset points to a local file containing the asset data. The asset is only downloaded if an up-to-date local file for the asset isn’t already present due to an earlier download. */ + downloadAsync(): Promise; + + /** Returns the `Expo.Asset` instance representing an asset given its module. */ + static fromModule(module: RequireSource): Asset; + + /** + * A helper that wraps `Expo.Asset.fromModule(module).downloadAsync` for convenience. + * @param moduleIds An array of `require('path/to/file')`. Can also be just one module without an Array. + */ + static loadAsync(module: RequireSource[] | RequireSource): Promise; +} + +/** + * Provides basic sample playback and recording. + * + * Note that Expo does not yet support backgrounding, so audio is not available to play in the background of your experience. Audio also automatically stops if headphones / bluetooth audio devices are disconnected. + */ +export namespace Audio { + enum InterruptionModeIos { + /** This is the default option. If this option is set, your experience’s audio is mixed with audio playing in background apps. */ + INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS = 0, + + /** If this option is set, your experience’s audio interrupts audio from other apps. */ + INTERRUPTION_MODE_IOS_DO_NOT_MIX = 1, + + /** If this option is set, your experience’s audio lowers the volume ("ducks") of audio from other apps while your audio plays. */ + INTERRUPTION_MODE_IOS_DUCK_OTHERS = 2 + } + + const INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS: 0; + const INTERRUPTION_MODE_IOS_DO_NOT_MIX: 1; + const INTERRUPTION_MODE_IOS_DUCK_OTHERS: 2; + + enum InterruptionModeAndroid { + /** If this option is set, your experience’s audio interrupts audio from other apps. */ + INTERRUPTION_MODE_ANDROID_DO_NOT_MIX = 1, + + /** This is the default option. If this option is set, your experience’s audio lowers the volume ("ducks") of audio from other apps while your audio plays. */ + INTERRUPTION_MODE_ANDROID_DUCK_OTHERS = 2 + } + + const INTERRUPTION_MODE_ANDROID_DO_NOT_MIX: 1; + const INTERRUPTION_MODE_ANDROID_DUCK_OTHERS: 2; + + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT: 0; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_THREE_GPP: 1; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4: 2; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_NB: 3; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_WB: 4; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADIF: 5; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADTS: 6; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_RTP_AVP: 7; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG2TS: 8; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_WEBM: 9; + + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT: 0; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB: 1; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_WB: 2; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC: 3; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_HE_AAC: 4; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC_ELD: 5; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_VORBIS: 6; + + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_LINEARPCM: 'lpcm'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AC3: 'ac-3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_60958AC3: 'cac3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLEIMA4: 'ima4'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC: 'aac '; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4CELP: 'celp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4HVXC: 'hvxc'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4TWINVQ: 'twvq'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE3: 'MAC3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE6: 'MAC6'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ULAW: 'ulaw'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ALAW: 'alaw'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN: 'QDMC'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN2: 'QDM2'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QUALCOMM: 'Qclp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER1: '.mp1'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER2: '.mp2'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER3: '.mp3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLELOSSLESS: 'alac'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE: 'aach'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_LD: 'aacl'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD: 'aace'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_SBR: 'aacf'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_V2: 'aacg'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE_V2: 'aacp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_SPATIAL: 'aacs'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR: 'samr'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR_WB: 'sawb'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AUDIBLE: 'AUDB'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ILBC: 'ilbc'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_DVIINTELIMA: 0x6d730011; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MICROSOFTGSM: 0x6d730031; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AES3: 'aes3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ENHANCEDAC3: 'ec-3'; + + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN: 0; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_LOW: 0x20; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MEDIUM: 0x40; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH: 0x60; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MAX: 0x7f; + + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_CONSTANT: 0; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_LONG_TERM_AVERAGE: 1; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE_CONSTRAINED: 2; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE: 3; + + type RecordingStatus = { + canRecord: false, + isDoneRecording: false + } | { + canRecord: true, + isRecording: boolean, + durationMillis: number + } | { + canRecord: false, + isDoneRecording: true, + durationMillis: number + }; + + const RECORDING_OPTIONS_PRESET_HIGH_QUALITY: RecordingOptions; + const RECORDING_OPTIONS_PRESET_LOW_QUALITY: RecordingOptions; + + interface RecordingOptions { + android: { + extension: string; + outputFormat: number; + audioEncoder: number; + sampleRate?: number; + numberOfChannels?: number; + bitRate?: number; + maxFileSize?: number; + }; + ios: { + extension: string; + outputFormat?: string | number; + audioQuality: number; + sampleRate: number; + numberOfChannels: number; + bitRate: number; + bitRateStrategy?: number; + bitDepthHint?: number; + linearPCMBitDepth?: number; + linearPCMIsBigEndian?: boolean; + linearPCMIsFloat?: boolean; + }; + } + + interface AudioMode { + /** Boolean selecting if your experience’s audio should play in silent mode on iOS. This value defaults to `false`. */ + playsInSilentModeIOS: boolean; + + /** Boolean selecting if recording is enabled on iOS. This value defaults to `false`. NOTE: when this flag is set to true, playback may be routed to the phone receiver instead of to the speaker. */ + allowsRecordingIOS: boolean; + + /** Enum selecting how your experience’s audio should interact with the audio from other apps on iOS. */ + interruptionModeIOS: InterruptionModeIos; + + /** Boolean selecting if your experience’s audio should automatically be lowered in volume ("duck") if audio from another app interrupts your experience. This value defaults to true. If false, audio from other apps will pause your audio. */ + shouldDuckAndroid: boolean; + + /** an enum selecting how your experience’s audio should interact with the audio from other apps on Android: */ + interruptionModeAndroid: InterruptionModeAndroid; + } + + function setIsEnabledAsync(value: boolean): Promise; + function setAudioModeAsync(mode: AudioMode): Promise; + + /** This class represents a sound corresponding to an Asset or URL. */ + class Sound extends PlaybackObject { + constructor(); + + /** + * Creates and loads a sound from source, with optional `initialStatus`, `onPlaybackStatusUpdate`, and `downloadFirst`. + * + * @returns A `Promise` that is rejected if creation failed, or fulfilled with the following dictionary if creation succeeded: + * - `sound`: The newly created and loaded Sound object. + * - `status`: The PlaybackStatus of the Sound object. See the AV documentation for further information. + */ + static create( + /** + * The source of the sound. The following forms are supported: + * + * - A dictionary of the form `{ uri: 'http://path/to/file' }` with a network URL pointing to an audio file on the web. + * - `require('path/to/file')` for an audio file asset in the source code directory. + * - An `Expo.Asset` object for an audio file asset. + */ + source: PlaybackSource, + + /** The initial intended PlaybackStatusToSet of the sound, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. */ + initialStatus?: PlaybackStatusToSet, + + /** A function taking a single parameter PlaybackStatus. This value defaults to `null` if no parameter is passed. */ + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null, + + /** If set to true, the system will attempt to download the resource to the device before loading. This value defaults to `true`. Note that at the moment, this will only work for `source`s of the form `require('path/to/file')` or `Asset` objects. */ + downloadFirst?: boolean + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } + + class Recording { + constructor(); + + /** Gets the `status` of the `Recording`. */ + getStatusAsync(): Promise; + + /** Sets a function to be called regularly with the `status` of the `Recording`. */ + setOnRecordingStatusUpdate(onRecordingStatusUpdate?: (status: RecordingStatus) => void): void; + + /** Sets the interval with which onRecordingStatusUpdate is called while the recording can record. This value defaults to 500 milliseconds. */ + setProgressUpdateInterval(progressUpdateIntervalMillis: number): void; + + /** Loads the recorder into memory and prepares it for recording. This must be called before calling `startAsync()`. This method can only be called if the `Recording` instance has never yet been prepared. */ + prepareToRecordAsync( + /** Options for the recording, including sample rate, bitrate, channels, format, encoder, and extension. If no options are passed to `prepareToRecordAsync()`, the recorder will be created with options `Expo.Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY`. */ + options?: RecordingOptions + ): Promise; + + /** Begins recording. This method can only be called if the `Recording` has been prepared. */ + startAsync(): Promise; + + /** + * Pauses recording. This method can only be called if the Recording has been prepared. + * + * NOTE: This is only available on Android API version 24 and later. + */ + pauseAsync(): Promise; + + /** Stops the recording and deallocates the recorder from memory. This reverts the Recording instance to an unprepared state, and another Recording instance must be created in order to record again. This method can only be called if the `Recording` has been prepared. */ + stopAndUnloadAsync(): Promise; + + /** + * Gets the local URI of the Recording. Note that this will only succeed once the Recording is prepared to record. + * + * @returns A string with the local URI of the `Recording`, or `null` if the `Recording` is not prepared to record. + */ + getURI(): string | null | undefined; + + /** + * Creates and loads a new `Sound` object to play back the `Recording`. Note that this will only succeed once the `Recording` is done recording (once `stopAndUnloadAsync()` has been called). + * + * @returns A Promise that is rejected if creation failed, or fulfilled with the following dictionary if creation succeeded: + * - `sound`: the newly created and loaded Sound object. + * - `status`: the PlaybackStatus of the Sound object. + */ + createNewLoadedSound( + /** The initial intended `PlaybackStatusToSet` of the sound, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. */ + initialStatus?: PlaybackStatusToSet, + + /** A function taking a single parameter `PlaybackStatus`. This value defaults to `null` if no parameter is passed. */ + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } +} + +/** + * AuthSession + */ +export namespace AuthSession { + type StartAsyncResponse = { + type: 'cancel'; + } | { + type: 'dismissed'; + } | { + type: 'success'; + params: HashMap; + event: HashMap; + } | { + type: 'error'; + params: HashMap; + errorCode: string; + event: HashMap; + }; + + function startAsync(options: { authUrl: string; returnUrl?: string; }): Promise; + function dismiss(): void; + function getRedirectUrl(): string; +} + +// #region AV +/** + * AV + */ +export type PlaybackStatus = { + isLoaded: false; + androidImplementation?: string; + + /** Populated exactly once when an error forces the object to unload. */ + error?: string; +} | { + isLoaded: true; + androidImplementation?: string; + uri: string; + progressUpdateIntervalMillis: number; + durationMillis?: number; + positionMillis: number; + playableDurationMillis?: number; + shouldPlay: boolean; + isPlaying: boolean; + isBuffering: boolean; + rate: number; + shouldCorrectPitch: boolean; + volume: number; + isMuted: boolean; + isLooping: boolean; + + /** True exactly once when the track plays to finish. */ + didJustFinish: boolean; +}; + +export interface PlaybackStatusToSet { + androidImplementation?: string; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: FloatFromZeroToOne; + shouldCorrectPitch?: boolean; + volume?: FloatFromZeroToOne; + isMuted?: boolean; + isLooping?: boolean; +} + +export type PlaybackSource = RequireSource | { uri: string } | Asset; + +export class PlaybackObject { + /** + * Gets the `PlaybackStatus` of the `playbackObject`. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject`. + */ + getStatusAsync(): Promise; + + /** + * Loads the media from source into memory and prepares it for playing. This must be called before calling setStatusAsync() or any of the convenience set status methods. This method can only be called if the playbackObject is in an unloaded state. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once it is loaded, or rejects if loading failed. The `Promise` will also reject if the `playbackObject` was already loaded. See below for details on `PlaybackStatus`. + */ + loadAsync( + /** + * The source of the media. The following forms are supported: + * - A dictionary of the form `{ uri: 'http://path/to/file' }` with a network URL pointing to a media file on the web. + * - `require('path/to/file')` for a media file asset in the source code directory. + * - An `Expo.Asset object` for a media file asset. + */ + source: PlaybackSource, + + /** The initial intended `PlaybackStatusToSet` of the `playbackObject`, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. See below for details on `PlaybackStatusToSet` and the default initial playback status. */ + initialStatus?: PlaybackStatusToSet, + + /** If set to `true`, the system will attempt to download the resource to the device before loading. This value defaults to true. Note that at the moment, this will only work for sources of the form `require('path/to/file')` or `Expo.Asset` objects. */ + downloadFirst?: boolean + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: false })`. */ + pauseAsync(): Promise; + + /** + * This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: true })`. + * + * Playback may not start immediately after calling this function for reasons such as buffering. Make sure to update your UI based on the `isPlaying` and `isBuffering` properties of the `PlaybackStatus`. + */ + playAsync(): Promise; + + /** + * This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: true, positionMillis: millis })`. + * + * Playback may not start immediately after calling this function for reasons such as buffering. Make sure to update your UI based on the isPlaying and `isBuffering` properties of the `PlaybackStatus`. + */ + playFromPositionAsync( + /** The desired position of playback in milliseconds. */ + positionMillis: number, + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis, seekMillisToleranceBefore: toleranceMillisBefore, seekMillisToleranceAfter: toleranceMillisAfter })`. The tolerances are used only on iOS. */ + tolerances?: { + toleranceMillisBefore: number, + toleranceMillisAfter: number + } + ): Promise; + + /** + * Replays the item. When using `playFromPositionAsync(0)` the item is seeked to the position at `0` ms. On iOS this method uses internal implementation of the player and is able to play the item from the beginning immediately. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once the new status has been set successfully, or rejects if setting the new status failed. + */ + replayAsync( + /** The new `PlaybackStatusToSet` of the `playbackObject`, whose values will override the current playback status. */ + status: PlaybackStatusToSet + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ isLooping: value })`. */ + setIsLoopingAsync( + /** A boolean describing if the media should play once (`false`) or loop indefinitely (`true`). */ + isLooping: boolean + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ isMuted: value })`. */ + setIsMutedAsync( + /** A boolean describing if the audio of this media should be muted. */ + isMuted: boolean + ): Promise; + + /** + * Sets a function to be called regularly with the `PlaybackStatus` of the `playbackObject`. See below for details on `PlaybackStatus` and an example use case of this function. + * + * `onPlaybackStatusUpdate` will be called whenever a call to the API for this `playbackObject` completes (such as `setStatusAsync()`, `getStatusAsync()`, or `unloadAsync()`), and will also be called at regular intervals while the media is in the loaded state. Set `progressUpdateIntervalMillis` via `setStatusAsync()` or `setProgressUpdateIntervalAsync()` to modify the interval with which `onPlaybackStatusUpdate` is called while loaded. + */ + setOnPlaybackStatusUpdate( + /** A function taking a single parameter `PlaybackStatus`. */ + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void + ): void; + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis })`. */ + setPositionAsync( + positionMillis: number, + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis, seekMillisToleranceBefore: toleranceMillisBefore, seekMillisToleranceAfter: toleranceMillisAfter })`. The tolerances are used only on iOS. */ + tolerances?: { + toleranceMillisBefore: number, + toleranceMillisAfter: number + } + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ progressUpdateIntervalMillis: millis })`. */ + setProgressUpdateIntervalAsync( + /** The new minimum interval in milliseconds between calls of `onPlaybackStatusUpdate`. */ + progressUpdateIntervalMillis: number + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ rate: value, shouldCorrectPitch: shouldCorrectPitch })`. */ + setRateAsync( + /** The desired playback rate of the media. This value must be between `0.0` and `32.0`. Only available on Android API version 23 and later and iOS. */ + rate: number, + + /** A boolean describing if we should correct the pitch for a changed rate. If set to `true`, the pitch of the audio will be corrected (so a rate different than `1.0` will timestretch the audio). */ + shouldCorrectPitch: boolean + ): Promise; + + /** Sets a new `PlaybackStatusToSet` on the `playbackObject`. This method can only be called if the media has been loaded. Return a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once the new status has been set successfully, or rejects if setting the new status failed. */ + setStatusAsync( + /** The new `PlaybackStatusToSet` of the `playbackObject`, whose values will override the current playback status. */ + status: PlaybackStatusToSet + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ volume: value })`. */ + setVolumeAsync( + /** A number between `0.0` (silence) and `1.0` (maximum volume). */ + volume: number + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: false, positionMillis: 0 })`. */ + stopAsync(): Promise; + + /** + * Unloads the media from memory. `loadAsync()` must be called again in order to be able to play the media. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once it is unloaded, or rejects if unloading failed. See below for details on `PlaybackStatus`. + */ + unloadAsync(): Promise; +} +// #endregion + +// #region BarCodeScanner +/** + * BarCodeScanner + */ +export interface BarCodeScannerProps extends ViewProperties { + type?: 'front' | 'back'; + torchMode?: 'on' | 'off'; + barCodeTypes?: string[]; + onBarCodeRead?: BarCodeReadCallback; +} + +export class BarCodeScanner extends Component { + static Constants: { + TorchMode: { + on: string; + off: string + } + } & CameraConstants; +} +// #endregion + +// #region BlurView +/** + * BlurView + */ +export interface BlurViewProps extends ViewProperties { + tint: 'light' | 'default' | 'dark'; + intensity: number; +} +export class BlurView extends Component { } +// #endregion + +/** + * Brightness + */ +export namespace Brightness { + function setBrightnessAsync(brightnessValue: FloatFromZeroToOne): Promise; + function getBrightnessAsync(): Promise; + function getSystemBrightnessAsync(): Promise; + function setSystemBrightnessAsync(brightnessValue: FloatFromZeroToOne): Promise; +} + +// #region Camera +/** + * Camera + */ +export interface PictureOptions { + quality?: number; +} + +export interface PictureResponse { + uri: string; + width: number; + height: number; + exif: string; + base64: string; +} + +export interface RecordingOptions { + quality?: string | number; + maxDuration?: number; + maxFileSize?: number; +} + +export class CameraObject { + takePictureAsync(options: PictureOptions): Promise; + recordAsync(options: RecordingOptions): Promise<{ uri: string; }>; + stopRecording(): void; + getSupportedRatiosAsync(): Promise; // Android only +} + +export interface CameraProps extends ViewProperties { + flashMode?: string | number; + type?: string | number; + ratio?: string; + autoFocus?: string | number | boolean; + focusDepth?: FloatFromZeroToOne; + zoom?: FloatFromZeroToOne; + whiteBalance?: string | number; + barCodeTypes?: string[]; + onCameraReady?: () => void; + onMountError?: () => void; + onBarCodeRead?: BarCodeReadCallback; + ref?: Ref; +} + +export interface CameraConstants { + readonly Type: string; + readonly FlashMode: string; + readonly AutoFocus: string; + readonly WhiteBalance: string; + readonly VideoQuality: string; + readonly BarCodeType: { + aztec: string; + codabar: string; + code39: string; + code93: string; + code128: string; + code138: string; + code39mod43: string; + datamatrix: string; + ean13: string; + ean8: string; + interleaved2of5: string; + itf14: string; + maxicode: string; + pdf417: string; + rss14: string; + rssexpanded: string; + upc_a: string; + upc_e: string; + upc_ean: string; + qr: string; + }; +} + +export class Camera extends Component { + static readonly Constants: CameraConstants; +} +// #endregion + +/** + * Constants + */ +export namespace Constants { + const appOwnership: 'expo' | 'standalone' | 'guest'; + const expoVersion: string; + const deviceId: string; + const deviceName: string; + const deviceYearClass: number; + const isDevice: boolean; + + interface Platform { + ios: { + platform: string; + model: string; + userInterfaceIdiom: string; + }; + } + const platform: Platform; + const sessionId: string; + const statusBarHeight: number; + const systemFonts: string[]; + + interface Manifest { + name: string; + description?: string; + slug?: string; + sdkVersion?: string; + version?: string; + orientation?: Orientation; + primaryColor?: string; + privacy?: 'public' | 'unlisted'; + scheme?: string; + icon?: string; + platforms?: string[]; + githubUrl?: string; + notification?: { + icon?: string, + color?: string, + androidMode?: 'default' | 'collapse', + androidCollapsedTitle?: string + }; + loading?: { + icon?: string, + exponentIconColor?: 'white' | 'blue', + exponentIconGrayscale?: 1 | 0, + backgroundImage?: string, + backgroundColor?: string, + hideExponentText?: boolean + }; + appKey?: string; + androidStatusBar?: { + barStyle?: 'lignt-content' | 'dark-content', + backgroundColor?: string + }; + androidShowExponentNotificationInShellApp?: boolean; + extra?: { + [propName: string]: any + }; + rnCliPath?: any; + entryPoint?: string; + packagerOpts?: { + hostType?: string, + dev?: boolean, + strict?: boolean, + minify?: boolean, + urlType?: string, + urlRandomness?: string, + lanType?: string, + [propName: string]: any + }; + ignoreNodeModulesValidation?: any; + nodeModulesPath?: string; + ios?: { + bundleIdentifier?: string, + buildNumber?: string, + config?: { + usesNonExemptEncryption?: boolean, + googleSignIn?: { + reservedClientId: string + } + }, + supportsTablet?: boolean, + infoPlist?: any + }; + android?: { + package?: string, + versionCode?: string, + config?: { + fabric?: { + apiKey: string, + buildSecret: string + }, + googleMaps?: { + apiKey: string + }, + googleSignIn?: { + apiKey: string, + certificateHash: string + } + } + }; + facebookScheme?: any; + facebookAppId?: string; + facebookDisplayName?: string; + splash?: { + backgroundColor?: string; + resizeMode?: ResizeModeContain | ResizeModeCover; + image?: string; + }; + assetBundlePatterns?: string[]; + releaseChannel: string; + [propName: string]: any; + } + const manifest: Manifest; + const linkingUri: string; +} + +/** + * Contacts + */ +export namespace Contacts { + type PhoneNumbers = 'phoneNumbers'; + type Emails = 'emails'; + type Addresses = 'addresses'; + type Image = 'image'; + type Thumbnail = 'thumbnail'; + type Note = 'note'; + type Birthday = 'birthday'; + type NonGregorianBirthday = 'nonGregorianBirthday'; + type NamePrefix = 'namePrefix'; + type NameSuffix = 'nameSuffix'; + type PhoneticFirstName = 'phoneticFirstName'; + type PhoneticMiddleName = 'phoneticMiddleName'; + type PhoneticLastName = 'phoneticLastName'; + type SocialProfiles = 'socialProfiles'; + type InstantMessageAddresses = 'instantMessageAddresses'; + type UrlAddresses = 'urlAddresses'; + type Dates = 'dates'; + type Relationships = 'relationships'; + + const PHONE_NUMBERS: PhoneNumbers; + const EMAILS: Emails; + const ADDRESSES: Addresses; + const IMAGE: Image; + const THUMBNAIL: Thumbnail; + const NOTE: Note; + const BIRTHDAY: Birthday; + const NON_GREGORIAN_BIRTHDAY: NonGregorianBirthday; + const NAME_PREFIX: NamePrefix; + const NAME_SUFFIX: NameSuffix; + const PHONETIC_FIRST_NAME: PhoneticFirstName; + const PHONETIC_MIDDLE_NAME: PhoneticMiddleName; + const PHONETIC_LAST_NAME: PhoneticLastName; + const SOCIAL_PROFILES: SocialProfiles; + const IM_ADDRESSES: InstantMessageAddresses; + const URLS: UrlAddresses; + const DATES: Dates; + const RELATIONSHIPS: Relationships; + + type FieldType = PhoneNumbers | Emails | Addresses | Image | Thumbnail | + Note | Birthday | NonGregorianBirthday | NamePrefix | NameSuffix | + PhoneticFirstName | PhoneticMiddleName | PhoneticLastName | SocialProfiles | + InstantMessageAddresses | UrlAddresses | Dates | Relationships; + + interface Options { + pageSize?: number; + pageOffset?: number; + fields?: FieldType[]; + } + + interface Contact { + id: string; + contactType: string; + name: string; + firstName?: string; + middleName?: string; + lastName?: string; + previousLastName?: string; + namePrefix?: string; + nameSuffix?: string; + nickname?: string; + phoneticFirstName?: string; + phoneticMiddleName?: string; + phoneticLastName?: string; + emails?: Array<{ + email?: string; + primary?: boolean; + label: string; + id: string; + }>; + phoneNumbers?: Array<{ + number?: string; + primary?: boolean; + digits?: string; + countryCode?: string; + label: string; + id: string; + }>; + addresses?: Array<{ + street?: string; + city?: string; + country?: string; + region?: string; + neighborhood?: string; + postalCode?: string; + poBox?: string; + isoCountryCode?: string; + label: string; + id: string; + }>; + socialProfiles?: Array<{ + service?: string; + localizedProfile?: string; + url?: string; + username?: string; + userId?: string; + label: string; + id: string; + }>; + instantMessageAddresses?: Array<{ + service?: string; + username?: string; + localizedService?: string; + label: string; + id: string; + }>; + urls?: { + label: string; + url?: string; + id: string; + }; + company?: string; + jobTitle?: string; + department?: string; + imageAvailable?: boolean; + image?: { + uri?: string; + }; + thumbnail?: { + uri?: string; + }; + note?: string; + dates?: Array<{ + day?: number; + month?: number; + year?: number; + id: string; + label: string; + }>; + relationships?: Array<{ + label: string; + name?: string; + id: string; + }>; + } + + interface Response { + data: Contact[]; + total: number; + hasNextPage: boolean; + hasPreviousPage: boolean; + } + + function getContactsAsync(options: Options): Promise; + function getContactByIdAsync(options: { id?: string; fields?: FieldType[] }): Promise; +} + +/** + * DocumentPicker + */ +export namespace DocumentPicker { + interface Options { + type?: string; + } + + type Response = { + type: 'success'; + uri: string; + name: string; + size: number; + } | { + type: 'cancel'; + }; + + function getDocumentAsync(options?: Options): Promise; +} + +/** + * ErrorRecovery + */ +export namespace ErrorRecovery { + function setRecoveryProps(props: HashMap): void; +} + +/** + * Facebook + */ +export namespace Facebook { + interface Options { + permissions?: string[]; + behavior?: 'web' | 'native' | 'browser' | 'system'; + } + interface Response { + type: 'cancel' | 'success'; + token?: string; + expires?: number; + } + function logInWithReadPermissionsAsync(appId: string, options?: Options): Promise; +} + +/** + * Facebook Ads + */ +export namespace FacebookAds { + /** + * Interstitial Ads + */ + namespace InterstitialAdManager { + function showAd(placementId: string): Promise; + } + + /** + * Native Ads + */ + type MediaCachePolicy = 'none' | 'icon' | 'image' | 'all'; + class NativeAdsManager { + constructor(placementId: string, numberOfAdsToRequest?: number); + disableAutoRefresh(): void; + setMediaCachePolicy(cachePolicy: MediaCachePolicy): void; + } + + function withNativeAd(component: Component<{ + icon?: string; + coverImage?: string; + title?: string; + subtitle?: string; + description?: string; + callToActionText?: string; + socialContext?: string; + }>): Component<{ adsManager: NativeAdsManager }, { ad: any, canRequestAds: boolean }>; + + /** + * Banner View + */ + type AdType = 'large' | 'rectangle' | 'standard'; + + interface BannerViewProps { + type: AdType; + placementId: string; + onPress: () => void; + onError: () => void; + } + + class BannerView extends Component { } + + /** + * Ad Settings + */ + namespace AdSettings { + const currentDeviceHash: string; + function addTestDevice(device: string): void; + function clearTestDevices(): void; + type SDKLogLevel = 'none' | 'debug' | 'verbose' | 'warning' | 'error' | 'notification'; + function setLogLevel(logLevel: SDKLogLevel): void; + function setIsChildDirected(isDirected: boolean): void; + function setMediationService(mediationService: string): void; + function setUrlPrefix(urlPrefix: string): void; + } +} + +/** + * FaceDetector + */ +export namespace FaceDetector { + interface Point { + x: Axis; + y: Axis; + } + interface FaceFeature { + bounds: { + size: { + width: number; + height: number; + }, + origin: Point; + }; + smilingProbability?: number; + leftEarPosition?: Point; + rightEarPosition?: Point; + leftEyePosition?: Point; + leftEyeOpenProbability?: number; + rightEyePosition?: Point; + rightEyeOpenProbability?: number; + leftCheekPosition?: Point; + rightCheekPosition?: Point; + leftMouthPosition?: Point; + mouthPosition?: Point; + rightMouthPosition?: Point; + bottomMouthPosition?: Point; + noseBasePosition?: Point; + yawAngle?: number; + rollAngle?: number; + } + interface DetectFaceResult { + faces: FaceFeature[]; + image: { + uri: string; + width: number; + height: number; + orientation: number; + }; + } + interface Mode { + fast: 'fast'; + accurate: 'accurate'; + } + interface _Shared { + all: 'all'; + none: 'none'; + } + type Landmarks = _Shared; + type Classifications = _Shared; + interface _Constants { + Mode: Mode; + Landmarks: Landmarks; + Classifications: Classifications; + } + + const Constants: _Constants; + + interface DetectionOptions { + mode?: keyof Mode; + detectLandmarks?: keyof Landmarks; + runClassifications?: keyof Classifications; + } + + function detectFaces(uri: string, options?: DetectionOptions): Promise; +} + +/** + * FileSystem + */ +export namespace FileSystem { + type FileInfo = { + exists: true; + isDirectory: boolean; + uri: string; + size: number; + modificationTime: number; + md5?: Md5; + } | { + exists: false; + isDirectory: false; + }; + + interface DownloadResult { + uri: string; + status: number; + headers: { [name: string]: string }; + md5?: Md5; + } + + const documentDirectory: string; + const cacheDirectory: string; + + function getInfoAsync(fileUri: string, options?: { md5?: string, size?: boolean; }): Promise; + function readAsStringAsync(fileUri: string): Promise; + function writeAsStringAsync(fileUri: string, contents: string): Promise; + function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise; + function moveAsync(options: { from: string, to: string; }): Promise; + function copyAsync(options: { from: string, to: string; }): Promise; + function makeDirectoryAsync(dirUri: string, options?: { intermediates: boolean }): Promise; + function readDirectoryAsync(dirUri: string): Promise; + function downloadAsync(uri: string, fileUri: string, options?: { md5?: boolean; }): Promise; + function createDownloadResumable( + uri: string, + fileUri: string, + options?: DownloadOptions, + callback?: (totalBytesWritten: number, totalBytesExpectedToWrite: number) => void, + resumeData?: string | null + ): DownloadResumable; + + interface PauseResult { + url: string; + fileUri: string; + options: { md5: boolean; }; + resumeData: string; + } + + interface DownloadOptions { + md5?: boolean; + headers?: { [name: string]: string }; + } + + interface DownloadProgressData { + totalBytesWritten: number; + totalBytesExpectedToWrite: number; + } + + type DownloadProgressCallback = (data: DownloadProgressData) => void; + + class DownloadResumable { + constructor( + url: string, + fileUri: string, + options: DownloadOptions, + callback?: DownloadProgressCallback, + resumeData?: string + ); + + downloadAsync(): Promise; + pauseAsync(): Promise; + resumeAsync(): Promise; + savable(): PauseResult; + } +} + +/** Use TouchID/FaceID (iOS) or the Fingerprint API (Android) to authenticate the user with a fingerprint scan. */ +export namespace Fingerprint { + type FingerprintAuthenticationResult = { + success: true + } | { + success: false, + + /** Error code in the case where authentication fails. */ + error: string + }; + + /** Determine whether the Fingerprint scanner is available on the device. */ + function hasHardwareAsync(): Promise; + + /** Determine whether the device has saved fingerprints to use for authentication. */ + function isEnrolledAsync(): Promise; + + /** + * Attempts to authenticate via Fingerprint. Android: When using the fingerprint module on Android, you need to provide a UI component to prompt the user to scan their fingerprint, as the OS has no default alert for it. + * + * @param promptMessage A message that is shown alongside the TouchID/FaceID prompt. (iOS only) + */ + function authenticateAsync(promptMessageIOS?: string): Promise; + + /** Cancels the fingerprint authentication flow. (Android only) */ + function cancelAuthenticate(): void; +} + +/** + * Font + */ +export namespace Font { + interface FontMap { + [name: string]: RequireSource; + } + + function loadAsync(name: string, url: string): Promise; + function loadAsync(map: FontMap): Promise; +} + +// #region GLView +/** + * GLView + */ +export interface GLViewProps extends ViewProperties { + onContextCreate(): void; + msaaSamples: number; +} + +export class GLView extends Component { } +// #endregion + +/** + * Google + */ +export namespace Google { + interface LogInConfig { + androidClientId?: string; + androidStandaloneAppClientId?: string; + iosClientId?: string; + iosStandaloneAppClientId?: string; + webClientId?: string; + behavior?: 'system' | 'web'; + scopes?: string[]; + } + + type LogInResult = { + type: 'cancel'; + } | { + type: 'success'; + accessToken: string; + idToken?: string; + refreshToken?: string; + serverAuthCode?: string; + user: { + id: string; + name: string; + givenName: string; + familyName: string; + photoUrl?: string; + email?: string; + } + }; + + function logInAsync(config: LogInConfig): Promise; +} + +/** Access the device gyroscope sensor to respond to changes in rotation in 3d space. */ +export namespace Gyroscope { + interface GyroscopeObject { + x: Axis; + y: Axis; + z: Axis; + } + + /** A callback that is invoked when an gyroscope update is available. */ + function addListener(listener: (obj: GyroscopeObject) => any): EventSubscription; + + /** Remove all listeners. */ + function removeAllListeners(): void; + + /** Subscribe for updates to the gyroscope. */ + function setUpdateInterval(intervalMs: number): void; +} + +/** + * ImageManipulator + */ +export namespace ImageManipulator { + interface ImageResult { + uri: string; + width: number; + height: number; + base64?: string; + } + + interface SaveOptions { + base64?: boolean; + compress?: FloatFromZeroToOne; + format?: 'jpeg' | 'png'; + } + + interface CropParameters { + originX: number; + originY: number; + width: number; + height: number; + } + + interface ImageManipulationOptions { + resize?: { width?: number; height?: number }; + rotate?: number; + flip?: { vertical?: boolean; horizontal?: boolean }; + crop?: CropParameters; + } + + function manipulate(uri: string, actions: ImageManipulationOptions, saveOptions?: SaveOptions): Promise; +} + +/** + * Image Picker + */ +export namespace ImagePicker { + interface ImageInfo { + uri: string; + width: number; + height: number; + } + + type ImageResult = { cancelled: true } | ({ cancelled: false } & ImageInfo); + + interface _MediaTypeOptions { + All: 'All'; + Videos: 'Videos'; + Images: 'Images'; + } + + const MediaTypeOptions: _MediaTypeOptions; + + interface ImageLibraryOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + mediaTypes?: keyof _MediaTypeOptions; + } + + function launchImageLibraryAsync(options?: ImageLibraryOptions): Promise; + + interface CameraOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + } + + function launchCameraAsync(options?: CameraOptions): Promise; +} + +/** + * IntentLauncherAndroid + */ +export namespace IntentLauncherAndroid { + const ACTION_ACCESSIBILITY_SETTINGS: 'android.settings.ACCESSIBILITY_SETTINGS'; + const ACTION_APP_NOTIFICATION_REDACTION: 'android.settings.ACTION_APP_NOTIFICATION_REDACTION'; + const ACTION_CONDITION_PROVIDER_SETTINGS: 'android.settings.ACTION_CONDITION_PROVIDER_SETTINGS'; + const ACTION_NOTIFICATION_LISTENER_SETTINGS: 'android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS'; + const ACTION_PRINT_SETTINGS: 'android.settings.ACTION_PRINT_SETTINGS'; + const ACTION_ADD_ACCOUNT_SETTINGS: 'android.settings.ADD_ACCOUNT_SETTINGS'; + const ACTION_AIRPLANE_MODE_SETTINGS: 'android.settings.AIRPLANE_MODE_SETTINGS'; + const ACTION_APN_SETTINGS: 'android.settings.APN_SETTINGS'; + const ACTION_APPLICATION_DETAILS_SETTINGS: 'android.settings.APPLICATION_DETAILS_SETTINGS'; + const ACTION_APPLICATION_DEVELOPMENT_SETTINGS: 'android.settings.APPLICATION_DEVELOPMENT_SETTINGS'; + const ACTION_APPLICATION_SETTINGS: 'android.settings.APPLICATION_SETTINGS'; + const ACTION_APP_NOTIFICATION_SETTINGS: 'android.settings.APP_NOTIFICATION_SETTINGS'; + const ACTION_APP_OPS_SETTINGS: 'android.settings.APP_OPS_SETTINGS'; + const ACTION_BATTERY_SAVER_SETTINGS: 'android.settings.BATTERY_SAVER_SETTINGS'; + const ACTION_BLUETOOTH_SETTINGS: 'android.settings.BLUETOOTH_SETTINGS'; + const ACTION_CAPTIONING_SETTINGS: 'android.settings.CAPTIONING_SETTINGS'; + const ACTION_CAST_SETTINGS: 'android.settings.CAST_SETTINGS'; + const ACTION_DATA_ROAMING_SETTINGS: 'android.settings.DATA_ROAMING_SETTINGS'; + const ACTION_DATE_SETTINGS: 'android.settings.DATE_SETTINGS'; + const ACTION_DEVICE_INFO_SETTINGS: 'android.settings.DEVICE_INFO_SETTINGS'; + const ACTION_DEVICE_NAME: 'android.settings.DEVICE_NAME'; + const ACTION_DISPLAY_SETTINGS: 'android.settings.DISPLAY_SETTINGS'; + const ACTION_DREAM_SETTINGS: 'android.settings.DREAM_SETTINGS'; + const ACTION_HARD_KEYBOARD_SETTINGS: 'android.settings.HARD_KEYBOARD_SETTINGS'; + const ACTION_HOME_SETTINGS: 'android.settings.HOME_SETTINGS'; + const ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS: 'android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS'; + const ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS: 'android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS'; + const ACTION_INPUT_METHOD_SETTINGS: 'android.settings.INPUT_METHOD_SETTINGS'; + const ACTION_INPUT_METHOD_SUBTYPE_SETTINGS: 'android.settings.INPUT_METHOD_SUBTYPE_SETTINGS'; + const ACTION_INTERNAL_STORAGE_SETTINGS: 'android.settings.INTERNAL_STORAGE_SETTINGS'; + const ACTION_LOCALE_SETTINGS: 'android.settings.LOCALE_SETTINGS'; + const ACTION_LOCATION_SOURCE_SETTINGS: 'android.settings.LOCATION_SOURCE_SETTINGS'; + const ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS: 'android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS'; + const ACTION_MANAGE_APPLICATIONS_SETTINGS: 'android.settings.MANAGE_APPLICATIONS_SETTINGS'; + const ACTION_MANAGE_DEFAULT_APPS_SETTINGS: 'android.settings.MANAGE_DEFAULT_APPS_SETTINGS'; + const ACTION_MEMORY_CARD_SETTINGS: 'android.settings.MEMORY_CARD_SETTINGS'; + const ACTION_MONITORING_CERT_INFO: 'android.settings.MONITORING_CERT_INFO'; + const ACTION_NETWORK_OPERATOR_SETTINGS: 'android.settings.NETWORK_OPERATOR_SETTINGS'; + const ACTION_NFCSHARING_SETTINGS: 'android.settings.NFCSHARING_SETTINGS'; + const ACTION_NFC_PAYMENT_SETTINGS: 'android.settings.NFC_PAYMENT_SETTINGS'; + const ACTION_NFC_SETTINGS: 'android.settings.NFC_SETTINGS'; + const ACTION_NIGHT_DISPLAY_SETTINGS: 'android.settings.NIGHT_DISPLAY_SETTINGS'; + const ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS: 'android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS'; + const ACTION_NOTIFICATION_SETTINGS: 'android.settings.NOTIFICATION_SETTINGS'; + const ACTION_PAIRING_SETTINGS: 'android.settings.PAIRING_SETTINGS'; + const ACTION_PRIVACY_SETTINGS: 'android.settings.PRIVACY_SETTINGS'; + const ACTION_QUICK_LAUNCH_SETTINGS: 'android.settings.QUICK_LAUNCH_SETTINGS'; + const ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS: 'android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS'; + const ACTION_SECURITY_SETTINGS: 'android.settings.SECURITY_SETTINGS'; + const ACTION_SETTINGS: 'android.settings.SETTINGS'; + const ACTION_SHOW_ADMIN_SUPPORT_DETAILS: 'android.settings.SHOW_ADMIN_SUPPORT_DETAILS'; + const ACTION_SHOW_INPUT_METHOD_PICKER: 'android.settings.SHOW_INPUT_METHOD_PICKER'; + const ACTION_SHOW_REGULATORY_INFO: 'android.settings.SHOW_REGULATORY_INFO'; + const ACTION_SHOW_REMOTE_BUGREPORT_DIALOG: 'android.settings.SHOW_REMOTE_BUGREPORT_DIALOG'; + const ACTION_SOUND_SETTINGS: 'android.settings.SOUND_SETTINGS'; + const ACTION_STORAGE_MANAGER_SETTINGS: 'android.settings.STORAGE_MANAGER_SETTINGS'; + const ACTION_SYNC_SETTINGS: 'android.settings.SYNC_SETTINGS'; + const ACTION_SYSTEM_UPDATE_SETTINGS: 'android.settings.SYSTEM_UPDATE_SETTINGS'; + const ACTION_TETHER_PROVISIONING_UI: 'android.settings.TETHER_PROVISIONING_UI'; + const ACTION_TRUSTED_CREDENTIALS_USER: 'android.settings.TRUSTED_CREDENTIALS_USER'; + const ACTION_USAGE_ACCESS_SETTINGS: 'android.settings.USAGE_ACCESS_SETTINGS'; + const ACTION_USER_DICTIONARY_INSERT: 'android.settings.USER_DICTIONARY_INSERT'; + const ACTION_USER_DICTIONARY_SETTINGS: 'android.settings.USER_DICTIONARY_SETTINGS'; + const ACTION_USER_SETTINGS: 'android.settings.USER_SETTINGS'; + const ACTION_VOICE_CONTROL_AIRPLANE_MODE: 'android.settings.VOICE_CONTROL_AIRPLANE_MODE'; + const ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE: 'android.settings.VOICE_CONTROL_BATTERY_SAVER_MODE'; + const ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE: 'android.settings.VOICE_CONTROL_DO_NOT_DISTURB_MODE'; + const ACTION_VOICE_INPUT_SETTINGS: 'android.settings.VOICE_INPUT_SETTINGS'; + const ACTION_VPN_SETTINGS: 'android.settings.VPN_SETTINGS'; + const ACTION_VR_LISTENER_SETTINGS: 'android.settings.VR_LISTENER_SETTINGS'; + const ACTION_WEBVIEW_SETTINGS: 'android.settings.WEBVIEW_SETTINGS'; + const ACTION_WIFI_IP_SETTINGS: 'android.settings.WIFI_IP_SETTINGS'; + const ACTION_WIFI_SETTINGS: 'android.settings.WIFI_SETTINGS'; + const ACTION_WIRELESS_SETTINGS: 'android.settings.WIRELESS_SETTINGS'; + const ACTION_ZEN_MODE_AUTOMATION_SETTINGS: 'android.settings.ZEN_MODE_AUTOMATION_SETTINGS'; + const ACTION_ZEN_MODE_EVENT_RULE_SETTINGS: 'android.settings.ZEN_MODE_EVENT_RULE_SETTINGS'; + const ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS: 'android.settings.ZEN_MODE_EXTERNAL_RULE_SETTINGS'; + const ACTION_ZEN_MODE_PRIORITY_SETTINGS: 'android.settings.ZEN_MODE_PRIORITY_SETTINGS'; + const ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS: 'android.settings.ZEN_MODE_SCHEDULE_RULE_SETTINGS'; + const ACTION_ZEN_MODE_SETTINGS: 'android.settings.ZEN_MODE_SETTINGS'; + + function startActivityAsync(activity: string, data?: HashMap): Promise; +} + +/** + * KeepAwake + */ +export class KeepAwake extends Component { + static activate(): void; + static deactivate(): void; +} + +// #region LinearGradient +/** + * LinearGradient + */ +export interface LinearGradientProps extends ViewProperties { + colors: string[]; + start?: [number, number]; + end?: [number, number]; + locations?: number[]; +} + +export class LinearGradient extends Component { } +// #endregion + +/** + * Location + */ +export namespace Location { + interface LocationOptions { + enableHighAccuracy?: boolean; + timeInterval?: number; + distanceInterval?: number; + } + + interface LocationProps { + latitude: number; + longitude: number; + } + + interface Coords extends LocationProps { + altitude: number; + accuracy: number; + } + + interface LocationData { + coords: { + heading: number; + speed: number + } & Coords; + timestamp: number; + } + + interface ProviderStatus { + locationServicesEnabled: boolean; + gpsAvailable?: boolean; + networkAvailable?: boolean; + passiveAvailable?: boolean; + } + + interface HeadingStatus { + magHeading: number; + trueHeading: number; + accuracy: number; + } + + interface GeocodeData { + city: string; + street: string; + region: string; + postalCode: string; + country: string; + name: string; + } + + type LocationCallback = (data: LocationData) => void; + + function getCurrentPositionAsync(options: LocationOptions): Promise; + function watchPositionAsync(options: LocationOptions, callback: LocationCallback): EventSubscription; + function getProviderStatusAsync(): Promise; + function getHeadingAsync(): Promise; + function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; + function geocodeAsync(address: string): Promise; + function reverseGeocodeAsync(location: LocationProps): Promise; + function setApiKey(key: string): void; +} + +/** + * Magnetometer + */ +export namespace Magnetometer { + interface MagnetometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: MagnetometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Notifications + */ +export namespace Notifications { + interface Notification { + origin: 'selected' | 'received'; + data: any; + remote: boolean; + isMultiple: boolean; + } + + interface LocalNotification { + title: string; + body?: string; + data?: any; + ios?: { + sound?: boolean + }; + android?: { + sound?: boolean; + icon?: string; + color?: string; + priority?: 'min' | 'low' | 'high' | 'max'; + sticky?: boolean; + vibrate?: boolean | number[]; + link?: string; + }; + } + + type LocalNotificationId = string | number; + + function addListener(listener: (notification: Notification) => any): EventSubscription; + function getExpoPushTokenAsync(): Promise; + function presentLocalNotificationAsync(localNotification: LocalNotification): Promise; + function scheduleLocalNotificationAsync( + localNotification: LocalNotification, + schedulingOptions: { time: Date | number, repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' } + ): Promise; + function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function dismissAllNotificationsAsync(): Promise; + function cancelScheduledNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function cancelAllScheduledNotificationsAsync(): Promise; + function getBadgeNumberAsync(): Promise; + function setBadgeNumberAsync(number: number): Promise; +} + +/** + * Pedometer + */ +export namespace Pedometer { + function isAvailableAsync(): Promise; + function getStepCountAsync(start: Date, end: Date): Promise<{ steps: number; }>; + function watchStepCount(callback: (params: { steps: number; }) => void): EventSubscription; +} + +/** + * Permissions + */ +export namespace Permissions { + type PermissionType = 'remoteNotifications' | 'location' | + 'camera' | 'contacts' | 'audioRecording'; + type PermissionStatus = 'undetermined' | 'granted' | 'denied'; + type PermissionExpires = 'never'; + + interface PermissionDetailsLocationIOS { + scope: 'whenInUse' | 'always'; + } + + interface PermissionDetailsLocationAndroid { + scope: 'fine' | 'coarse' | 'none'; + } + + interface PermissionResponse { + status: PermissionStatus; + expires: PermissionExpires; + ios?: PermissionDetailsLocationIOS; + android?: PermissionDetailsLocationAndroid; + } + + function getAsync(type: PermissionType): Promise; + function askAsync(type: PermissionType): Promise; + + type RemoteNotificationPermission = 'remoteNotifications'; + + const CAMERA: 'camera'; + const CAMERA_ROLL: 'cameraRoll'; + const AUDIO_RECORDING: 'audioRecording'; + const LOCATION: 'location'; + const REMOTE_NOTIFICATIONS: RemoteNotificationPermission; + const NOTIFICATIONS: RemoteNotificationPermission; + const CONTACTS: 'contacts'; + const SYSTEM_BRIGHTNESS: 'systemBrightness'; +} + +/** + * Register Root Component + */ +export function registerRootComponent(component: ComponentType): void; + +/** + * ScreenOrientation + */ +export namespace ScreenOrientation { + interface Orientations { + ALL: 'ALL'; + ALL_BUT_UPSIDE_DOWN: 'ALL_BUT_UPSIDE_DOWN'; + PORTRAIT: 'PORTRAIT'; + PORTRAIT_UP: 'PORTRAIT_UP'; + PORTRAIT_DOWN: 'PORTRAIT_DOWN'; + LANDSCAPE: 'LANDSCAPE'; + LANDSCAPE_LEFT: 'LANDSCAPE_LEFT'; + LANDSCAPE_RIGHT: 'LANDSCAPE_RIGHT'; + } + + const Orientation: Orientations; + + function allow(orientation: keyof Orientations): void; +} + +/** + * SecureStore + */ +export namespace SecureStore { + interface SecureStoreOptions { + keychainService?: string; + keychainAccessible?: number; + } + + function setItemAsync(key: string, value: string, options?: SecureStoreOptions): Promise; + function getItemAsync(key: string, options?: SecureStoreOptions): Promise; + function deleteItemAsync(key: string, options?: SecureStoreOptions): Promise; +} + +/** + * Segment + */ +export namespace Segment { + function initialize(keys: { + androidWriteKey: string; + iosWriteKey: string; + }): void; + function identify(userId: string): void; + function identifyWithTraits(userId: string, traits: object): void; + function track(event: string): void; + function reset(): void; + function trackWithProperties(event: string, properties: object): void; + function screen(screenName: string): void; + function screenWithProperties(screenName: string, properties: object): void; + function flush(): void; +} + +/** + * Speech + */ +export namespace Speech { + interface SpeechOptions { + language?: string; + pitch?: number; + rate?: number; + onStart?: () => void; + onStopped?: () => void; + onDone?: () => void; + onError?: (error: string) => void; + } + + function speak(text: string, options?: SpeechOptions): void; + function stop(): void; + function isSpeakingAsync(): Promise; +} + +/** + * SQLite + */ +export namespace SQLite { + type Error = any; + + interface Database { + transaction( + callback: (transaction: Transaction) => any, + error?: (error: Error) => any, // TODO def of error + success?: () => any + ): void; + } + + interface Transaction { + executeSql( + sqlStatement: string, + arguments?: string[] | number[], + success?: (transaction: Transaction, resultSet: ResultSet) => any, + error?: (transaction: Transaction, error: Error) => any + ): void; + } + + interface ResultSet { + insertId: number; + rowAffected: number; + rows: { + length: number; + item: (index: number) => any; + _array: HashMap[]; + }; + } + + function openDatabase( + name: string | { + name: string, + version?: string, + description?: string, + size?: number, + callback?: () => any + }, + version?: string, + description?: string, + size?: number, + callback?: () => any + ): any; +} + +// #region Svg +/** + * Svg + */ +export interface SvgCommonProps { + fill?: string; + fillOpacity?: number | string; + stroke?: string; + strokeWidth?: number | string; + strokeOpacity?: number | string; + strokeLinecap?: string; + strokeLineJoin?: string; + strokeDasharray?: any[]; + strokeDashoffset?: any; + x?: number | string; + y?: number | string; + rotate?: number | string; + scale?: number | string; + origin?: number | string; + originX?: number | string; + originY?: number | string; + id?: string; + disabled?: boolean; + onPress?: () => any; + onPressIn?: () => any; + onPressOut?: () => any; + onLongPress?: () => any; + delayPressIn?: number; + delayPressOut?: number; + delayLongPress?: number; +} + +export interface SvgRectProps extends SvgCommonProps { + width: number | string; + height: number | string; +} + +export interface SvgCircleProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + r: number | string; +} + +export interface SvgEllipseProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + rx: number | string; + ry: number | string; +} + +export interface SvgLineProps extends SvgCommonProps { + x1: number | string; + y1: number | string; + x2: number | string; + y2: number | string; +} + +export interface SvgPolyProps extends SvgCommonProps { + points: string; +} + +export interface SvgPathProps extends SvgCommonProps { + d: string; +} + +export interface SvgTextProps extends SvgCommonProps { + textAnchor?: string; + fontSize?: number | string; + fontWeight?: string; +} + +export interface SvgTSpanProps extends SvgTextProps { + dx?: string; + dy?: string; +} + +export interface SvgTextPathProps extends SvgCommonProps { + href?: string; + startOffset?: string; +} + +export interface SvgUseProps extends SvgCommonProps { + href: string; + x: number | string; + y: number | string; +} + +export interface SvgSymbolProps extends SvgCommonProps { + viewBox: string; + width: number | string; + height: number | string; +} + +export interface SvgLinearGradientProps extends SvgCommonProps { + x1: number | string; + x2: number | string; + y1: number | string; + y2: number | string; +} + +export interface SvgRadialGradientProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + rx: number | string; + ry: number | string; + fx: number | string; + fy: number | string; + gradientUnits?: string; +} + +export interface SvgStopProps extends SvgCommonProps { + offset?: string; + stopColor?: string; + stopOpacity?: string; +} + +export class Svg extends Component<{ width: number, height: number }> { + static Circle: ComponentClass; + static ClipPath: ComponentClass; + static Defs: ComponentClass; + static Ellipse: ComponentClass; + static G: ComponentClass; + static Line: ComponentClass; + static LinearGradient: ComponentClass; + static Path: ComponentClass; + static Polygon: ComponentClass; + static Polyline: ComponentClass; + static RadialGradient: ComponentClass; + static Rect: ComponentClass; + static Stop: ComponentClass; + static Symbol: ComponentClass; + static Text: ComponentClass; + static TextPath: ComponentClass; + static TSpan: ComponentClass; + static Use: ComponentClass; +} +// #endregion + +/** + * Take Snapshot + */ +export function takeSnapshotAsync( + view?: (number | React.ReactElement), + options?: { + width?: number, + height?: number, + format?: 'png' | 'jpg' | 'jpeg' | 'webm', + quality?: number, + result?: 'file' | 'base64' | 'data-uri', + } +): Promise; + +/** Helpful utility functions that don’t fit anywhere else, including some localization and internationalization methods. */ +export namespace Util { + /** Returns the current device country code. */ + function getCurrentDeviceCountryAsync(): Promise; + + /** Returns the current device locale as a string. */ + function getCurrentLocaleAsync(): Promise; + + /** Returns the current device time zone name. */ + function getCurrentTimeZoneAsync(): Promise; + + /** Reloads the current experience. This will fetch and load the newest available JavaScript supported by the device’s Expo environment. This is useful for triggering an update of your experience if you have published a new version. */ + function reload(): void; + + /** _Android only_. Invokes a callback when a new version of your app is successfully downloaded in the background. */ + function addNewVersionListenerExperimental(listener: (event: { + manifest: object; + }) => void): { remove(): void; }; +} + +// #region Video +/** + * Expo Video + */ +export interface NaturalSize { + width: number; + height: number; + orientation: Orientation; +} + +export interface ReadyForDisplayEvent { + naturalSize: NaturalSize; + status: PlaybackStatus; +} + +export enum FullscreenUpdateVariants { + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT = 0, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT = 1, + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS = 2, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS = 3 +} + +export interface FullscreenUpdateEvent { + fullscreenUpdate: FullscreenUpdateVariants; + status: PlaybackStatus; +} + +export interface VideoProps { + source?: PlaybackSource | null; + posterSource?: URISource | RequireSource; + + resizeMode?: ResizeModeContain | ResizeModeCover | ResizeModeStretch; + useNativeControls?: boolean; + usePoster?: boolean; + + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void; + onReadyForDisplay?: (event: ReadyForDisplayEvent) => void; + onIOSFullscreenUpdate?: (event: FullscreenUpdateEvent) => void; + + onLoadStart?: () => void; + onLoad?: (status: PlaybackStatus) => void; + onError?: (error: string) => void; + + status?: PlaybackStatusToSet; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: number; + shouldCorrectPitch?: boolean; + volume?: number; + isMuted?: boolean; + isLooping?: boolean; + + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; + rotation?: number; + ref?: Ref; +} + +export interface VideoState { + showPoster: boolean; +} + +export class Video extends Component { + static RESIZE_MODE_CONTAIN: ResizeModeContain; + static RESIZE_MODE_COVER: ResizeModeCover; + static RESIZE_MODE_STRETCH: ResizeModeStretch; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS; +} +// #endregion + +/** + * Web Browser + */ +export namespace WebBrowser { + function openBrowserAsync(url: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function openAuthSessionAsync(url: string, redirectUrl?: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function dismissBrowser(): Promise<{ type: 'dismissed' }>; +} diff --git a/types/expo/v24/tsconfig.json b/types/expo/v24/tsconfig.json new file mode 100644 index 0000000000..87b7b33224 --- /dev/null +++ b/types/expo/v24/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "expo": [ + "expo/v24" + ], + "expo/*": [ + "expo/v24/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expo-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/expo/v24/tslint.json b/types/expo/v24/tslint.json new file mode 100644 index 0000000000..8270136207 --- /dev/null +++ b/types/expo/v24/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "void-return": false, + "max-line-length": false + } +} From 89ded17f34ec409ff8f2a3e5b1697e7362c35f48 Mon Sep 17 00:00:00 2001 From: Aleksei Tsikov Date: Mon, 26 Feb 2018 21:56:03 +0200 Subject: [PATCH 119/128] [events] Set removeAllListeners argument as optional (#23828) * Set removeAllListeners argument as optional * Update version properly --- types/events/events-tests.ts | 6 ++++++ types/events/index.d.ts | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/types/events/events-tests.ts b/types/events/events-tests.ts index ccf89c1402..67fe352225 100644 --- a/types/events/events-tests.ts +++ b/types/events/events-tests.ts @@ -53,6 +53,12 @@ setTimeout(() => { emitter.removeAllListeners('send'); }, 3000); +setTimeout(() => { + console.log('\n'); + emitter.emit('send', 'params1'); + emitter.removeAllListeners(); +}, 3000); + setTimeout(() => { console.log('\n'); emitter.emit(1); diff --git a/types/events/index.d.ts b/types/events/index.d.ts index 85ce0a7b0e..c9b08a4575 100644 --- a/types/events/index.d.ts +++ b/types/events/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for events 1.1 +// Type definitions for events 1.2 // Project: https://github.com/Gozala/events // Definitions by: Yasunori Ohoka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -15,7 +15,7 @@ export class EventEmitter { on(type: string | number, listener: Listener): this; once(type: string | number, listener: Listener): this; removeListener(type: string | number, listener: Listener): this; - removeAllListeners(type: string | number): this; + removeAllListeners(type?: string | number): this; listeners(type: string | number): Listener[]; listenerCount(type: string | number): number; } From fe34804ed7a3ecd9a9dcc32b6f6ba35bf906137b Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Mon, 26 Feb 2018 11:58:17 -0800 Subject: [PATCH 120/128] remove unnecessary comment --- types/single-line-log/single-line-log-tests.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/single-line-log/single-line-log-tests.ts b/types/single-line-log/single-line-log-tests.ts index 3814c64400..cb1ac0d7c6 100644 --- a/types/single-line-log/single-line-log-tests.ts +++ b/types/single-line-log/single-line-log-tests.ts @@ -1,4 +1,3 @@ -// @ts-check /// import singleLineLog = require('single-line-log'); From c9749a4f65137fa4d98ca64307bfe05301720113 Mon Sep 17 00:00:00 2001 From: David Date: Mon, 26 Feb 2018 19:59:10 +0000 Subject: [PATCH 121/128] [aws-lambda] Include CloudFrontRequest in CloudFrontRequestResult union type (#23882) A request is a valid callback result type. See example: https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html#lambda-edge-authoring-functions-example-ab-testing --- types/aws-lambda/aws-lambda-tests.ts | 10 +++++++++- types/aws-lambda/index.d.ts | 3 ++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index bd29160912..2b7b375576 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -631,7 +631,15 @@ let apiGtwProxyHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.API let proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => { }; apiGtwProxyHandler = proxyHandler; -let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => { }; +let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => { + cb(); + cb(null); + cb(new Error('')); + cb(null, { clientIp: str, method: str, uri: str, querystring: str, headers: { } }); + cb(null, { status: str }); + // $ExpectError + cb(null, { }); +}; let cloudFrontResponseHandler: AWSLambda.CloudFrontResponseHandler = (event: AWSLambda.CloudFrontResponseEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontResponseCallback) => { }; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 03910b108c..eccc96ba3e 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -15,6 +15,7 @@ // Palmi Valgeirsson // Danilo Raisi // Simon Buchan +// David Hayden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -516,7 +517,7 @@ export interface CloudFrontResponseEvent { }>; } -export type CloudFrontRequestResult = undefined | null | CloudFrontResultResponse; +export type CloudFrontRequestResult = undefined | null | CloudFrontResultResponse | CloudFrontRequest; export interface CloudFrontRequestEvent { Records: Array<{ From c37774d139d876b29373722c3c1ac4424835b78c Mon Sep 17 00:00:00 2001 From: Roberto Huertas Date: Mon, 26 Feb 2018 21:32:41 +0100 Subject: [PATCH 122/128] fixes issue #23759 (#23824) --- types/react-navigation/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 7cc0dc3d63..531a18e9e5 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -12,6 +12,7 @@ // Qibang Sun // Sergei Butko: // Veit Lehmann: +// Roberto Huertas: // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -166,10 +167,9 @@ export interface NavigationScreenConfigProps { export type NavigationScreenConfig = Options - | (NavigationScreenConfigProps & - ((navigationOptionsContainer: { + | ((navigationOptionsContainer: NavigationScreenConfigProps & { navigationOptions: NavigationScreenProp, - }) => Options)); + }) => Options); export type NavigationComponent = NavigationScreenComponent From 35cb910717f1cd6f79eaf8452bc0cba68be4bcd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Guilherme=20H=C3=BCbner=20Franco?= Date: Mon, 26 Feb 2018 17:33:11 -0300 Subject: [PATCH 123/128] Add react-text-mask definitions (#23871) --- types/react-text-mask/index.d.ts | 36 +++++++++++++++++++++++++++++ types/react-text-mask/tsconfig.json | 22 ++++++++++++++++++ types/react-text-mask/tslint.json | 3 +++ 3 files changed, 61 insertions(+) create mode 100644 types/react-text-mask/index.d.ts create mode 100644 types/react-text-mask/tsconfig.json create mode 100644 types/react-text-mask/tslint.json diff --git a/types/react-text-mask/index.d.ts b/types/react-text-mask/index.d.ts new file mode 100644 index 0000000000..f4c46bea58 --- /dev/null +++ b/types/react-text-mask/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for react-text-mask 16.0 +// Project: https://github.com/text-mask/text-mask +// Definitions by: Guilherme Hübner +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from "react"; + +export type maskArray = Array; + +export interface MaskedInputProps extends React.InputHTMLAttributes { + mask?: maskArray | ((input: HTMLInputElement) => maskArray); + + guide?: boolean; + + placeholderChar?: string; + + keepCharPositions?: boolean; + + pipe?: (conformedValue: string, config: any) => false | string | { value: string, indexesOfPipedChars: number[] }; + + onReject?: (infos: { conformedValue: string, maskRejection: boolean, pipeRejection: boolean }) => void; + + onAccept?: () => void; +} + +export interface conformToMaskResult { + conformedValue: string; + meta: { + someCharsRejected: boolean + }; +} + +export default class MaskedInput extends React.Component {} + +export function conformToMask(text: string, mask: maskArray, config: any): conformToMaskResult; diff --git a/types/react-text-mask/tsconfig.json b/types/react-text-mask/tsconfig.json new file mode 100644 index 0000000000..ca4a35b1cb --- /dev/null +++ b/types/react-text-mask/tsconfig.json @@ -0,0 +1,22 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/react-text-mask/tslint.json b/types/react-text-mask/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/react-text-mask/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 27be94dcba26ac2f350cb88ef87dd2cf5a8d164e Mon Sep 17 00:00:00 2001 From: Moritz Gunz Date: Mon, 26 Feb 2018 21:38:51 +0100 Subject: [PATCH 124/128] [spotify-web-playback-sdk] Reflect new changes (#23819) * Introduce new addListener / removeListener methods * Add definition creators * Add expected handler types --- types/spotify-web-playback-sdk/index.d.ts | 20 +++++++++++-- .../spotify-web-playback-sdk-tests.ts | 30 +++++++++++-------- 2 files changed, 35 insertions(+), 15 deletions(-) diff --git a/types/spotify-web-playback-sdk/index.d.ts b/types/spotify-web-playback-sdk/index.d.ts index 95d8375b56..ee3086e40e 100644 --- a/types/spotify-web-playback-sdk/index.d.ts +++ b/types/spotify-web-playback-sdk/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for spotify-web-playback-sdk 0.1 // Project: https://beta.developer.spotify.com/documentation/web-playback-sdk/reference/ // Definitions by: Festify Dev Team +// Marcus Weiner +// Moritz Gunz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Window { @@ -86,6 +88,10 @@ declare namespace Spotify { FULL_REPEAT = 2, } + type ErrorListener = (err: Error) => void; + type PlaybackInstanceListener = (inst: WebPlaybackInstance) => void; + type PlaybackStateListener = (s: PlaybackState) => void; + class SpotifyPlayer { constructor(options: PlayerInit); @@ -95,9 +101,17 @@ declare namespace Spotify { getVolume(): Promise; nextTrack(): Promise; - on(event: 'ready', cb: (pb: WebPlaybackInstance) => void): void; - on(event: 'player_state_changed', cb: (pb: PlaybackState) => void): void; - on(event: ErrorTypes, cb: (err: Error) => void): void; + addListener(event: 'ready', cb: PlaybackInstanceListener): void; + addListener(event: 'player_state_changed', cb: PlaybackStateListener): void; + addListener(event: ErrorTypes, cb: ErrorListener): void; + on(event: 'ready', cb: PlaybackInstanceListener): void; + on(event: 'player_state_changed', cb: PlaybackStateListener): void; + on(event: ErrorTypes, cb: ErrorListener): void; + + removeListener( + event: 'ready' | 'player_state_changed' | ErrorTypes, + cb?: ErrorListener | PlaybackInstanceListener | PlaybackStateListener, + ): void; pause(): Promise; previousTrack(): Promise; diff --git a/types/spotify-web-playback-sdk/spotify-web-playback-sdk-tests.ts b/types/spotify-web-playback-sdk/spotify-web-playback-sdk-tests.ts index afb82ef994..8f2c27f33d 100644 --- a/types/spotify-web-playback-sdk/spotify-web-playback-sdk-tests.ts +++ b/types/spotify-web-playback-sdk/spotify-web-playback-sdk-tests.ts @@ -5,14 +5,14 @@ const player = new Spotify.Player({ name: "Carly Rae Jepsen Player", - getOAuthToken: (callback) => { + getOAuthToken: (callback: (t: string) => void) => { // Run code to get a fresh access token callback("access token here"); }, volume: 0.5 }); -player.connect().then((success) => { +player.connect().then((success: boolean) => { if (success) { console.log("The Web Playback SDK successfully connected to Spotify!"); } @@ -20,11 +20,11 @@ player.connect().then((success) => { player.disconnect(); -player.on("ready", (data) => { +player.addListener("ready", (data) => { console.log("The Web Playback SDK is ready to play music!"); }); -player.getCurrentState().then((playbackState) => { +player.getCurrentState().then((playbackState: Spotify.PlaybackState | null) => { if (playbackState) { const { current_track, next_tracks } = playbackState.track_window; @@ -35,7 +35,7 @@ player.getCurrentState().then((playbackState) => { } }); -player.getVolume().then((volume) => { +player.getVolume().then((volume: number) => { const volume_percentage = (volume * 100); console.log(`The volume of the player is ${volume_percentage}%`); }); @@ -68,12 +68,12 @@ player.nextTrack().then(() => { console.log("Skipped to next track!"); }); -player.on("ready", (data) => { +player.on("ready", (data: Spotify.WebPlaybackInstance) => { const { device_id } = data; console.log("Connected with Device ID", device_id); }); -player.on("player_state_changed", (playbackState) => { +player.on("player_state_changed", (playbackState: Spotify.PlaybackState) => { const { position, duration } = playbackState; const { current_track } = playbackState.track_window; @@ -82,18 +82,24 @@ player.on("player_state_changed", (playbackState) => { console.log("Duration of Song", duration); }); -player.on('initialization_error', (e) => { +player.addListener('initialization_error', (e: Spotify.Error) => { console.error("Failed to initialize", e.message); }); -player.on('authentication_error', (e) => { +player.addListener('authentication_error', (e: Spotify.Error) => { console.error("Failed to authenticate", e.message); }); -player.on('account_error', (e) => { +player.addListener('account_error', (e: Spotify.Error) => { console.error("Failed to validate Spotify account", e.message); }); -player.on('playback_error', (e) => { +const listener = (e: Spotify.Error) => { console.error("Failed to perform playback", e.message); -}); +}; +player.addListener('playback_error', listener); +player.addListener('playback_error', () => {}); +player.removeListener('playback_error', () => {}); + +player.removeListener('playback_error'); +player.removeListener('playback_error', listener); From bd8ace8ec9f4ec63dee0b9af1f2eb1b7a5fd7d0e Mon Sep 17 00:00:00 2001 From: Theron Cross Date: Mon, 26 Feb 2018 14:46:41 -0600 Subject: [PATCH 125/128] Fix Enumerable#isAny second param type (#23827) * Fix Enumerable#isAny param type https://emberjs.com/api/ember/3.0/classes/Ember.NativeArray/methods/isAny?anchor=isAny * Update Enum#isAny and #isEvery params to any --- types/ember/index.d.ts | 4 ++-- types/ember/test/array.ts | 2 +- types/ember/test/ember-tests.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index bb268646be..8a47f00476 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -1182,7 +1182,7 @@ declare module 'ember' { * argument for all items in the enumerable. This method is often simpler/faster * than using a callback. */ - isEvery(key: string, value: boolean): boolean; + isEvery(key: string, value: any): boolean; /** * Returns `true` if the passed function returns true for any item in the * enumeration. @@ -1193,7 +1193,7 @@ declare module 'ember' { * argument for any item in the enumerable. This method is often simpler/faster * than using a callback. */ - isAny(key: string, value?: boolean): boolean; + isAny(key: string, value?: any): boolean; /** * This will combine the values of the enumerator into a single value. It * is a useful way to collect a summary value from an enumeration. This diff --git a/types/ember/test/array.ts b/types/ember/test/array.ts index 38f0fad5c6..8416a4a9ec 100755 --- a/types/ember/test/array.ts +++ b/types/ember/test/array.ts @@ -15,7 +15,7 @@ const people = Ember.A([ assertType(people.get('length')); assertType(people.get('lastObject')); assertType(people.isAny('isHappy')); -assertType(people.isAny('isHappy', false)); +assertType(people.isAny('isHappy', 'false')); assertType>(people.filterBy('isHappy')); assertType>(people.rejectBy('isHappy')); assertType>(people.filter((person) => person.get('name') === 'Yehuda')); diff --git a/types/ember/test/ember-tests.ts b/types/ember/test/ember-tests.ts index 94de3bf259..f0aff2478c 100755 --- a/types/ember/test/ember-tests.ts +++ b/types/ember/test/ember-tests.ts @@ -131,7 +131,7 @@ const isHappy = (person: typeof Person3.prototype): boolean => { people2.every(isHappy); people2.any(isHappy); people2.isEvery('isHappy', true); -people2.isAny('isHappy', true); +people2.isAny('isHappy', 'true'); people2.isAny('isHappy'); // Examples taken from http://emberjs.com/api/classes/Em.RSVP.Promise.html From ce73af4e00eb928d1410bdc06f94e06e37c488f6 Mon Sep 17 00:00:00 2001 From: Steven Date: Mon, 26 Feb 2018 13:35:23 -0800 Subject: [PATCH 126/128] fixed error in react-navigation preventing declaring navigationOptions as a function (#23879) --- types/react-navigation/index.d.ts | 1 + .../react-navigation-tests.tsx | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 531a18e9e5..c4e396783f 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -13,6 +13,7 @@ // Sergei Butko: // Veit Lehmann: // Roberto Huertas: +// Steven Miller // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx index a7eaad092b..017a9b9153 100644 --- a/types/react-navigation/react-navigation-tests.tsx +++ b/types/react-navigation/react-navigation-tests.tsx @@ -199,6 +199,26 @@ function renderBasicStackNavigator(): JSX.Element { ); } +const stackNavigatorConfigWithNavigationOptionsAsFunction: StackNavigatorConfig = { + mode: "card", + headerMode: "screen", + navigationOptions: ({navigationOptions, navigation, screenProps}) => (stackNavigatorScreenOptions), +}; + +const AdvancedStackNavigator = StackNavigator( + routeConfigMap, + stackNavigatorConfigWithNavigationOptionsAsFunction +); + +function renderAdvancedStackNavigator(): JSX.Element { + return ( + { }} + style={viewStyle} + /> + ); +} + /** * Drawer navigator. */ From c6614dd157bd8364265070150c0b68d41025b1be Mon Sep 17 00:00:00 2001 From: Ben Grynhaus Date: Mon, 26 Feb 2018 23:45:54 +0200 Subject: [PATCH 127/128] Added types for 'ipcheck' (#23813) * Added types for 'ipcheck' * Fixed tests got be according to linting guidelines * Made tsconfig stricter * Standard tslint file * Standartize ipcheck.d.ts * tslint disable in .d.ts file * disabled interface-name rule --- types/ipcheck/index.d.ts | 29 +++++++++++++++++++++++++++++ types/ipcheck/ipcheck-tests.ts | 19 +++++++++++++++++++ types/ipcheck/tsconfig.json | 16 ++++++++++++++++ types/ipcheck/tslint.json | 6 ++++++ 4 files changed, 70 insertions(+) create mode 100644 types/ipcheck/index.d.ts create mode 100644 types/ipcheck/ipcheck-tests.ts create mode 100644 types/ipcheck/tsconfig.json create mode 100644 types/ipcheck/tslint.json diff --git a/types/ipcheck/index.d.ts b/types/ipcheck/index.d.ts new file mode 100644 index 0000000000..2eca10280b --- /dev/null +++ b/types/ipcheck/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for ipcheck 0.1 +// Project: https://github.com/gosquared/ipcheck +// Definitions by: Ben Grynhaus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +declare const ipcheck: ipcheck.IPCheckStatic; +export = ipcheck; +export as namespace ipcheck; + +declare namespace ipcheck { + interface IPCheck { + address: number[]; + input: string; + ipv: 4 | 6 | 0; + mask: number; + valid: boolean; + + match(cidr: IPCheck | string): boolean; + } + + interface IPCheckConstructor { + new (input: string): IPCheck; + } + + interface IPCheckStatic extends IPCheckConstructor { + match(ip: IPCheck | string, cidr: IPCheck | string): boolean; + } +} diff --git a/types/ipcheck/ipcheck-tests.ts b/types/ipcheck/ipcheck-tests.ts new file mode 100644 index 0000000000..e54d396652 --- /dev/null +++ b/types/ipcheck/ipcheck-tests.ts @@ -0,0 +1,19 @@ +import * as ipcheck from "ipcheck"; + +ipcheck.match(1, 1); // $ExpectError +ipcheck.match("", 1); // $ExpectError +ipcheck.match(1, ""); // $ExpectError + +new ipcheck(1); // $ExpectError + +const ip = new ipcheck(""); + +// $ExpectError +if (ip.ipv === 1) { +} + +// $ExpectError +if (ip.ipv === 1) { +} + +ip.match(1); // $ExpectError diff --git a/types/ipcheck/tsconfig.json b/types/ipcheck/tsconfig.json new file mode 100644 index 0000000000..18470e3333 --- /dev/null +++ b/types/ipcheck/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "ipcheck-tests.ts"] +} diff --git a/types/ipcheck/tslint.json b/types/ipcheck/tslint.json new file mode 100644 index 0000000000..2c7c1bed53 --- /dev/null +++ b/types/ipcheck/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "interface-name": false + } +} From 62c721de256ceea7e43ae82d8fd8c80c2b8a3cf2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kevin=20Tji=C3=A5m?= Date: Tue, 27 Feb 2018 10:14:16 +0800 Subject: [PATCH 128/128] [@types/amphtml-validator] New type definitions (#23923) * feat(amphtml-validator): add type definitions for amphtml-validator * feat(amphtml-validator): PR reviews - fix lint rules, consolidate files, remove comments, improve tests --- .../amphtml-validator-tests.ts | 28 ++++ types/amphtml-validator/index.d.ts | 156 ++++++++++++++++++ types/amphtml-validator/tsconfig.json | 16 ++ types/amphtml-validator/tslint.json | 1 + 4 files changed, 201 insertions(+) create mode 100644 types/amphtml-validator/amphtml-validator-tests.ts create mode 100644 types/amphtml-validator/index.d.ts create mode 100644 types/amphtml-validator/tsconfig.json create mode 100644 types/amphtml-validator/tslint.json diff --git a/types/amphtml-validator/amphtml-validator-tests.ts b/types/amphtml-validator/amphtml-validator-tests.ts new file mode 100644 index 0000000000..4160f7a451 --- /dev/null +++ b/types/amphtml-validator/amphtml-validator-tests.ts @@ -0,0 +1,28 @@ +import * as ampHtmlValidator from "amphtml-validator"; + +(async () => { + const validator = await ampHtmlValidator.getInstance(); + const result = validator.validateString(""); + const { status, errors } = result; + if (status === "FAIL" || status === "UNKNOWN") { + const errs = errors.map(err => { + const { + severity, + line, + col, + message, + specUrl, + category, + code, + params + } = err; + return err; + }); + } +})(); + +(() => { + const validator = ampHtmlValidator.newInstance(""); + const result = validator.validateString(""); + const { status, errors } = result; +})(); diff --git a/types/amphtml-validator/index.d.ts b/types/amphtml-validator/index.d.ts new file mode 100644 index 0000000000..bcf8e5d66e --- /dev/null +++ b/types/amphtml-validator/index.d.ts @@ -0,0 +1,156 @@ +// Type definitions for amphtml-validator 1.0 +// Project: https://github.com/ampproject/amphtml/tree/master/validator/nodejs +// Definitions by: Kevin Tjiam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Context, Script } from "vm"; + +export interface ValidationError { + severity: ValidationErrorSeverity; + line: number; + col: number; + message: string; + specUrl: string | null; + category: ErrorCategoryCode; + code: ValidationErrorCode; + params: string[]; +} + +export interface ValidationResult { + status: ValidationResultStatus; + errors: ValidationError[]; +} + +export class Validator extends Script { + sandbox: Context; + validateString(stringToValidate: string): ValidationResult; +} + +export function getInstance( + validatorJs?: string, + userAgent?: string +): Promise; +export function newInstance(validatorJsContents: string): Validator; + +/** + * Enums from protobufs + * https://github.com/ampproject/amphtml/blob/master/validator/validator.proto + */ +export type ValidationResultStatus = "UNKNOWN" | "PASS" | "FAIL"; + +export type ValidationErrorSeverity = "UNKNOWN_SEVERITY" | "ERROR" | "WARNING"; + +export type ErrorCategoryCode = + | "UNKNOWN" + | "GENERIC" + | "DISALLOWED_HTML_WITH_AMP_EQUIVALENT" + | "DISALLOWED_HTML" + | "AUTHOR_STYLESHEET_PROBLEM" + | "MANDATORY_AMP_TAG_MISSING_OR_INCORRECT" + | "AMP_TAG_PROBLEM" + | "CUSTOM_JAVASCRIPT_DISALLOWED" + | "AMP_LAYOUT_PROBLEM" + | "AMP_HTML_TEMPLATE_PROBLEM" + | "DEPRECATION"; + +export type ValidationErrorCode = + | "UNKNOWN_CODE" + | "MANDATORY_TAG_MISSING" + | "TAG_REQUIRED_BY_MISSING" + | "WARNING_TAG_REQUIRED_BY_MISSING" + | "WARNING_EXTENSION_UNUSED" + | "EXTENSION_UNUSED" + | "WARNING_EXTENSION_DEPRECATED_VERSION" + | "ATTR_REQUIRED_BUT_MISSING" + | "DISALLOWED_TAG" + | "GENERAL_DISALLOWED_TAG" + | "DISALLOWED_SCRIPT_TAG" + | "DISALLOWED_ATTR" + | "DISALLOWED_STYLE_ATTR" + | "INVALID_ATTR_VALUE" + | "DUPLICATE_ATTRIBUTE" + | "ATTR_VALUE_REQUIRED_BY_LAYOUT" + | "IMPLIED_LAYOUT_INVALID" + | "SPECIFIED_LAYOUT_INVALID" + | "MANDATORY_ATTR_MISSING" + | "MANDATORY_ONEOF_ATTR_MISSING" + | "DUPLICATE_DIMENSION" + | "DUPLICATE_UNIQUE_TAG" + | "DUPLICATE_UNIQUE_TAG_WARNING" + | "WRONG_PARENT_TAG" + | "STYLESHEET_TOO_LONG" + | "MANDATORY_CDATA_MISSING_OR_INCORRECT" + | "CDATA_VIOLATES_BLACKLIST" + | "NON_WHITESPACE_CDATA_ENCOUNTERED" + | "DEPRECATED_ATTR" + | "DEPRECATED_TAG" + | "MANDATORY_PROPERTY_MISSING_FROM_ATTR_VALUE" + | "INVALID_PROPERTY_VALUE_IN_ATTR_VALUE" + | "MISSING_URL" + | "INVALID_URL" + | "INVALID_URL_PROTOCOL" + | "DISALLOWED_DOMAIN" + | "DISALLOWED_RELATIVE_URL" + | "DISALLOWED_PROPERTY_IN_ATTR_VALUE" + | "MUTUALLY_EXCLUSIVE_ATTRS" + | "UNESCAPED_TEMPLATE_IN_ATTR_VALUE" + | "TEMPLATE_PARTIAL_IN_ATTR_VALUE" + | "TEMPLATE_IN_ATTR_NAME" + | "INCONSISTENT_UNITS_FOR_WIDTH_AND_HEIGHT" + | "DISALLOWED_TAG_ANCESTOR" + | "MANDATORY_LAST_CHILD_TAG" + | "MANDATORY_TAG_ANCESTOR" + | "MANDATORY_TAG_ANCESTOR_WITH_HINT" + | "ATTR_DISALLOWED_BY_IMPLIED_LAYOUT" + | "ATTR_DISALLOWED_BY_SPECIFIED_LAYOUT" + | "INCORRECT_NUM_CHILD_TAGS" + | "INCORRECT_MIN_NUM_CHILD_TAGS" + | "DISALLOWED_CHILD_TAG_NAME" + | "DISALLOWED_FIRST_CHILD_TAG_NAME" + | "DISALLOWED_MANUFACTURED_BODY" + | "CHILD_TAG_DOES_NOT_SATISFY_REFERENCE_POINT" + | "MANDATORY_REFERENCE_POINT_MISSING" + | "DUPLICATE_REFERENCE_POINT" + | "TAG_NOT_ALLOWED_TO_HAVE_SIBLINGS" + | "TAG_REFERENCE_POINT_CONFLICT" + | "CHILD_TAG_DOES_NOT_SATISFY_REFERENCE_POINT_SINGULAR" + | "BASE_TAG_MUST_PRECEED_ALL_URLS" + | "MISSING_REQUIRED_EXTENSION" + | "ATTR_MISSING_REQUIRED_EXTENSION" + | "DOCUMENT_TOO_COMPLEX" + | "INVALID_UTF8" + | "CSS_SYNTAX" + | "CSS_SYNTAX_INVALID_AT_RULE" + | "CSS_SYNTAX_STRAY_TRAILING_BACKSLASH" + | "CSS_SYNTAX_UNTERMINATED_COMMENT" + | "CSS_SYNTAX_UNTERMINATED_STRING" + | "CSS_SYNTAX_BAD_URL" + | "CSS_SYNTAX_EOF_IN_PRELUDE_OF_QUALIFIED_RULE" + | "CSS_SYNTAX_INVALID_DECLARATION" + | "CSS_SYNTAX_INCOMPLETE_DECLARATION" + | "CSS_SYNTAX_ERROR_IN_PSEUDO_SELECTOR" + | "CSS_SYNTAX_MISSING_SELECTOR" + | "CSS_SYNTAX_NOT_A_SELECTOR_START" + | "CSS_SYNTAX_UNPARSED_INPUT_REMAINS_IN_SELECTOR" + | "CSS_SYNTAX_MISSING_URL" + | "CSS_SYNTAX_INVALID_URL" + | "CSS_SYNTAX_INVALID_URL_PROTOCOL" + | "CSS_SYNTAX_DISALLOWED_DOMAIN" + | "CSS_SYNTAX_DISALLOWED_RELATIVE_URL" + | "CSS_SYNTAX_INVALID_ATTR_SELECTOR" + | "CSS_SYNTAX_INVALID_PROPERTY" + | "CSS_SYNTAX_INVALID_PROPERTY_NOLIST" + | "CSS_SYNTAX_QUALIFIED_RULE_HAS_NO_DECLARATIONS" + | "CSS_SYNTAX_DISALLOWED_QUALIFIED_RULE_MUST_BE_INSIDE_KEYFRAME" + | "CSS_SYNTAX_DISALLOWED_KEYFRAME_INSIDE_KEYFRAME" + | "CSS_SYNTAX_MALFORMED_MEDIA_QUERY" + | "CSS_SYNTAX_DISALLOWED_MEDIA_TYPE" + | "CSS_SYNTAX_DISALLOWED_MEDIA_FEATURE" + | "CSS_SYNTAX_DISALLOWED_PROPERTY_VALUE" + | "CSS_SYNTAX_DISALLOWED_PROPERTY_VALUE_WITH_HINT" + | "CSS_SYNTAX_PROPERTY_DISALLOWED_WITHIN_AT_RULE" + | "CSS_SYNTAX_PROPERTY_DISALLOWED_TOGETHER_WITH" + | "CSS_SYNTAX_PROPERTY_REQUIRES_QUALIFICATION"; diff --git a/types/amphtml-validator/tsconfig.json b/types/amphtml-validator/tsconfig.json new file mode 100644 index 0000000000..0c0c91b549 --- /dev/null +++ b/types/amphtml-validator/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "amphtml-validator-tests.ts"] +} diff --git a/types/amphtml-validator/tslint.json b/types/amphtml-validator/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/amphtml-validator/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" }