From b3e1195fe52f7dc3ed9cd8c82fbd14e89eb8d167 Mon Sep 17 00:00:00 2001 From: Damien SOREL Date: Thu, 7 Mar 2019 13:37:18 +0100 Subject: [PATCH 001/337] Initial definition for @wordpress/jest-console --- types/wordpress__jest-console/index.d.ts | 51 +++++++++++++++++++ .../jest-console-tests.ts | 13 +++++ types/wordpress__jest-console/tsconfig.json | 24 +++++++++ types/wordpress__jest-console/tslint.json | 1 + 4 files changed, 89 insertions(+) create mode 100644 types/wordpress__jest-console/index.d.ts create mode 100644 types/wordpress__jest-console/jest-console-tests.ts create mode 100644 types/wordpress__jest-console/tsconfig.json create mode 100644 types/wordpress__jest-console/tslint.json diff --git a/types/wordpress__jest-console/index.d.ts b/types/wordpress__jest-console/index.d.ts new file mode 100644 index 0000000000..ecda81d6f7 --- /dev/null +++ b/types/wordpress__jest-console/index.d.ts @@ -0,0 +1,51 @@ +// Type definitions for @wordpress/jest-console 3.0 +// Project: https://github.com/wordpress/gutenberg/tree/master/packages/jest-console/readme.md +// Definitions by: Damien Sorel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +/// + +declare namespace jest { + interface Matchers { + /** + * Ensure that `console.error` function was called. + */ + toHaveErrored(): R; + + /** + * Ensure that `console.error` function was called with specific arguments. + */ + toHaveErroredWith(...args: any[]): R; + + /** + * Ensure that `console.info` function was called. + */ + toHaveInformed(): R; + + /** + * Ensure that `console.info` function was called with specific arguments. + */ + toHaveInformedWith(...args: any[]): R; + + /** + * Ensure that `console.log` function was called. + */ + toHaveLogged(): R; + + /** + * Ensure that `console.log` function was called with specific arguments. + */ + toHaveLoggedWith(...args: any[]): R; + + /** + * Ensure that `console.warn` function was called. + */ + toHaveWarned(): R; + + /** + * Ensure that `console.warn` function was called with specific arguments. + */ + toHaveWarnedWith(...args: any[]): R; + } +} diff --git a/types/wordpress__jest-console/jest-console-tests.ts b/types/wordpress__jest-console/jest-console-tests.ts new file mode 100644 index 0000000000..7c8eec6968 --- /dev/null +++ b/types/wordpress__jest-console/jest-console-tests.ts @@ -0,0 +1,13 @@ +it('uses the console', () => { + expect(console).toHaveErrored(); + expect(console).toHaveErroredWith('message'); + + expect(console).toHaveInformed(); + expect(console).toHaveInformedWith('message'); + + expect(console).toHaveLogged(); + expect(console).toHaveLoggedWith('message'); + + expect(console).toHaveWarned(); + expect(console).toHaveWarnedWith('message'); +}); diff --git a/types/wordpress__jest-console/tsconfig.json b/types/wordpress__jest-console/tsconfig.json new file mode 100644 index 0000000000..f21c4b6ce7 --- /dev/null +++ b/types/wordpress__jest-console/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", + "jest-console-tests.ts" + ] +} diff --git a/types/wordpress__jest-console/tslint.json b/types/wordpress__jest-console/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/wordpress__jest-console/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 728bc739a0163f0761d0d625e68b799471996f07 Mon Sep 17 00:00:00 2001 From: Jarrett Meyer Date: Mon, 11 Mar 2019 15:22:18 -0400 Subject: [PATCH 002/337] Adds nodeSort() functions to d3-sankey --- types/d3-sankey/index.d.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/types/d3-sankey/index.d.ts b/types/d3-sankey/index.d.ts index 4f70bbbe61..c05f3031b2 100644 --- a/types/d3-sankey/index.d.ts +++ b/types/d3-sankey/index.d.ts @@ -337,6 +337,18 @@ export interface SankeyLayout, b: SankeyNode) => number) | undefined; + + /** + * Set the node comparison function and return this Sankey layout generator. + * + * @param compare Node comparison function. + */ + nodeSort(compare: (a: SankeyNode, b: SankeyNode) => number): this; } /** From e0eaf5058a1a8cc51786531198dc78c96c0075f2 Mon Sep 17 00:00:00 2001 From: Jarrett Meyer Date: Mon, 11 Mar 2019 15:31:06 -0400 Subject: [PATCH 003/337] bump version --- types/d3-sankey/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/d3-sankey/index.d.ts b/types/d3-sankey/index.d.ts index c05f3031b2..f5394a1b26 100644 --- a/types/d3-sankey/index.d.ts +++ b/types/d3-sankey/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Last module patch version validated against: 0.7.1 +// Last module patch version validated against: 0.11.0 import { Link } from 'd3-shape'; From 46e664589abe3f13ca566b1464c55c5554ff7e8c Mon Sep 17 00:00:00 2001 From: Ziyu Wang Date: Tue, 12 Mar 2019 11:54:17 +1100 Subject: [PATCH 004/337] strict null checks for redux-actions --- types/redux-actions/index.d.ts | 17 +++++++++++------ types/redux-actions/redux-actions-tests.ts | 20 ++++++++++++++------ types/redux-actions/tsconfig.json | 2 +- 3 files changed, 26 insertions(+), 13 deletions(-) diff --git a/types/redux-actions/index.d.ts b/types/redux-actions/index.d.ts index 6891563ab9..0ecb215572 100644 --- a/types/redux-actions/index.d.ts +++ b/types/redux-actions/index.d.ts @@ -5,6 +5,7 @@ // Alec Hill // Alexey Pelykh // Thiago de Andrade +// Ziyu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -17,7 +18,7 @@ export interface BaseAction { } export interface Action extends BaseAction { - payload?: Payload; + payload: Payload; error?: boolean; } @@ -66,6 +67,10 @@ export type Reducer = (state: State, action: Action) => export type ReducerMeta = (state: State, action: ActionMeta) => State; +export type ReduxReducer = (state: State | undefined, action: Action) => State; + +export type ReduxReducerMeta = (state: State | undefined, action: ActionMeta) => State; + /** argument inferring borrowed from lodash definitions */ export type ActionFunction0 = () => R; export type ActionFunction1 = (t1: T1) => R; @@ -148,13 +153,13 @@ export function handleAction( actionType: string | ActionFunctions | CombinedActionType, reducer: Reducer | ReducerNextThrow, initialState: State -): Reducer; +): ReduxReducer; export function handleAction( actionType: string | ActionWithMetaFunctions | CombinedActionType, reducer: ReducerMeta | ReducerNextThrowMeta, initialState: State -): Reducer; +): ReduxReducerMeta; export interface Options { prefix?: string; @@ -165,19 +170,19 @@ export function handleActions( reducerMap: ReducerMap, initialState: StateAndPayload, options?: Options -): Reducer; +): ReduxReducer; export function handleActions( reducerMap: ReducerMap, initialState: State, options?: Options -): Reducer; +): ReduxReducer; export function handleActions( reducerMap: ReducerMapMeta, initialState: State, options?: Options -): ReducerMeta; +): ReduxReducerMeta; // https://github.com/redux-utilities/redux-actions/blob/v2.3.0/src/combineActions.js#L21 export function combineActions(...actionTypes: Array | string | symbol>): CombinedActionType; diff --git a/types/redux-actions/redux-actions-tests.ts b/types/redux-actions/redux-actions-tests.ts index 207e4746b7..27f33a2843 100644 --- a/types/redux-actions/redux-actions-tests.ts +++ b/types/redux-actions/redux-actions-tests.ts @@ -1,7 +1,6 @@ import * as ReduxActions from 'redux-actions'; let state: number; -const minimalAction: ReduxActions.BaseAction = { type: 'INCREMENT' }; const incrementAction: () => ReduxActions.Action = ReduxActions.createAction( 'INCREMENT', () => 1 @@ -11,14 +10,13 @@ const multiplyAction: (...args: number[]) => ReduxActions.Action = Redux 'MULTIPLY' ); -const action: ReduxActions.Action = incrementAction(); - const actionHandler = ReduxActions.handleAction( 'INCREMENT', (state: number, action: ReduxActions.Action) => state + action.payload, 0 ); +state = actionHandler(undefined, incrementAction()); state = actionHandler(0, incrementAction()); const actionHandlerWithReduceMap = ReduxActions.handleAction( @@ -31,6 +29,7 @@ const actionHandlerWithReduceMap = ReduxActions.handleAction( 0 ); +state = actionHandlerWithReduceMap(undefined, multiplyAction(10)); state = actionHandlerWithReduceMap(0, multiplyAction(10)); const actionsHandler = ReduxActions.handleActions({ @@ -38,7 +37,8 @@ const actionsHandler = ReduxActions.handleActions({ MULTIPLY: (state: number, action: ReduxActions.Action) => state * action.payload }, 0); -state = actionsHandler(0, { type: 'INCREMENT' }); +state = actionsHandler(undefined, incrementAction()); +state = actionsHandler(0, incrementAction()); const actionsHandlerWithInitialState = ReduxActions.handleActions({ INCREMENT: { @@ -49,7 +49,8 @@ const actionsHandlerWithInitialState = ReduxActions.handleActions({ } }, 0); -state = actionsHandlerWithInitialState(0, { type: 'INCREMENT' }); +state = actionsHandlerWithInitialState(undefined, incrementAction()); +state = actionsHandlerWithInitialState(0, incrementAction()); const actionsHandlerWithRecursiveReducerMap = ReduxActions.handleActions({ ADJUST: { @@ -58,6 +59,7 @@ const actionsHandlerWithRecursiveReducerMap = ReduxActions.handleActions) => state * action.payload }, 0, {prefix: 'TEST'}); -state = actionsHandlerWithOptions(0, { type: 'TEST/INCREMENT' }); +state = actionsHandlerWithOptions(undefined, { type: 'TEST/INCREMENT', payload: 1 }); +state = actionsHandlerWithOptions(0, { type: 'TEST/INCREMENT', payload: 1 }); const actionsHandlerWithRecursiveReducerMapAndOptions = ReduxActions.handleActions({ ADJUST: { @@ -74,6 +77,7 @@ const actionsHandlerWithRecursiveReducerMapAndOptions = ReduxActions.handleActio } }, 0, {namespace: '--'}); +state = actionsHandlerWithRecursiveReducerMapAndOptions(undefined, { type: 'ADJUST--UP', payload: 1 }); state = actionsHandlerWithRecursiveReducerMapAndOptions(0, { type: 'ADJUST--UP', payload: 1 }); // ---------------------------------------------------------------------------------------------------- @@ -117,6 +121,7 @@ const typedActionHandler = ReduxActions.handleAction( const actionNoArgs = typedIncrementAction(); actionNoArgs.payload.increase = 1; +typedState = typedActionHandler(undefined, actionNoArgs); typedState = typedActionHandler({ value: 0 }, actionNoArgs); const typedIncrementAction1TypedArg: (value: number) => @@ -144,6 +149,7 @@ const typedActionHandlerReducerMap = ReduxActions.handleActions( {value: 1} ); +typedState = typedActionHandlerReducerMap(undefined, actionFrom1Arg); typedState = typedActionHandlerReducerMap({ value: 0 }, actionFrom1Arg); const typedIncrementByActionWithMetaAnyArgs: (...args: any[]) => ReduxActions.ActionMeta = @@ -167,6 +173,7 @@ const typedActionHandlerWithMeta = ReduxActions.handleAction( @@ -181,6 +188,7 @@ const typedActionHandlerReducerMetaMap = ReduxActions.handleActions ReduxActions.ActionMeta = diff --git a/types/redux-actions/tsconfig.json b/types/redux-actions/tsconfig.json index ea4f7f1a53..8a88909508 100644 --- a/types/redux-actions/tsconfig.json +++ b/types/redux-actions/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": false, "baseUrl": "../", "typeRoots": [ From 87294f57f69d42287df551c65f271c620e66a696 Mon Sep 17 00:00:00 2001 From: Ziyu Wang Date: Tue, 12 Mar 2019 12:03:50 +1100 Subject: [PATCH 005/337] increment version number to match redux-actions --- types/redux-actions/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/redux-actions/index.d.ts b/types/redux-actions/index.d.ts index 0ecb215572..f0654eab08 100644 --- a/types/redux-actions/index.d.ts +++ b/types/redux-actions/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redux-actions 2.3 +// Type definitions for redux-actions 2.6 // Project: https://github.com/redux-utilities/redux-actions // Definitions by: Jack Hsu , // Alex Gorbatchev , From 425ddf9e29d2cb37dfd37ea16b1ff4862c38d691 Mon Sep 17 00:00:00 2001 From: mrsekut Date: Tue, 12 Mar 2019 16:22:22 +0900 Subject: [PATCH 006/337] Update Optional argument of push method --- types/redux-form/index.d.ts | 1 + types/redux-form/lib/FieldArray.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index 752dccd876..7005abf1de 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -14,6 +14,7 @@ // Mohamed Shaaban // Ethan Setnik // Walter Barbagallo +// Kota Marusue // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 import { diff --git a/types/redux-form/lib/FieldArray.d.ts b/types/redux-form/lib/FieldArray.d.ts index b84d04ad5a..026e75633f 100644 --- a/types/redux-form/lib/FieldArray.d.ts +++ b/types/redux-form/lib/FieldArray.d.ts @@ -40,7 +40,7 @@ export interface FieldArrayFieldsProps { length: number; map(callback: FieldIterate): R[]; pop(): FieldValue; - push(value: FieldValue): void; + push(value?: FieldValue): void; remove(index: number): void; shift(): FieldValue; swap(indexA: number, indexB: number): void; From 4108ddb08ef6a33760f4d2ebafdd38012afdc23b Mon Sep 17 00:00:00 2001 From: Eugene Wang Date: Wed, 13 Mar 2019 15:02:01 -0400 Subject: [PATCH 007/337] correction of credits or comments This type definition has totally nothing related to @caseycesari 's geojson parser library. The previous PR is misleading, at least on this type definition. --- types/geojson/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/geojson/index.d.ts b/types/geojson/index.d.ts index 90beca01c1..db8074e242 100644 --- a/types/geojson/index.d.ts +++ b/types/geojson/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for geojson 7946.0 -// Project: https://geojson.org/, https://github.com/caseycesari/geojson.js +// Project: https://geojson.org/ // Definitions by: Jacob Bruun // Arne Schubert // Jeff Jacobson From 18be7de7bd4050dbdf8c77f5f0baee5b8347e8dc Mon Sep 17 00:00:00 2001 From: Moshe Kolodny Date: Wed, 13 Mar 2019 17:49:37 -0400 Subject: [PATCH 008/337] Add stronger typings to jasmine spys --- types/jasmine-ajax/jasmine-ajax-tests.ts | 2 +- types/jasmine/package.json | 11 + types/jasmine/ts3.1/index.d.ts | 857 ++++++++++++++ types/jasmine/ts3.1/jasmine-tests.ts | 1358 ++++++++++++++++++++++ types/jasmine/ts3.1/tsconfig.json | 22 + types/jasmine/ts3.1/tslint.json | 13 + 6 files changed, 2262 insertions(+), 1 deletion(-) create mode 100644 types/jasmine/package.json create mode 100644 types/jasmine/ts3.1/index.d.ts create mode 100644 types/jasmine/ts3.1/jasmine-tests.ts create mode 100644 types/jasmine/ts3.1/tsconfig.json create mode 100644 types/jasmine/ts3.1/tslint.json diff --git a/types/jasmine-ajax/jasmine-ajax-tests.ts b/types/jasmine-ajax/jasmine-ajax-tests.ts index cf1db49f28..325a66d14f 100644 --- a/types/jasmine-ajax/jasmine-ajax-tests.ts +++ b/types/jasmine-ajax/jasmine-ajax-tests.ts @@ -462,7 +462,7 @@ describe('FakeRequest', () => { it('ticks the jasmine clock on timeout', () => { const clock = { tick: jasmine.createSpy('tick') }; - spyOn(jasmine, 'clock').and.returnValue(clock); + spyOn(jasmine, 'clock').and.returnValue(clock as any); const request = new this.FakeRequest(); request.open(); diff --git a/types/jasmine/package.json b/types/jasmine/package.json new file mode 100644 index 0000000000..f2591ceb88 --- /dev/null +++ b/types/jasmine/package.json @@ -0,0 +1,11 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { + "*": [ + "ts3.1/*" + ] + } + } +} diff --git a/types/jasmine/ts3.1/index.d.ts b/types/jasmine/ts3.1/index.d.ts new file mode 100644 index 0000000000..c5c39b342c --- /dev/null +++ b/types/jasmine/ts3.1/index.d.ts @@ -0,0 +1,857 @@ +// Definitions by: Boris Yankov +// Theodore Brown +// David Pärsson +// Gabe Moothart +// Lukas Zech +// Boris Breuer +// Chris Yungmann +// Giles Roadnight +// Yaroslav Admin +// Domas Trijonis +// Peter Safranek +// Moshe Kolodny +// For ddescribe / iit use : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts + +type ImplementationCallback = (() => Promise) | ((done: DoneFn) => void); +type InferableFunction = (...args: any[]) => any; + +/** + * Create a group of specs (often called a suite). + * @param description Textual description of the group + * @param specDefinitions Function for Jasmine to invoke that will define inner suites a specs + */ +declare function describe(description: string, specDefinitions: () => void): void; + +/** + * A focused `describe`. If suites or specs are focused, only those that are focused will be executed. + * @param description Textual description of the group + * @param specDefinitions Function for Jasmine to invoke that will define inner suites a specs + */ +declare function fdescribe(description: string, specDefinitions: () => void): void; + +/** + * A temporarily disabled `describe`. Specs within an xdescribe will be marked pending and not executed. + * @param description Textual description of the group + * @param specDefinitions Function for Jasmine to invoke that will define inner suites a specs + */ +declare function xdescribe(description: string, specDefinitions: () => void): void; + +/** + * Define a single spec. A spec should contain one or more expectations that test the state of the code. + * A spec whose expectations all succeed will be passing and a spec with any failures will fail. + * @param expectation Textual description of what this spec is checking + * @param assertion Function that contains the code of your test. If not provided the test will be pending. + * @param timeout Custom timeout for an async spec. + */ +declare function it(expectation: string, assertion?: ImplementationCallback, timeout?: number): void; + +/** + * A focused `it`. If suites or specs are focused, only those that are focused will be executed. + * @param expectation Textual description of what this spec is checking + * @param assertion Function that contains the code of your test. If not provided the test will be pending. + * @param timeout Custom timeout for an async spec. + */ +declare function fit(expectation: string, assertion?: ImplementationCallback, timeout?: number): void; + +/** + * A temporarily disabled `it`. The spec will report as pending and will not be executed. + * @param expectation Textual description of what this spec is checking + * @param assertion Function that contains the code of your test. If not provided the test will be pending. + * @param timeout Custom timeout for an async spec. + */ +declare function xit(expectation: string, assertion?: ImplementationCallback, timeout?: number): void; + +/** + * Mark a spec as pending, expectation results will be ignored. + * If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. + * @param reason Reason the spec is pending. + */ +declare function pending(reason?: string): void; + +/** + * Run some shared setup before each of the specs in the describe in which it is called. + * @param action Function that contains the code to setup your specs. + * @param timeout Custom timeout for an async beforeEach. + */ +declare function beforeEach(action: ImplementationCallback, timeout?: number): void; + +/** + * Run some shared teardown after each of the specs in the describe in which it is called. + * @param action Function that contains the code to teardown your specs. + * @param timeout Custom timeout for an async afterEach. + */ +declare function afterEach(action: ImplementationCallback, timeout?: number): void; + +/** + * Run some shared setup once before all of the specs in the describe are run. + * Note: Be careful, sharing the setup from a beforeAll makes it easy to accidentally leak state between your specs so that they erroneously pass or fail. + * @param action Function that contains the code to setup your specs. + * @param timeout Custom timeout for an async beforeAll. + */ +declare function beforeAll(action: ImplementationCallback, timeout?: number): void; + +/** + * Run some shared teardown once before all of the specs in the describe are run. + * Note: Be careful, sharing the teardown from a afterAll makes it easy to accidentally leak state between your specs so that they erroneously pass or fail. + * @param action Function that contains the code to teardown your specs. + * @param timeout Custom timeout for an async afterAll + */ +declare function afterAll(action: ImplementationCallback, timeout?: number): void; + +/** + * Create an expectation for a spec. + * @checkReturnValue see https://tsetse.info/check-return-value + * @param spy + */ +declare function expect(spy: Function): jasmine.Matchers; + +/** + * Create an expectation for a spec. + * @checkReturnValue see https://tsetse.info/check-return-value + * @param actual + */ +declare function expect(actual: ArrayLike): jasmine.ArrayLikeMatchers; + +/** + * Create an expectation for a spec. + * @checkReturnValue see https://tsetse.info/check-return-value + * @param actual Actual computed value to test expectations against. + */ +declare function expect(actual: T): jasmine.Matchers; + +/** + * Create an expectation for a spec. + */ +declare function expect(): jasmine.NothingMatcher; + +/** + * Create an asynchronous expectation for a spec. Note that the matchers + * that are provided by an asynchronous expectation all return promises + * which must be either returned from the spec or waited for using `await` + * in order for Jasmine to associate them with the correct spec. + * @checkReturnValue see https://tsetse.info/check-return-value + * @param actual - Actual computed value to test expectations against. + */ +declare function expectAsync(actual: Promise): jasmine.AsyncMatchers; + +/** + * Explicitly mark a spec as failed. + * @param e Reason for the failure + */ +declare function fail(e?: any): void; + +/** + * Action method that should be called when the async work is complete. + */ +interface DoneFn extends Function { + (): void; + + /** fails the spec and indicates that it has completed. If the message is an Error, Error.message is used */ + fail: (message?: Error | string) => void; +} + +type Methods = { + [K in { + [K in keyof T]: T[K] extends Function ? K : never + }[keyof T]]: T[K] +}; + +/** + * Install a spy onto an existing object. + * @param object The object upon which to install the `Spy`. + * @param method The name of the method to replace with a `Spy`. + */ +declare function spyOn( + object: T, method: T[K] extends InferableFunction ? K : never, +): jasmine.Spy; + +/** + * Install a spy on a property installed with `Object.defineProperty` onto an existing object. + * @param object The object upon which to install the `Spy`. + * @param property The name of the property to replace with a `Spy`. + * @param accessType The access type (get|set) of the property to `Spy` on. + */ +declare function spyOnProperty(object: T, property: keyof T, accessType?: 'get' | 'set'): jasmine.Spy; + +/** + * Installs spies on all writable and configurable properties of an object. + * @param object The object upon which to install the `Spy`s. + */ +declare function spyOnAllFunctions(object: object): jasmine.Spy; + +declare function runs(asyncMethod: Function): void; +declare function waitsFor(latchMethod: () => boolean, failureMessage?: string, timeout?: number): void; +declare function waits(timeout?: number): void; + +declare namespace jasmine { + type Expected = T | ObjectContaining | Any | Spy; + type SpyObjMethodNames = + T extends undefined ? + (ReadonlyArray | {[methodName: string]: any}) : + (ReadonlyArray | {[P in keyof T]?: ReturnType}); + + function clock(): Clock; + + var matchersUtil: MatchersUtil; + + function any(aclass: any): Any; + + function anything(): Any; + + function arrayContaining(sample: ArrayLike): ArrayContaining; + function arrayWithExactContents(sample: ArrayLike): ArrayContaining; + function objectContaining(sample: Partial): ObjectContaining; + function createSpy(name?: string, originalFn?: Fun): Spy; + + function createSpyObj(baseName: string, methodNames: SpyObjMethodNames): any; + function createSpyObj(baseName: string, methodNames: SpyObjMethodNames): SpyObj; + + function createSpyObj(methodNames: SpyObjMethodNames): any; + function createSpyObj(methodNames: SpyObjMethodNames): SpyObj; + + function pp(value: any): string; + + function getEnv(): Env; + + function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + + function addMatchers(matchers: CustomMatcherFactories): void; + + function stringMatching(str: string | RegExp): Any; + + function formatErrorMsg(domain: string, usage: string): (msg: string) => string; + + interface Any { + (...params: any[]): any; // jasmine.Any can also be a function + new (expectedClass: any): any; + + jasmineMatches(other: any): boolean; + jasmineToString(): string; + } + + // taken from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() + interface ArrayLike { + length: number; + [n: number]: T; + } + + interface ArrayContaining { + new (sample: ArrayLike): ArrayLike; + + asymmetricMatch(other: any): boolean; + jasmineToString(): string; + } + + interface ObjectContaining { + new (sample: Partial): Partial; + + jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; + jasmineToString(): string; + } + + interface Block { + new (env: Env, func: SpecFunction, spec: Spec): any; + + execute(onComplete: () => void): void; + } + + interface WaitsBlock extends Block { + new (env: Env, timeout: number, spec: Spec): any; + } + + interface WaitsForBlock extends Block { + new (env: Env, timeout: number, latchFunction: SpecFunction, message: string, spec: Spec): any; + } + + interface Clock { + install(): void; + uninstall(): void; + /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ + tick(ms: number): void; + mockDate(date?: Date): void; + withMock(func: () => void): void; + } + + type CustomEqualityTester = (first: any, second: any) => boolean | void; + + interface CustomMatcher { + compare(actual: T, expected: T, ...args: any[]): CustomMatcherResult; + compare(actual: any, ...expected: any[]): CustomMatcherResult; + negativeCompare?(actual: T, expected: T, ...args: any[]): CustomMatcherResult; + negativeCompare?(actual: any, ...expected: any[]): CustomMatcherResult; + } + + type CustomMatcherFactory = (util: MatchersUtil, customEqualityTesters: CustomEqualityTester[]) => CustomMatcher; + + interface CustomMatcherFactories { + [index: string]: CustomMatcherFactory; + } + + interface CustomMatcherResult { + pass: boolean; + message?: string; + } + + interface MatchersUtil { + equals(a: any, b: any, customTesters?: CustomEqualityTester[]): boolean; + contains(haystack: ArrayLike | string, needle: any, customTesters?: CustomEqualityTester[]): boolean; + buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: any[]): string; + } + + interface Env { + currentSpec: Spec; + + matchersClass: Matchers; + + version(): any; + versionString(): string; + nextSpecId(): number; + addReporter(reporter: Reporter | CustomReporter): void; + execute(): void; + describe(description: string, specDefinitions: () => void): Suite; + // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these + beforeEach(beforeEachFunction: ImplementationCallback, timeout?: number): void; + beforeAll(beforeAllFunction: ImplementationCallback, timeout?: number): void; + currentRunner(): Runner; + afterEach(afterEachFunction: ImplementationCallback, timeout?: number): void; + afterAll(afterAllFunction: ImplementationCallback, timeout?: number): void; + xdescribe(desc: string, specDefinitions: () => void): XSuite; + it(description: string, func: () => void): Spec; + // iit(description: string, func: () => void): Spec; Not a part of jasmine. Angular team adds these + xit(desc: string, func: () => void): XSpec; + compareRegExps_(a: RegExp, b: RegExp, mismatchKeys: string[], mismatchValues: string[]): boolean; + compareObjects_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; + equals_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; + contains_(haystack: any, needle: any): boolean; + addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + addMatchers(matchers: CustomMatcherFactories): void; + specFilter(spec: Spec): boolean; + throwOnExpectationFailure(value: boolean): void; + seed(seed: string | number): string | number; + provideFallbackReporter(reporter: Reporter): void; + throwingExpectationFailures(): boolean; + allowRespy(allow: boolean): void; + randomTests(): boolean; + randomizeTests(b: boolean): void; + clearReporters(): void; + } + + interface FakeTimer { + new (): any; + + reset(): void; + tick(millis: number): void; + runFunctionsWithinRange(oldMillis: number, nowMillis: number): void; + scheduleFunction(timeoutKey: any, funcToCall: () => void, millis: number, recurring: boolean): void; + } + + interface HtmlReporter { + new (): any; + } + + interface HtmlSpecFilter { + new (): any; + } + + interface Result { + type: string; + } + + interface NestedResults extends Result { + description: string; + + totalCount: number; + passedCount: number; + failedCount: number; + + skipped: boolean; + + rollupCounts(result: NestedResults): void; + log(values: any): void; + getItems(): Result[]; + addResult(result: Result): void; + passed(): boolean; + } + + interface MessageResult extends Result { + values: any; + trace: Trace; + } + + interface ExpectationResult extends Result { + matcherName: string; + passed(): boolean; + expected: any; + actual: any; + message: string; + trace: Trace; + } + + interface Order { + new (options: { random: boolean, seed: string }): any; + random: boolean; + seed: string; + sort(items: T[]): T[]; + } + + namespace errors { + class ExpectationFailed extends Error { + constructor(); + + stack: any; + } + } + + interface TreeProcessor { + new (attrs: any): any; + execute: (done: Function) => void; + processTree(): any; + } + + interface Trace { + name: string; + message: string; + stack: any; + } + + interface PrettyPrinter { + new (): any; + + format(value: any): void; + iterateObject(obj: any, fn: (property: string, isGetter: boolean) => void): void; + emitScalar(value: any): void; + emitString(value: string): void; + emitArray(array: any[]): void; + emitObject(obj: any): void; + append(value: any): void; + } + + interface StringPrettyPrinter extends PrettyPrinter { + } + + interface Queue { + new (env: any): any; + + env: Env; + ensured: boolean[]; + blocks: Block[]; + running: boolean; + index: number; + offset: number; + abort: boolean; + + addBefore(block: Block, ensure?: boolean): void; + add(block: any, ensure?: boolean): void; + insertNext(block: any, ensure?: boolean): void; + start(onComplete?: () => void): void; + isRunning(): boolean; + next_(): void; + results(): NestedResults; + } + + interface Matchers { + new (env: Env, actual: T, spec: Env, isNot?: boolean): any; + + env: Env; + actual: T; + spec: Env; + isNot?: boolean; + message(): any; + + /** + * + * @param expected the actual value to be === to the expected value. + * @param expectationFailOutput + */ + toBe(expected: Expected, expectationFailOutput?: any): boolean; + + /** + * + * @param expected the actual value to be equal to the expected, using deep equality comparison. + * @param expectationFailOutput + */ + toEqual(expected: Expected, expectationFailOutput?: any): boolean; + toMatch(expected: string | RegExp, expectationFailOutput?: any): boolean; + toBeDefined(expectationFailOutput?: any): boolean; + toBeUndefined(expectationFailOutput?: any): boolean; + toBeNull(expectationFailOutput?: any): boolean; + toBeNaN(): boolean; + toBeTruthy(expectationFailOutput?: any): boolean; + toBeFalsy(expectationFailOutput?: any): boolean; + toHaveBeenCalled(): boolean; + toHaveBeenCalledBefore(expected: Spy): boolean; + toHaveBeenCalledWith(...params: any[]): boolean; + toHaveBeenCalledTimes(expected: number): boolean; + toContain(expected: any, expectationFailOutput?: any): boolean; + toBeLessThan(expected: number, expectationFailOutput?: any): boolean; + toBeLessThanOrEqual(expected: number, expectationFailOutput?: any): boolean; + toBeGreaterThan(expected: number, expectationFailOutput?: any): boolean; + toBeGreaterThanOrEqual(expected: number, expectationFailOutput?: any): boolean; + toBeCloseTo(expected: number, precision?: any, expectationFailOutput?: any): boolean; + toThrow(expected?: any): boolean; + toThrowError(message?: string | RegExp): boolean; + toThrowError(expected?: new (...args: any[]) => Error, message?: string | RegExp): boolean; + toThrowMatching(predicate: (thrown: any) => boolean): boolean; + toBeNegativeInfinity(expectationFailOutput?: any): boolean; + toBePositiveInfinity(expectationFailOutput?: any): boolean; + toHaveClass(expected: any, expectationFailOutput?: any): boolean; + + /** + * Add some context for an expect. + * @param message - Additional context to show when the matcher fails + */ + withContext(message: string): Matchers; + + not: Matchers; + + Any: Any; + } + + interface ArrayLikeMatchers extends Matchers> { + toBe(expected: Expected> | ArrayContaining, expectationFailOutput?: any): boolean; + toEqual(expected: Expected> | ArrayContaining, expectationFailOutput?: any): boolean; + toContain(expected: Expected, expectationFailOutput?: any): boolean; + not: ArrayLikeMatchers; + } + + interface NothingMatcher { + nothing(): void; + } + + interface AsyncMatchers { + /** + * Expect a promise to be resolved. + * @param expectationFailOutput + */ + toBeResolved(expectationFailOutput?: any): Promise; + + /** + * Expect a promise to be rejected. + * @param expectationFailOutput + */ + toBeRejected(expectationFailOutput?: any): Promise; + + /** + * Expect a promise to be resolved to a value equal to the expected, using deep equality comparison. + * @param expected - Value that the promise is expected to resolve to. + */ + toBeResolvedTo(expected: Expected): Promise; + + /** + * Expect a promise to be rejected with a value equal to the expected, using deep equality comparison. + * @param expected - Value that the promise is expected to be rejected with. + */ + toBeRejectedWith(expected: Expected): Promise; + + /** + * Add some context for an expect. + * @param message - Additional context to show when the matcher fails. + */ + withContext(message: string): AsyncMatchers; + + /** + * Invert the matcher following this expect. + */ + not: AsyncMatchers; + } + + interface Reporter { + reportRunnerStarting(runner: Runner): void; + reportRunnerResults(runner: Runner): void; + reportSuiteResults(suite: Suite): void; + reportSpecStarting(spec: Spec): void; + reportSpecResults(spec: Spec): void; + log(str: string): void; + } + + interface MultiReporter extends Reporter { + addReporter(reporter: Reporter): void; + } + + interface SuiteInfo { + totalSpecsDefined: number; + } + + interface CustomReportExpectation { + matcherName: string; + message: string; + passed: boolean; + stack: string; + } + + interface FailedExpectation extends CustomReportExpectation { + actual: string; + expected: string; + } + + interface PassedExpectation extends CustomReportExpectation { + } + + interface CustomReporterResult { + description: string; + failedExpectations?: FailedExpectation[]; + fullName: string; + id: string; + passedExpectations?: PassedExpectation[]; + pendingReason?: string; + status?: string; + } + + interface RunDetails { + failedExpectations: ExpectationResult[]; + order: Order; + } + + interface CustomReporter { + jasmineStarted?(suiteInfo: SuiteInfo): void; + suiteStarted?(result: CustomReporterResult): void; + specStarted?(result: CustomReporterResult): void; + specDone?(result: CustomReporterResult): void; + suiteDone?(result: CustomReporterResult): void; + jasmineDone?(runDetails: RunDetails): void; + } + + interface Runner { + new (env: Env): any; + + execute(): void; + beforeEach(beforeEachFunction: SpecFunction): void; + afterEach(afterEachFunction: SpecFunction): void; + beforeAll(beforeAllFunction: SpecFunction): void; + afterAll(afterAllFunction: SpecFunction): void; + finishCallback(): void; + addSuite(suite: Suite): void; + add(block: Block): void; + specs(): Spec[]; + suites(): Suite[]; + topLevelSuites(): Suite[]; + results(): NestedResults; + } + + type SpecFunction = (spec?: Spec) => void; + + interface SuiteOrSpec { + id: number; + env: Env; + description: string; + queue: Queue; + } + + interface Spec extends SuiteOrSpec { + new (env: Env, suite: Suite, description: string): any; + + suite: Suite; + + afterCallbacks: SpecFunction[]; + spies_: Spy[]; + + results_: NestedResults; + matchersClass: Matchers; + + getFullName(): string; + results(): NestedResults; + log(arguments: any): any; + runs(func: SpecFunction): Spec; + addToQueue(block: Block): void; + addMatcherResult(result: Result): void; + getResult(): any; + expect(actual: any): any; + waits(timeout: number): Spec; + waitsFor(latchFunction: SpecFunction, timeoutMessage?: string, timeout?: number): Spec; + fail(e?: any): void; + getMatchersClass_(): Matchers; + addMatchers(matchersPrototype: CustomMatcherFactories): void; + finishCallback(): void; + finish(onComplete?: () => void): void; + after(doAfter: SpecFunction): void; + execute(onComplete?: () => void, enabled?: boolean): any; + addBeforesAndAftersToQueue(): void; + explodes(): void; + spyOn(obj: any, methodName: string, ignoreMethodDoesntExist: boolean): Spy; + spyOnProperty(object: any, property: string, accessType?: 'get' | 'set'): Spy; + spyOnAllFunctions(object: any): Spy; + + removeAllSpies(): void; + throwOnExpectationFailure: boolean; + } + + interface XSpec { + id: number; + runs(): void; + } + + interface Suite extends SuiteOrSpec { + new (env: Env, description: string, specDefinitions: () => void, parentSuite: Suite): any; + + parentSuite: Suite; + + getFullName(): string; + finish(onComplete?: () => void): void; + beforeEach(beforeEachFunction: SpecFunction): void; + afterEach(afterEachFunction: SpecFunction): void; + beforeAll(beforeAllFunction: SpecFunction): void; + afterAll(afterAllFunction: SpecFunction): void; + results(): NestedResults; + add(suiteOrSpec: SuiteOrSpec): void; + specs(): Spec[]; + suites(): Suite[]; + children(): any[]; + execute(onComplete?: () => void): void; + } + + interface XSuite { + execute(): void; + } + + interface Spy { + (...params: any[]): any; + + and: SpyAnd; + calls: Calls; + withArgs(...args: any[]): Spy; + } + + type SpyObj = T & { + [k in keyof T]: T[k] extends InferableFunction ? T[k] & Spy : T[k]; + }; + + interface SpyAnd { + identity: string; + + /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ + callThrough(): Spy; + /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ + returnValue(val: ReturnType): Spy; + /** By chaining the spy with and.returnValues, all calls to the function will return specific values in order until it reaches the end of the return values list. */ + returnValues(...values: Array>): Spy; + /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ + callFake(fn: Fun): Spy; + /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ + throwError(msg: string): Spy; + /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ + stub(): Spy; + } + + interface Calls { + /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. */ + any(): boolean; + /** By chaining the spy with calls.count(), will return the number of times the spy was called */ + count(): number; + /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index */ + argsFor(index: number): Parameters; + /** By chaining the spy with calls.allArgs(), will return the arguments to all calls */ + allArgs(): Array>; + /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls */ + all(): Array>; + /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call */ + mostRecent(): CallInfo; + /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call */ + first(): CallInfo; + /** By chaining the spy with calls.reset(), will clears all tracking for a spy */ + reset(): void; + } + + interface CallInfo { + /** The context (the this) for the call */ + object: any; + /** All arguments passed to the call */ + args: Parameters; + /** The return value of the call */ + returnValue: ReturnType; + } + + interface Util { + inherit(childClass: Function, parentClass: Function): any; + formatException(e: any): any; + htmlEscape(str: string): string; + argsToArray(args: any): any; + extend(destination: any, source: any): any; + } + + interface JsApiReporter extends Reporter { + started: boolean; + finished: boolean; + result: any; + messages: any; + runDetails: RunDetails; + + new (): any; + + suites(): Suite[]; + summarize_(suiteOrSpec: SuiteOrSpec): any; + results(): any; + resultsForSpec(specId: any): any; + log(str: any): any; + resultsForSpecs(specIds: any): any; + summarizeResult_(result: any): any; + } + + interface Jasmine { + Spec: Spec; + clock: Clock; + util: Util; + } + + var HtmlReporter: HtmlReporter; + var HtmlSpecFilter: HtmlSpecFilter; + + /** + * Default number of milliseconds Jasmine will wait for an asynchronous spec to complete. + */ + var DEFAULT_TIMEOUT_INTERVAL: number; + + /** + * Maximum number of array elements to display when pretty printing objects. + * This will also limit the number of keys and values displayed for an object. + * Elements past this number will be ellipised. + */ + var MAX_PRETTY_PRINT_ARRAY_LENGTH: number; + + /** + * Maximum number of charasters to display when pretty printing objects. + * Characters past this number will be ellipised. + */ + var MAX_PRETTY_PRINT_CHARS: number; + + /** + * Maximum object depth the pretty printer will print to. + * Set this to a lower value to speed up pretty printing if you have large objects. + */ + var MAX_PRETTY_PRINT_DEPTH: number; +} + +declare module "jasmine" { + class jasmine { + constructor(options: any); + jasmine: jasmine.Jasmine; + addMatchers(matchers: jasmine.CustomMatcherFactories): void; + addReporter(reporter: jasmine.Reporter): void; + addSpecFile(filePath: string): void; + addSpecFiles(files: string[]): void; + configureDefaultReporter(options: any, ...args: any[]): void; + execute(files?: string[], filterString?: string): any; + exitCodeCompletion(passed: any): void; + loadConfig(config: any): void; + loadConfigFile(configFilePath: any): void; + loadHelpers(): void; + loadSpecs(): void; + onComplete(onCompleteCallback: (passed: boolean) => void): void; + provideFallbackReporter(reporter: jasmine.Reporter): void; + randomizeTests(value?: any): boolean; + seed(value: any): void; + showColors(value: any): void; + stopSpecOnExpectationFailure(value: any): void; + static ConsoleReporter(): any; + env: jasmine.Env; + reportersCount: number; + completionReporter: jasmine.CustomReporter; + reporter: jasmine.CustomReporter; + coreVersion(): string; + showingColors: boolean; + projectBaseDir: string; + printDeprecation(): void; + specFiles: string[]; + helperFiles: string[]; + } + export = jasmine; +} diff --git a/types/jasmine/ts3.1/jasmine-tests.ts b/types/jasmine/ts3.1/jasmine-tests.ts new file mode 100644 index 0000000000..92c2a87494 --- /dev/null +++ b/types/jasmine/ts3.1/jasmine-tests.ts @@ -0,0 +1,1358 @@ +// tests based on http://jasmine.github.io/2.2/introduction.html + +describe("A suite", () => { + it("contains spec with an expectation", () => { + expect(true).toBe(true); + }); +}); + +describe("A suite is just a function", () => { + var a: boolean; + + it("and so is a spec", () => { + a = true; + expect(a).toBe(true); + }); +}); + +describe("The 'toBe' matcher compares with ===", () => { + it("and has a positive case", () => { + expect(true).toBe(true); + }); + + it("and can have a negative case", () => { + expect(false).not.toBe(true); + }); +}); + +describe("Included matchers:", () => { + it("The 'toBe' matcher compares with ===", () => { + const a = 12; + const b = a; + + expect(a).toBe(b); + expect(a).not.toBe(24); + }); + + describe("The 'toEqual' matcher", () => { + it("works for simple literals and variables", () => { + const a = 12; + expect(a).toEqual(12); + }); + + it("should work for objects", () => { + const foo = { + a: 12, + b: 34 + }; + const bar = { + a: 12, + b: 34 + }; + expect(foo).toEqual(bar); + }); + + it("should work for optional values", () => { + const opt: string | undefined = Math.random() > .5 ? "s" : undefined; + expect(opt).toEqual(undefined); + }); + }); + + it("The 'toMatch' matcher is for regular expressions", () => { + const message = "foo bar baz"; + + expect(message).toMatch(/bar/); + expect(message).toMatch("bar"); + expect(message).not.toMatch(/quux/); + }); + + it("The 'toBeDefined' matcher compares against `undefined`", () => { + const a = { + foo: "foo" + }; + + expect(a.foo).toBeDefined(); + expect((a as any).bar).not.toBeDefined(); + }); + + it("The `toBeUndefined` matcher compares against `undefined`", () => { + const a = { + foo: "foo" + }; + + expect(a.foo).not.toBeUndefined(); + expect((a as any).bar).toBeUndefined(); + }); + + it("The 'toBeNull' matcher compares against null", () => { + const a: string | null = Math.random() > 0.5 ? "s" : null; + const foo = "foo"; + + expect(null).toBeNull(); + expect(a).toBeNull(); + expect(foo).not.toBeNull(); + }); + + it("The 'toBeTruthy' matcher is for boolean casting testing", () => { + const a: string | undefined = Math.random() > 0.5 ? "s" : undefined; + const foo = "foo"; + + expect(foo).toBeTruthy(); + expect(a).not.toBeTruthy(); + }); + + it("The 'toBeFalsy' matcher is for boolean casting testing", () => { + const a: string | undefined = Math.random() > 0.5 ? "s" : undefined; + const foo = "foo"; + + expect(a).toBeFalsy(); + expect(foo).not.toBeFalsy(); + }); + + it("The 'toContain' matcher is for finding an item in an Array", () => { + const a = ["foo", "bar", "baz"]; + + expect(a).toContain('foo'); + expect(a).not.toContain("quux"); + }); + + it("The 'toContain' matcher is also for finding an object containing distinct properties in an Array", () => { + const a = [{ a: "foo" }, { a: "bar" }, { b: "baz" }]; + + expect(a).toContain(jasmine.objectContaining({ a: "foo" })); + expect(a).not.toContain({ a: "quux" }); + }); + + it("The 'toBeLessThan' matcher is for mathematical comparisons", () => { + const pi = 3.1415926; + const e = 2.78; + + expect(e).toBeLessThan(pi); + expect(pi).not.toBeLessThan(e); + }); + + it("The 'toBeGreaterThan' is for mathematical comparisons", () => { + const pi = 3.1415926; + const e = 2.78; + + expect(pi).toBeGreaterThan(e); + expect(e).not.toBeGreaterThan(pi); + }); + + it("The 'toBeCloseTo' matcher is for precision math comparison", () => { + const pi = 3.1415926; + const e = 2.78; + + expect(pi).not.toBeCloseTo(e, 2); + expect(pi).toBeCloseTo(e, 0); + }); + + it("The 'toThrow' matcher is for testing if a function throws an exception", () => { + const foo = () => { + return 1 + 2; + }; + const bar = () => { + throw new Error("message"); + }; + + expect(foo).not.toThrow(); + expect(foo).toThrow(); + + expect(bar).not.toThrow(); + expect(bar).toThrow(); + }); + + it("The 'toThrowError' matcher is for testing a specific thrown exception", () => { + const foo = () => { + throw new TypeError("foo bar baz"); + }; + + expect(foo).toThrowError("foo bar baz"); + expect(foo).toThrowError(/bar/); + expect(foo).toThrowError(TypeError); + expect(foo).toThrowError(TypeError, "foo bar baz"); + }); + + it("async matchers", async () => { + const badness = new Error("badness"); + await expectAsync(Promise.resolve()).toBeResolved(); + await expectAsync(Promise.resolve()).toBeResolved("good job"); + await expectAsync(Promise.resolve(true)).toBeResolvedTo(true); + await expectAsync(Promise.reject(badness)).toBeRejected(); + await expectAsync(Promise.reject(badness)).toBeRejected("bad mojo"); + await expectAsync(Promise.reject(badness)).toBeRejectedWith(badness); + await expectAsync(Promise.resolve()).withContext("additional info").toBeResolved(); + }); + + it("async matchers - not", async () => { + const badness = new Error("badness"); + const malady = new Error("malady"); + await expectAsync(Promise.reject(badness)).not.toBeResolved(); + await expectAsync(Promise.resolve(true)).not.toBeResolvedTo(false); + await expectAsync(Promise.resolve()).not.toBeRejected(); + await expectAsync(Promise.reject(badness)).not.toBeRejectedWith(malady); + await expectAsync(Promise.reject(badness)).not.withContext("additional info").toBeResolved(); + await expectAsync(Promise.reject(badness)).withContext("additional info").not.toBeResolved(); + }); +}); + +describe("toThrowMatching", () => { + expect(() => { + ({} as any).doSomething(); + }).toThrowMatching(error => error !== undefined); +}); + +describe("toBeNegativeInfinity", () => { + expect("").toBeNegativeInfinity(); +}); + +describe("toBePositiveInfinity", () => { + expect("").toBePositiveInfinity(); +}); + +describe("toHaveClass", () => { + expect("").toHaveClass(Array); +}); + +describe("A spec", () => { + it("is just a function, so it can contain any code", () => { + var foo = 0; + foo += 1; + + expect(foo).toEqual(1); + }); + + it("can have more than one expectation", () => { + var foo = 0; + foo += 1; + + expect(foo).toEqual(1); + expect(true).toEqual(true); + }); +}); + +describe("A spec (with setup and tear-down)", () => { + var foo: number; + + beforeEach(() => { + foo = 0; + foo += 1; + }); + + afterEach(() => { + foo = 0; + }); + + it("is just a function, so it can contain any code", () => { + expect(foo).toEqual(1); + }); + + it("can have more than one expectation", () => { + expect(foo).toEqual(1); + expect(true).toEqual(true); + }); +}); + +describe("A spec", () => { + var foo: number; + + beforeEach(() => { + foo = 0; + foo += 1; + }); + + afterEach(() => { + foo = 0; + }); + + it("is just a function, so it can contain any code", () => { + expect(foo).toEqual(1); + }); + + it("can have more than one expectation", () => { + expect(foo).toEqual(1); + expect(true).toEqual(true); + }); + + describe("nested inside a second describe", () => { + var bar: number; + + beforeEach(() => { + bar = 1; + }); + + it("can reference both scopes as needed", () => { + expect(foo).toEqual(bar); + }); + }); +}); + +describe("withContext", () => { + it("can be used after an expectation", () => { + expect(1).withContext('context message').toBe(1); + }); +}); + +xdescribe("A spec", () => { + var foo: number; + + beforeEach(() => { + foo = 0; + foo += 1; + }); + + it("is just a function, so it can contain any code", () => { + expect(foo).toEqual(1); + }); +}); + +describe("Pending specs", () => { + xit("can be declared 'xit'", () => { + expect(true).toBe(false); + }); + + it("can be declared with 'it' but without a function"); + + it("can be declared by calling 'pending' in the spec body", () => { + expect(true).toBe(false); + pending(); // without reason + pending('this is why it is pending'); + }); +}); + +describe("A spy", () => { + var foo: any, bar: any, baz: any = null; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + }, + setBaz: (value: any) => { + baz = value; + } + }; + + spyOn(foo, 'setBar'); + spyOn(foo, 'setBaz'); + + foo.setBar(123); + foo.setBar(456, 'another param'); + foo.setBaz(789); + }); + + it("tracks that the spy was called", () => { + expect(foo.setBar).toHaveBeenCalled(); + }); + + it("tracks all the arguments of its calls", () => { + expect(foo.setBar).toHaveBeenCalledWith(123); + expect(foo.setBar).toHaveBeenCalledWith(456, 'another param'); + }); + + it("tracks the order in which spies were called", () => { + expect(foo.setBar).toHaveBeenCalledBefore(foo.setBaz); + }); + + it("stops all execution on a function", () => { + expect(bar).toBeNull(); + }); + + it("tracks if it was called at all", function() { + foo.setBar(); + + expect(foo.setBar.calls.any()).toEqual(true); + }); +}); + +describe("A spy, when configured to call through", () => { + var foo: any, bar: any, fetchedBar: any; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + }, + getBar: () => { + return bar; + } + }; + + spyOn(foo, 'getBar').and.callThrough(); + + foo.setBar(123); + fetchedBar = foo.getBar(); + }); + + it("tracks that the spy was called", () => { + expect(foo.getBar).toHaveBeenCalled(); + }); + + it("should not effect other functions", () => { + expect(bar).toEqual(123); + }); + + it("when called returns the requested value", () => { + expect(fetchedBar).toEqual(123); + }); +}); + +describe("A spy, when configured to fake a return value", () => { + var foo: any, bar: any, fetchedBar: any; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + }, + getBar: () => { + return bar; + } + }; + + spyOn(foo, "getBar").and.returnValue(745); + + foo.setBar(123); + fetchedBar = foo.getBar(); + }); + + it("tracks that the spy was called", () => { + expect(foo.getBar).toHaveBeenCalled(); + }); + + it("should not effect other functions", () => { + expect(bar).toEqual(123); + }); + + it("when called returns the requested value", () => { + expect(fetchedBar).toEqual(745); + }); +}); + +describe("A spy, when configured to fake a series of return values", () => { + var foo: any, bar: any; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + }, + getBar: () => { + return bar; + } + }; + + spyOn(foo, "getBar").and.returnValues("fetched first", "fetched second"); + + foo.setBar(123); + }); + + it("tracks that the spy was called", () => { + foo.getBar(123); + expect(foo.getBar).toHaveBeenCalled(); + }); + + it("should not affect other functions", () => { + expect(bar).toEqual(123); + }); + + it("when called multiple times returns the requested values in order", () => { + expect(foo.getBar()).toEqual("fetched first"); + expect(foo.getBar()).toEqual("fetched second"); + expect(foo.getBar()).toBeUndefined(); + }); +}); + +describe("A spy, when configured with an alternate implementation", () => { + var foo: any, bar: any, fetchedBar: any; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + }, + getBar: () => { + return bar; + } + }; + + spyOn(foo, "getBar").and.callFake(() => { + return 1001; + }); + + foo.setBar(123); + fetchedBar = foo.getBar(); + }); + + it("tracks that the spy was called", () => { + expect(foo.getBar).toHaveBeenCalled(); + }); + + it("should not effect other functions", () => { + expect(bar).toEqual(123); + }); + + it("when called returns the requested value", () => { + expect(fetchedBar).toEqual(1001); + }); +}); + +describe("A spy, when configured with alternate implementations for specified arguments", () => { + var foo: any, bar: any, fetchedBar: any; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + }, + getBar: () => { + return bar; + } + }; + + spyOn(foo, "getBar") + .withArgs(1, "2") + .and.callFake(() => 1002); + + foo.setBar(123); + fetchedBar = foo.getBar(1, "2"); + }); + + it("tracks that the spy was called", () => { + expect(foo.getBar).toHaveBeenCalled(); + }); + + it("should not effect other functions", () => { + expect(bar).toEqual(123); + }); + + it("when called returns the requested value", () => { + expect(fetchedBar).toEqual(1002); + }); +}); + +describe("A spy, when configured to throw a value", () => { + var foo: any, bar: any; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + } + }; + + spyOn(foo, "setBar").and.throwError("quux"); + }); + + it("throws the value", () => { + expect(() => { + foo.setBar(123); + }).toThrowError("quux"); + }); +}); + +describe("A spy, when configured with multiple actions", () => { + var foo: any, bar: any, fetchedBar: any; + var fakeCalled = false; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + }, + getBar: () => { + return bar; + } + }; + + spyOn(foo, 'getBar').and.callThrough().and.callFake(() => { + fakeCalled = true; + }); + + foo.setBar(123); + fetchedBar = foo.getBar(); + }); + + it("tracks that the spy was called", () => { + expect(foo.getBar).toHaveBeenCalled(); + }); + + it("should not effect other functions", () => { + expect(bar).toEqual(123); + }); + + it("when called returns the requested value", () => { + expect(fetchedBar).toEqual(123); + }); + + it("should have called the fake implementation", () => { + expect(fakeCalled).toEqual(true); + }); +}); + +describe("A spy", () => { + var foo: any, bar: any = null; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + } + }; + + spyOn(foo, 'setBar').and.callThrough(); + }); + + it("can call through and then stub in the same spec", () => { + foo.setBar(123); + expect(bar).toEqual(123); + + foo.setBar.and.stub(); + bar = null; + + foo.setBar(123); + expect(bar).toBe(null); + }); +}); + +describe("A spy", () => { + var foo: any, bar: any = null; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + } + }; + + spyOn(foo, 'setBar'); + }); + + it("tracks if it was called at all", () => { + expect(foo.setBar.calls.any()).toEqual(false); + + foo.setBar(); + + expect(foo.setBar.calls.any()).toEqual(true); + }); + + it("tracks the number of times it was called", () => { + expect(foo.setBar.calls.count()).toEqual(0); + + foo.setBar(); + foo.setBar(); + + expect(foo.setBar.calls.count()).toEqual(2); + }); + + it("tracks the arguments of each call", () => { + foo.setBar(123); + foo.setBar(456, "baz"); + + expect(foo.setBar.calls.argsFor(0)).toEqual([123]); + expect(foo.setBar.calls.argsFor(1)).toEqual([456, "baz"]); + }); + + it("tracks the arguments of all calls", () => { + foo.setBar(123); + foo.setBar(456, "baz"); + + expect(foo.setBar.calls.allArgs()).toEqual([[123], [456, "baz"]]); + }); + + it("can provide the context and arguments to all calls", () => { + foo.setBar(123); + + expect(foo.setBar.calls.all()).toEqual([{ object: foo, args: [123], returnValue: undefined }]); + }); + + it("has a shortcut to the most recent call", () => { + foo.setBar(123); + foo.setBar(456, "baz"); + + expect(foo.setBar.calls.mostRecent()).toEqual({ object: foo, args: [456, "baz"], returnValue: undefined }); + }); + + it("has a shortcut to the first call", () => { + foo.setBar(123); + foo.setBar(456, "baz"); + + expect(foo.setBar.calls.first()).toEqual({ object: foo, args: [123], returnValue: undefined }); + }); + + it("can be reset", () => { + foo.setBar(123); + foo.setBar(456, "baz"); + + expect(foo.setBar.calls.any()).toBe(true); + + foo.setBar.calls.reset(); + + expect(foo.setBar.calls.any()).toBe(false); + }); +}); + +describe("A spy, when created manually", () => { + var whatAmI: any; + + beforeEach(() => { + whatAmI = jasmine.createSpy('whatAmI'); + + whatAmI("I", "am", "a", "spy"); + }); + + it("is named, which helps in error reporting", () => { + expect(whatAmI.and.identity()).toEqual('whatAmI'); + }); + + it("tracks that the spy was called", () => { + expect(whatAmI).toHaveBeenCalled(); + }); + + it("tracks its number of calls", () => { + expect(whatAmI.calls.count()).toEqual(1); + }); + + it("tracks all the arguments of its calls", () => { + expect(whatAmI).toHaveBeenCalledWith("I", "am", "a", "spy"); + }); + + it("allows access to the most recent call", () => { + expect(whatAmI.calls.mostRecent().args[0]).toEqual("I"); + }); +}); + +describe("Multiple spies, when created manually", () => { + class Tape { + private rewindTo: number; + play(): void { } + pause(): void { } + rewind(pos: number): void { + this.rewindTo = pos; + } + stop(): void { } + readonly isPlaying: boolean; // spy obj makes this writable + } + + var tape: Tape; + var tapeSpy: jasmine.SpyObj; + var el: jasmine.SpyObj; + + beforeEach(() => { + tapeSpy = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']); + tape = tapeSpy; + (tape as { isPlaying: boolean }).isPlaying = false; + el = jasmine.createSpyObj('Element', ['hasAttribute']); + + el.hasAttribute.and.returnValue(false); + el.hasAttribute("href"); + + tape.play(); + tape.pause(); + tape.rewind(0); + + tapeSpy.play.and.callThrough(); + tapeSpy.pause.and.callThrough(); + tapeSpy.rewind.and.callThrough(); + }); + + it("creates spies for each requested function", () => { + expect(tape.play).toBeDefined(); + expect(tape.pause).toBeDefined(); + expect(tape.stop).toBeDefined(); + expect(tape.rewind).toBeDefined(); + }); + + it("tracks that the spies were called", () => { + expect(tape.play).toHaveBeenCalled(); + expect(tape.pause).toHaveBeenCalled(); + expect(tape.rewind).toHaveBeenCalled(); + expect(tape.stop).not.toHaveBeenCalled(); + }); + + it("tracks all the arguments of its calls", () => { + expect(tape.rewind).toHaveBeenCalledWith(0); + }); + + it("read isPlaying property", () => { + expect(tape.isPlaying).toBe(false); + }); +}); + +describe("multiple spies, when created with spyOnAllFunctions", () => { + it("spies on all functions", () => { + const obj = { + x: (a: number) => a, + y: (a: number) => a, + }; + + spyOnAllFunctions(obj); + + obj.x(0); + obj.y(1); + + expect(obj.x).toHaveBeenCalled(); + expect(obj.y).toHaveBeenCalledWith(1); + }); +}); + +describe("jasmine.nothing", () => { + it("matches any value", () => { + expect().nothing(); + }); +}); + +describe("jasmine.any", () => { + it("matches any value", () => { + expect({}).toEqual(jasmine.any(Object)); + expect(12).toEqual(jasmine.any(Number)); + }); + + it("matches any function", () => { + interface Test { + fn1(): void; + fn2(param1: number): number; + } + + const a: Test = { + fn1: () => { }, + fn2: (param1: number) => param1, + }; + + const expected: Test = { + fn1: jasmine.any(Function), + fn2: jasmine.any(Function), + }; + + expect(a).toEqual(expected); + }); + + describe("when used with a spy", () => { + it("is useful for comparing arguments", () => { + const foo = jasmine.createSpy('foo'); + foo(12, () => { + return true; + }); + + expect(foo).toHaveBeenCalledWith(jasmine.any(Number), jasmine.any(Function)); + }); + }); +}); + +describe("jasmine.objectContaining", () => { + interface fooType { + a: number; + b: number; + bar: string; + } + var foo: fooType; + + beforeEach(() => { + foo = { + a: 1, + b: 2, + bar: "baz" + }; + }); + + it("matches objects with the expect key/value pairs", () => { + // not explictly providing the type on objectContaining only guards against + // missmatching types on know properties + expect(foo).not.toEqual(jasmine.objectContaining({ + a: 37, + foo: 2, // <-- this does not cause an error as the compiler cannot infer the type completely + // b: '123', <-- this would cause an error as `b` defined as number in fooType + })); + + // explictly providing the type on objectContaining makes the guard more precise + // as misspelled properties are detected as well + expect(foo).not.toEqual(jasmine.objectContaining({ + bar: '', + // foo: 1, <-- this would cause an error as `foo` is not defined in fooType + })); + }); + + describe("when used with a spy", () => { + it("is useful for comparing arguments", () => { + const callback = jasmine.createSpy('callback'); + + callback({ + bar: "baz" + }); + + expect(callback).toHaveBeenCalledWith(jasmine.objectContaining({ + bar: "baz" + })); + expect(callback).not.toHaveBeenCalledWith(jasmine.objectContaining({ + c: 37 + })); + }); + }); +}); + +describe("jasmine.arrayContaining", () => { + var foo: number[]; + + beforeEach(() => { + foo = [1, 2, 3, 4]; + }); + + it("matches arrays with some of the values", () => { + expect(foo).toEqual(jasmine.arrayContaining([3, 1])); + expect(foo).not.toEqual(jasmine.arrayContaining([6])); + + expect(foo).toBe(jasmine.arrayContaining([3, 1])); + expect(foo).not.toBe(jasmine.arrayContaining([6])); + }); + + describe("when used with a spy", () => { + it("is useful when comparing arguments", () => { + const callback = jasmine.createSpy('callback'); + + callback([1, 2, 3, 4]); + + expect(callback).toHaveBeenCalledWith(jasmine.arrayContaining([4, 2, 3])); + expect(callback).not.toHaveBeenCalledWith(jasmine.arrayContaining([5, 2])); + }); + }); +}); + +describe("jasmine.arrayWithExactContents", () => { + var foo: number[]; + + beforeEach(() => { + foo = [1, 2, 3, 4]; + }); + + it("matches arrays with exactly the same values", () => { + expect(foo).toEqual(jasmine.arrayWithExactContents([1, 2, 3, 4])); + expect(foo).not.toEqual(jasmine.arrayWithExactContents([6])); + + expect(foo).toBe(jasmine.arrayWithExactContents([1, 2, 3, 4])); + expect(foo).not.toBe(jasmine.arrayWithExactContents([6])); + }); + + describe("when used with a spy", () => { + it("is useful when comparing arguments", () => { + const callback = jasmine.createSpy('callback'); + + callback([1, 2, 3, 4]); + + expect(callback).toHaveBeenCalledWith(jasmine.arrayWithExactContents([1, 2, 3, 4])); + expect(callback).not.toHaveBeenCalledWith(jasmine.arrayWithExactContents([5, 2])); + }); + }); +}); + +describe("Manually ticking the Jasmine Clock", () => { + var timerCallback: any; + + beforeEach(() => { + timerCallback = jasmine.createSpy("timerCallback"); + jasmine.clock().install(); + }); + + afterEach(() => { + jasmine.clock().uninstall(); + }); + + it("causes a timeout to be called synchronously", () => { + setTimeout(() => { + timerCallback(); + }, 100); + + expect(timerCallback).not.toHaveBeenCalled(); + + jasmine.clock().tick(101); + + expect(timerCallback).toHaveBeenCalled(); + }); + + it("causes an interval to be called synchronously", () => { + setInterval(() => { + timerCallback(); + }, 100); + + expect(timerCallback).not.toHaveBeenCalled(); + + jasmine.clock().tick(101); + expect(timerCallback.calls.count()).toEqual(1); + + jasmine.clock().tick(50); + expect(timerCallback.calls.count()).toEqual(1); + + jasmine.clock().tick(50); + expect(timerCallback.calls.count()).toEqual(2); + }); + + describe("Mocking the Date object", () => { + it("mocks the Date object and sets it to a given time", () => { + const baseTime = new Date(2013, 9, 23); + + jasmine.clock().mockDate(baseTime); + + jasmine.clock().tick(50); + expect(new Date().getTime()).toEqual(baseTime.getTime() + 50); + }); + }); +}); + +describe("Asynchronous specs", () => { + var value: number; + beforeEach((done: DoneFn) => { + setTimeout(() => { + value = 0; + done(); + }, 1); + }); + + it("should support async execution of test preparation and expectations", (done: DoneFn) => { + value += 1; + expect(value).toBeGreaterThan(0); + done(); + }); + + describe("long asynchronous specs", () => { + beforeEach((done: DoneFn) => { + done(); + }, 1000); + + it("takes a long time", (done: DoneFn) => { + setTimeout(() => { + done(); + }, 9000); + }, 10000); + + afterEach((done: DoneFn) => { + done(); + }, 1000); + }); +}); + +describe("Fail", () => { + it("should fail test when called without arguments", () => { + fail(); + }); + + it("should fail test when called with a fail message", () => { + fail("The test failed"); + }); + + it("should fail test when called an error", () => { + fail(new Error("The test failed with this error")); + }); +}); + +// test based on http://jasmine.github.io/2.2/custom_equality.html +describe("custom equality", () => { + const myCustomEquality: jasmine.CustomEqualityTester = function(first: any, second: any): boolean | void { + if (typeof first === "string" && typeof second === "string") { + return first[0] === second[1]; + } + }; + + beforeEach(() => { + jasmine.addCustomEqualityTester(myCustomEquality); + }); + + it("should be custom equal", () => { + expect("abc").toEqual("aaa"); + }); + + it("should be custom not equal", () => { + expect("abc").not.toEqual("abc"); + }); +}); + +// test based on http://jasmine.github.io/2.2/custom_matcher.html +var customMatchers: jasmine.CustomMatcherFactories = { + toBeGoofy: (util: jasmine.MatchersUtil, customEqualityTesters: jasmine.CustomEqualityTester[]) => { + return { + compare: (actual: any, expected: any): jasmine.CustomMatcherResult => { + if (expected === undefined) { + expected = ''; + } + const result: jasmine.CustomMatcherResult = { pass: false }; + + result.pass = util.equals(actual.hyuk, "gawrsh" + expected, customEqualityTesters); + + result.message = result.pass ? + `Expected ${actual} not to be quite so goofy` : + `Expected ${actual} to be goofy, but it was not very goofy`; + + return result; + } + }; + }, + toBeWithinRange: (util: jasmine.MatchersUtil, customEqualityTesters: jasmine.CustomEqualityTester[]) => { + return { + compare: (actual: any, floor: number, ceiling: number): jasmine.CustomMatcherResult => { + const pass = actual >= floor && actual <= ceiling; + const message = `expected ${actual} to be within range ${floor}-${ceiling}`; + return { message, pass }; + }, + + negativeCompare: (actual: any, floor: number, ceiling: number): jasmine.CustomMatcherResult => { + const pass = actual < floor && actual > ceiling; + const message = `expected ${actual} not to be within range ${floor}-${ceiling}`; + return { message, pass }; + } + }; + } +}; +// add the custom matchers to interface jasmine.Matchers via TypeScript declaration merging +// if your test files import or export anything, you'll want to use: +// declare global { +// namespace jasmine { +// interface Matchers { +// ... +// } +// } +// } +declare namespace jasmine { + interface Matchers { + toBeGoofy(expected?: Expected): boolean; + toBeWithinRange(expected?: Expected, floor?: number, ceiling?: number): boolean; + } +} + +describe("Custom matcher: 'toBeGoofy'", () => { + beforeEach(() => { + jasmine.addMatchers(customMatchers); + }); + + it("is available on an expectation", () => { + expect({ + hyuk: 'gawrsh' + }).toBeGoofy(); + }); + + it("can take an 'expected' parameter", () => { + expect({ + hyuk: 'gawrsh is fun' + }).toBeGoofy({ hyuk: ' is fun' }); + }); + + it("can take many 'expected' parameters", () => { + expect(2).toBeWithinRange(1, 3); + }); + + it("can use the custom negativeCompare method", () => { + const matcher = customMatchers["toBeWithinRange"](jasmine.matchersUtil, []); + const result = matcher.negativeCompare!(1, 2, 3); + + expect(result.pass).toBe(false); + expect(result.message).toBe("expected 1 not to be within range 2-3"); + }); + + it("can be negated", () => { + expect({ + hyuk: 'this is fun' + }).not.toBeGoofy(); + }); + + it("has a proper message on failure", () => { + const actual = { hyuk: 'this is fun' }; + + const matcher = customMatchers["toBeGoofy"](jasmine.matchersUtil, []); + const result = matcher.compare(actual, null); + + expect(result.pass).toBe(false); + expect(result.message).toBe(`Expected ${actual} to be goofy, but it was not very goofy`); + }); +}); + +describe('better typed spys', () => { + describe('a typed spy', () => { + const spy = jasmine.createSpy('spy', (num: number, str: string) => { + return `${num} and ${str}`; + }); + it('has a typed returnValue', () => { + // $ExpectType (val: string) => Spy<(num: number, str: string) => string> + spy.and.returnValue; + }); + it('has a typed calls property', () => { + spy.calls.first().args; // $ExpectType [number, string] + spy.calls.first().returnValue; // $ExpectType string + }); + it('has a typed callFake', () => { + // $ExpectType (fn: (num: number, str: string) => string) => Spy<(num: number, str: string) => string> + spy.and.callFake; + }); + }); + describe('spyOn', () => { + it('only works on methods', () => { + const foo = { + method() { + return 'baz'; + }, + value: 'value', + }; + const spy = spyOn(foo, 'method'); + const spy2 = spyOn(foo, 'value'); // $ExpectError + + // $ExpectType string + spy.calls.first().returnValue; + }); + it('can allows overriding the generic', () => { + class Base { + service() {} + } + class Super extends Base { + service2() {} + } + spyOn(new Super(), 'service'); + spyOn(new Super(), 'service2'); // $ExpectError + }); + }); + describe('createSpyObj', () => { + it('returns the correct spy types', () => { + const foo = { + method() { + return 'baz'; + }, + value: 'value', + }; + const spyObj = jasmine.createSpyObj('foo', ['method']); + + // $ExpectType (val: string) => Spy<() => string> + spyObj.method.and.returnValue; + }); + }); +}); + +// test based on http://jasmine.github.io/2.5/custom_reporter.html +var myReporter: jasmine.CustomReporter = { + jasmineStarted: (suiteInfo: jasmine.SuiteInfo) => { + console.log("Running suite with " + suiteInfo.totalSpecsDefined); + }, + + suiteStarted: (result: jasmine.CustomReporterResult) => { + console.log(`Suite started: ${result.description} whose full description is: ${result.fullName}`); + }, + + specStarted: (result: jasmine.CustomReporterResult) => { + console.log(`Spec started: ${result.description} whose full description is: ${result.fullName}`); + }, + + specDone: (result: jasmine.CustomReporterResult) => { + console.log(`Spec: ${result.description} was ${result.status}`); + // tslint:disable-next-line:prefer-for-of + for (var i = 0; result.failedExpectations && i < result.failedExpectations.length; i += 1) { + console.log("Failure: " + result.failedExpectations[i].message); + console.log("Actual: " + result.failedExpectations[i].actual); + console.log("Expected: " + result.failedExpectations[i].expected); + console.log(result.failedExpectations[i].stack); + } + console.log(result.passedExpectations && result.passedExpectations.length); + }, + + suiteDone: (result: jasmine.CustomReporterResult) => { + console.log(`Suite: ${result.description} was ${result.status}`); + // tslint:disable-next-line:prefer-for-of + for (var i = 0; result.failedExpectations && i < result.failedExpectations.length; i += 1) { + console.log('AfterAll ' + result.failedExpectations[i].message); + console.log(result.failedExpectations[i].stack); + } + }, + + jasmineDone: (runDetails: jasmine.RunDetails) => { + console.log('Finished suite'); + console.log('Random:', runDetails.order.random); + } +}; + +jasmine.getEnv().addReporter(myReporter); + +describe("Randomize Tests", () => { + it("should allow randomization of the order of tests", () => { + expect(() => { + const env = jasmine.getEnv(); + env.randomizeTests(true); + }).not.toThrow(); + }); + + it("should allow a seed to be passed in for randomization", () => { + expect(() => { + const env = jasmine.getEnv(); + env.randomizeTests(true); + return env.seed(1234); + }).not.toThrow(); + }); +}); + +// Dest spces copied from jasmine project (https://github.com/jasmine/jasmine/blob/master/spec/core/SpecSpec.js) +describe("createSpyObj", function() { + it("should create an object with spy methods and corresponding return values when you call jasmine.createSpyObj() with an object", function() { + const spyObj = jasmine.createSpyObj('BaseName', {method1: 42, method2: 'special sauce'}); + + expect(spyObj.method1()).toEqual(42); + expect(spyObj.method1.and.identity()).toEqual('BaseName.method1'); + + expect(spyObj.method2()).toEqual('special sauce'); + expect(spyObj.method2.and.identity()).toEqual('BaseName.method2'); + }); + + it("should create an object with a bunch of spy methods when you call jasmine.createSpyObj()", function() { + const spyObj = jasmine.createSpyObj('BaseName', ['method1', 'method2']); + + expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function) }); + expect(spyObj.method1.and.identity()).toEqual('BaseName.method1'); + expect(spyObj.method2.and.identity()).toEqual('BaseName.method2'); + }); + + it("should allow you to omit the baseName and takes only an object", function() { + const spyObj = jasmine.createSpyObj({method1: 42, method2: 'special sauce'}); + + expect(spyObj.method1()).toEqual(42); + expect(spyObj.method1.and.identity()).toEqual('unknown.method1'); + + expect(spyObj.method2()).toEqual('special sauce'); + expect(spyObj.method2.and.identity()).toEqual('unknown.method2'); + }); + + it("should allow you to omit the baseName and takes only a list of methods", function() { + const spyObj = jasmine.createSpyObj(['method1', 'method2']); + + expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function) }); + expect(spyObj.method1.and.identity()).toEqual('unknown.method1'); + expect(spyObj.method2.and.identity()).toEqual('unknown.method2'); + }); + + it("should throw if you pass an empty array argument", function() { + expect(function() { + jasmine.createSpyObj('BaseName', []); + }).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for"); + }); + + it("should throw if you pass an empty object argument", function() { + expect(function() { + jasmine.createSpyObj('BaseName', {}); + }).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for"); + }); +}); + +(() => { + // from boot.js + const env = jasmine.getEnv(); + + const htmlReporter = new jasmine.HtmlReporter(); + env.addReporter(htmlReporter); + + const specFilter = new jasmine.HtmlSpecFilter(); + env.specFilter = (spec) => { + return specFilter.matches(spec.getFullName()); + }; + + const currentWindowOnload = window.onload; + window.onload = () => { + if (currentWindowOnload) { + (currentWindowOnload as any)(null); + } + htmlReporter.initialize(); + env.execute(); + }; +})(); + +jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; +jasmine.MAX_PRETTY_PRINT_DEPTH = 40; diff --git a/types/jasmine/ts3.1/tsconfig.json b/types/jasmine/ts3.1/tsconfig.json new file mode 100644 index 0000000000..d48a4a559a --- /dev/null +++ b/types/jasmine/ts3.1/tsconfig.json @@ -0,0 +1,22 @@ +{ + "files": [ + "index.d.ts", + "jasmine-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": ["../../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/jasmine/ts3.1/tslint.json b/types/jasmine/ts3.1/tslint.json new file mode 100644 index 0000000000..c540ba0129 --- /dev/null +++ b/types/jasmine/ts3.1/tslint.json @@ -0,0 +1,13 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "no-declare-current-package": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "no-unnecessary-generics": false, + "no-var-keyword": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false + } +} From 5befd67eabb90ec9bd3308ca4319aae6d3c6ac08 Mon Sep 17 00:00:00 2001 From: Moshe Kolodny Date: Wed, 13 Mar 2019 21:57:19 -0400 Subject: [PATCH 009/337] Fix the build with a hack --- types/saywhen/saywhen-tests.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/types/saywhen/saywhen-tests.ts b/types/saywhen/saywhen-tests.ts index a253308156..3eb72825fe 100644 --- a/types/saywhen/saywhen-tests.ts +++ b/types/saywhen/saywhen-tests.ts @@ -1,7 +1,17 @@ import when = require('saywhen'); -when(jasmine.createSpy('test')); // $ExpectType CallHandler -when(jasmine.createSpy('test')).isCalled; // $ExpectType Proxy +// This interface is needed to get around the fact that the new jasmine +// `createSpy` method takes a generic type while the old typings don't. +// That means that in Typescript 3.0 the spy will be `Spy` and in 3.1 it +// will be `Spy`. This interface matches both and is +// what dtslint will expect the type to be. +interface JasmineSpy extends jasmine.Spy { + (...params: any[]): any; +} +const spy: JasmineSpy = jasmine.createSpy('test'); + +when(spy); // $ExpectType CallHandler +when(spy).isCalled; // $ExpectType Proxy when.captor(); // $ExpectType MatcherProxy<{}> when.captor(jasmine.any(Number)); // $ExpectType MatcherProxy From d470a7a43e67f0b97796c25be7286ba6436331a9 Mon Sep 17 00:00:00 2001 From: melchiorV Date: Thu, 14 Mar 2019 15:59:17 +0800 Subject: [PATCH 010/337] Mod the types about input in react --- types/react/v15/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react/v15/index.d.ts b/types/react/v15/index.d.ts index 512fb5a0a7..ecbf37f6aa 100644 --- a/types/react/v15/index.d.ts +++ b/types/react/v15/index.d.ts @@ -2879,7 +2879,7 @@ declare namespace React { alt?: string; autoComplete?: string; autoFocus?: boolean; - capture?: boolean; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute + capture?: boolean | string; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute checked?: boolean; crossOrigin?: string; disabled?: boolean; From 05effa563b24ad52f43266f989fbcc45e5675de4 Mon Sep 17 00:00:00 2001 From: melchiorV Date: Thu, 14 Mar 2019 16:26:08 +0800 Subject: [PATCH 011/337] Mod the types about AllHTMLAttributes in react --- types/react/v15/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react/v15/index.d.ts b/types/react/v15/index.d.ts index ecbf37f6aa..d4f6300588 100644 --- a/types/react/v15/index.d.ts +++ b/types/react/v15/index.d.ts @@ -2648,7 +2648,7 @@ declare namespace React { autoComplete?: string; autoFocus?: boolean; autoPlay?: boolean; - capture?: boolean; + capture?: boolean | string; cellPadding?: number | string; cellSpacing?: number | string; charSet?: string; From 714e7b70bd50ba590158321255484ef87eee5943 Mon Sep 17 00:00:00 2001 From: Sebastian Markgraf Date: Wed, 13 Mar 2019 10:27:27 +0100 Subject: [PATCH 012/337] [victory] Add missing object possibility to gutter. --- types/victory/index.d.ts | 2 +- types/victory/victory-tests.tsx | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index 29d0dd068a..e6ed4b9003 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -2003,7 +2003,7 @@ declare module "victory" { * gutters are between columns. When orientation is vertical, gutters * are the space between rows. */ - gutter?: number; + gutter?: number | {left: number, right: number}; /** * The itemsPerRow prop determines how many items to render in each row * of a horizontal legend, or in each column of a vertical legend. This diff --git a/types/victory/victory-tests.tsx b/types/victory/victory-tests.tsx index ac60806cee..8a7cd0c14b 100644 --- a/types/victory/victory-tests.tsx +++ b/types/victory/victory-tests.tsx @@ -821,3 +821,16 @@ test = ( zoomDomain={[0, 500]} /> ); + +// Gutter test +test = ( + +); From 5b1d81b8504eccf726e044a869a8bcf54023357c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Baumeyer?= Date: Thu, 14 Mar 2019 10:41:11 +0100 Subject: [PATCH 013/337] Update cron types & bump version --- types/cron/cron-tests.ts | 18 ++++++++++++++---- types/cron/index.d.ts | 32 +++++++++++++++++++++++--------- 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/types/cron/cron-tests.ts b/types/cron/cron-tests.ts index d146fe6a61..f152498eca 100644 --- a/types/cron/cron-tests.ts +++ b/types/cron/cron-tests.ts @@ -46,6 +46,12 @@ var job = new CronJob(moment(), () => { timeZone /* Time zone of this job. */ ); +// Another example with system commands +var job = new CronJob('00 30 11 * * 1-5', 'ls', { command: 'ls', args: ['./'] }, + true, /* Start the job right now */ + timeZone /* Time zone of this job. */ +); + // For good measure var job = new CronJob({ cronTime: '00 30 11 * * 1-5', @@ -59,10 +65,14 @@ var job = new CronJob({ start: false, timeZone: 'America/Los_Angeles' }); -console.log(job.lastDate()); -console.log(job.nextDates());// Should be a Moment object -console.log(job.nextDates(1));// Should be an array of Moment object -console.log(job.running); +const ld = job.lastDate(); // $ExpectType Date +console.log(ld); +const nd = job.nextDates(); // $ExpectType Moment +console.log(nd); +const nds = job.nextDates(1); // $ExpectType Moment | Moment[] +console.log(nds);// Should be a Moment array +const ru = job.running // $ExpectType boolean +console.log(ru); job.setTime(new CronTime('00 30 11 * * 1-2')); job.start(); job.stop(); diff --git a/types/cron/index.d.ts b/types/cron/index.d.ts index b508c0d1fd..de4398333c 100644 --- a/types/cron/index.d.ts +++ b/types/cron/index.d.ts @@ -1,10 +1,15 @@ -// Type definitions for cron 1.6 +// Type definitions for cron 1.7 // Project: https://www.npmjs.com/package/cron // Definitions by: Hiroki Horiuchi // Lundarl Gholoi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + import { Moment } from 'moment'; +import { SpawnOptions } from "child_process"; + +export declare type CronCommand = (() => void) | string | { command: string, args?: ReadonlyArray, options?: SpawnOptions}; export declare class CronTime { /** @@ -17,10 +22,14 @@ export declare class CronTime { /** * Tells you when ```CronTime``` will be run. - * @param i Indicate which turn of run after now. If not given return next run time. */ public sendAt(): Moment; - public sendAt(i?: number): Moment[]; + /** + * Tells you when ```CronTime``` will be run. + * @param i Indicate which turn of run after now. If not given return next run time. + * @returns A `Moment` when the source passed in the constructor is a `Date` or a `Moment` and an array of `Moment` when the source is a string + */ + public sendAt(i?: number): Moment | Moment[]; /** * Get the number of milliseconds in the future at which to fire our callbacks. */ @@ -35,11 +44,11 @@ export declare interface CronJobParameters { /** * The function to fire at the specified time. If an ```onComplete``` callback was provided, ```onTick``` will receive it as an argument. ```onTick``` may call ```onComplete``` when it has finished its work. */ - onTick: () => void; + onTick: CronCommand; /** * A function that will fire when the job is stopped with ```job.stop()```, and may also be called by ```onTick``` at the end of each run. */ - onComplete?: () => void; + onComplete?: CronCommand; /** * Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call ```job.start()``` in order to start the job (assuming ```job``` is the variable you set the cronjob to). This does not immediately fire your ```onTick``` function, it just gives you more control over the behavior of your jobs. */ @@ -88,7 +97,7 @@ export declare class CronJob { * @param utcOffset This allows you to specify the offset of your timezone rather than using the ```timeZone``` param. Probably don't use both ```timeZone``` and ```utcOffset``` together or weird things may happen. * @param unrefTimeout If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at [timers#timers_timeout_unref](https://nodejs.org/api/timers.html#timers_timeout_unref) from the NodeJS docs. */ - constructor(cronTime: string | Date | Moment, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean); + constructor(cronTime: string | Date | Moment, onTick: CronCommand, onComplete?: CronCommand, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean); /** * Create a new ```CronJob```. * @param options Job parameters. @@ -114,10 +123,15 @@ export declare class CronJob { public lastDate(): Date; /** * Tells you when a ```CronTime``` will be run. - * @param i Indicate which turn of run after now. If not given return next run time. */ + public nextDate(): Moment; public nextDates(): Moment; - public nextDates(i?: number): Moment[]; + /** + * Tells you when a ```CronTime``` will be run. + * @param i Indicate which turn of run after now. If not given return next run time. + * @returns A `Moment` when the cronTime passed in the constructor is a `Date` or a `Moment` and an array of `Moment` when the cronTime is a string + */ + public nextDates(i?: number): Moment | Moment[]; /** * Add another ```onTick``` function. * @param callback Target function. @@ -126,7 +140,7 @@ export declare class CronJob { } export declare var job: - ((cronTime: string | Date | Moment, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean) => CronJob) + ((cronTime: string | Date | Moment, onTick: () => void, onComplete?: CronCommand, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean) => CronJob) | ((options: CronJobParameters) => CronJob); export declare var time: (source: string | Date | Moment, zone?: string) => CronTime; export declare var sendAt: (cronTime: string | Date | Moment) => Moment; From 4e8c93e46f12a82e81e7386e191ff6f60fce62c2 Mon Sep 17 00:00:00 2001 From: Simon Kostede Date: Thu, 14 Mar 2019 16:28:29 +0100 Subject: [PATCH 014/337] fix: wrong type definition for "fileds" in placeDetails fields and response parameters only match partly see: https://developers.google.com/places/web-service/details#fields --- types/google__maps/index.d.ts | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/types/google__maps/index.d.ts b/types/google__maps/index.d.ts index f1df5d8f38..2745cafe62 100644 --- a/types/google__maps/index.d.ts +++ b/types/google__maps/index.d.ts @@ -2404,9 +2404,36 @@ export interface PlaceDetailsRequest { * parameter from a request, ALL possible fields will be returned, and you will be billed accordingly. * This applies only to Place Details requests. */ - fields?: Array; + fields?: PlaceDetailsRequestField[]; } +export type PlaceDetailsRequestField = ( + "address_component" | + "adr_address" | + "alt_id" | + "formatted_address" | + "geometry" | + "icon" | + "id" | + "name" | + "permanently_closed" | + "photo" | + "place_id" | + "plus_code" | + "scope" | + "type" | + "url" | + "user_ratings_total" | + "utc_offset" | + "vicinity" | + "formatted_phone_number" | + "international_phone_number" | + "opening_hours" | + "website" | + "price_level" | + "rating" | + "review"); + export interface PlaceDetailsResponse { /** contains metadata on the request. */ status: PlaceDetailsResponseStatus; From 20178e9c55f922235bf9297330cd6f19e318a7af Mon Sep 17 00:00:00 2001 From: "Matt R. Wilson" Date: Thu, 14 Mar 2019 13:41:52 -0600 Subject: [PATCH 015/337] Remove @types/knex. Self bundles types since 0.16.0 --- notNeededPackages.json | 6 + types/knex/index.d.ts | 732 ----------------------- types/knex/knex-tests.ts | 1223 -------------------------------------- types/knex/tsconfig.json | 24 - types/knex/tslint.json | 7 - 5 files changed, 6 insertions(+), 1986 deletions(-) delete mode 100644 types/knex/index.d.ts delete mode 100644 types/knex/knex-tests.ts delete mode 100644 types/knex/tsconfig.json delete mode 100644 types/knex/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index 812d1f9f1b..2030aa189f 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -1032,6 +1032,12 @@ "sourceRepoURL": "https://github.com/keycloak/keycloak", "asOfVersion": "3.4.1" }, + { + "libraryName": "knex", + "typingsPackageName": "knex", + "sourceRepoURL": "https://github.com/tgriesser/knex", + "asOfVersion": "0.16.1" + }, { "libraryName": "knockout-paging", "typingsPackageName": "knockout-paging", diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts deleted file mode 100644 index 7888559827..0000000000 --- a/types/knex/index.d.ts +++ /dev/null @@ -1,732 +0,0 @@ -// Type definitions for Knex.js 0.15 -// Project: https://github.com/tgriesser/knex, https://knexjs.org -// Definitions by: Qubo -// Pablo Rodríguez -// Matt R. Wilson -// Satana Charuwichitratana -// Shrey Jain -// Joel Shepherd -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -/// - -import events = require("events"); -import stream = require ("stream"); -import Bluebird = require("bluebird"); - -type Callback = (...args: any[]) => void; -type Client = (...args: any[]) => void; -type Value = string | number | boolean | Date | string[] | number[] | Date[] | boolean[] | Buffer | Knex.Raw; -interface ValueMap { [key: string]: Value | Knex.QueryBuilder; } -type ColumnName = string | Knex.Raw | Knex.QueryBuilder | {[key: string]: string }; -type TableName = string | Knex.Raw | Knex.QueryBuilder; -interface Identifier { [alias: string]: string; } - -interface Knex extends Knex.QueryInterface { - (tableName?: TableName | Identifier): Knex.QueryBuilder; - VERSION: string; - __knex__: string; - - raw: Knex.RawBuilder; - transaction(transactionScope: (trx: Knex.Transaction) => Promise | Bluebird | void): Bluebird; - destroy(callback: (...args: any[]) => void): void; - destroy(): Bluebird; - batchInsert(tableName: TableName, data: any[], chunkSize?: number): Knex.QueryBuilder; - schema: Knex.SchemaBuilder; - queryBuilder(): Knex.QueryBuilder; - - client: any; - migrate: Knex.Migrator; - seed: any; - fn: Knex.FunctionHelper; - on(eventName: string, callback: (...args: any[]) => void): Knex.QueryBuilder; -} - -declare function Knex(config: Knex.Config): Knex; - -declare namespace Knex { - // - // QueryInterface - // - - interface QueryInterface { - select: Select; - as: As; - columns: Select; - column: Select; - from: Table; - into: Table; - table: Table; - distinct: Distinct; - - // Joins - join: Join; - joinRaw: JoinRaw; - innerJoin: Join; - leftJoin: Join; - leftOuterJoin: Join; - rightJoin: Join; - rightOuterJoin: Join; - outerJoin: Join; - fullOuterJoin: Join; - crossJoin: Join; - - // Withs - with: With; - withRaw: WithRaw; - withSchema: WithSchema; - withWrapped: WithWrapped; - - // Wheres - where: Where; - andWhere: Where; - orWhere: Where; - whereNot: Where; - andWhereNot: Where; - orWhereNot: Where; - whereRaw: WhereRaw; - orWhereRaw: WhereRaw; - andWhereRaw: WhereRaw; - whereWrapped: WhereWrapped; - havingWrapped: WhereWrapped; - whereExists: WhereExists; - orWhereExists: WhereExists; - whereNotExists: WhereExists; - orWhereNotExists: WhereExists; - whereIn: WhereIn; - orWhereIn: WhereIn; - whereNotIn: WhereIn; - orWhereNotIn: WhereIn; - whereNull: WhereNull; - orWhereNull: WhereNull; - whereNotNull: WhereNull; - orWhereNotNull: WhereNull; - whereBetween: WhereBetween; - orWhereBetween: WhereBetween; - andWhereBetween: WhereBetween; - whereNotBetween: WhereBetween; - orWhereNotBetween: WhereBetween; - andWhereNotBetween: WhereBetween; - - // Group by - groupBy: GroupBy; - groupByRaw: RawQueryBuilder; - - // Order by - orderBy: OrderBy; - orderByRaw: RawQueryBuilder; - - // Union - union: Union; - unionAll(callback: QueryCallback): QueryBuilder; - - // Having - having: Having; - andHaving: Having; - havingRaw: RawQueryBuilder; - orHaving: Having; - orHavingRaw: RawQueryBuilder; - havingIn: HavingIn; - - // Clear - clearOrder(): QueryBuilder; - clearSelect(): QueryBuilder; - clearWhere(): QueryBuilder; - - // Paging - offset(offset: number): QueryBuilder; - limit(limit: number): QueryBuilder; - - // Aggregation - count(...columnNames: string[]): QueryBuilder; - count(columnName: Record | Raw): QueryBuilder; - countDistinct(columnName: string | Record | Raw): QueryBuilder; - min(columnName: string, ...columnNames: string[]): QueryBuilder; - min(columnName: Record | Raw): QueryBuilder; - max(columnName: string, ...columnNames: string[]): QueryBuilder; - max(columnName: Record | Raw): QueryBuilder; - sum(columnName: string, ...columnNames: string[]): QueryBuilder; - sum(columnName: Record | Raw): QueryBuilder; - sumDistinct(columnName: string | Record | Raw): QueryBuilder; - avg(columnName: string, ...columnNames: string[]): QueryBuilder; - avg(columnName: Record | Raw): QueryBuilder; - avgDistinct(columnName: string | Record | Raw): QueryBuilder; - increment(columnName: string, amount?: number): QueryBuilder; - decrement(columnName: string, amount?: number): QueryBuilder; - - // Others - first: Select; - - pluck(column: string): QueryBuilder; - - insert(data: any, returning?: string | string[]): QueryBuilder; - modify(callback: QueryCallbackWithArgs, ...args: any[]): QueryBuilder; - update(data: any, returning?: string | string[]): QueryBuilder; - update(columnName: string, value: Value, returning?: string | string[]): QueryBuilder; - returning(column: string | string[]): QueryBuilder; - - del(returning?: string | string[]): QueryBuilder; - delete(returning?: string | string[]): QueryBuilder; - truncate(): QueryBuilder; - - clone(): QueryBuilder; - } - - interface As { - (columnName: string): QueryBuilder; - } - - interface Select extends ColumnNameQueryBuilder { - (aliases: { [alias: string]: string }): QueryBuilder; - } - - interface Table { - // tslint:disable-next-line ban-types - (tableName: TableName | Identifier | Function | Raw): QueryBuilder; - } - - // tslint:disable-next-line no-empty-interface - interface Distinct extends ColumnNameQueryBuilder { - } - - interface JoinCallback { - (this: JoinClause, join: JoinClause): void; - } - - interface Join { - (raw: Raw): QueryBuilder; - (tableName: TableName | QueryCallback, clause: JoinCallback): QueryBuilder; - (tableName: TableName | QueryCallback, columns: { [key: string]: string | number | Raw }): QueryBuilder; - (tableName: TableName | QueryCallback, raw: Raw): QueryBuilder; - (tableName: TableName | QueryCallback, column1: string, column2: string): QueryBuilder; - (tableName: TableName | QueryCallback, column1: string, raw: Raw): QueryBuilder; - (tableName: TableName | QueryCallback, column1: string, operator: string, column2: string): QueryBuilder; - } - - interface JoinClause { - on(raw: Raw): JoinClause; - on(callback: JoinCallback): JoinClause; - on(columns: { [key: string]: string | Raw }): JoinClause; - on(column1: string, column2: string): JoinClause; - on(column1: string, raw: Raw): JoinClause; - on(column1: string, operator: string, column2: string | Raw): JoinClause; - andOn(raw: Raw): JoinClause; - andOn(callback: JoinCallback): JoinClause; - andOn(columns: { [key: string]: string | Raw }): JoinClause; - andOn(column1: string, column2: string): JoinClause; - andOn(column1: string, raw: Raw): JoinClause; - andOn(column1: string, operator: string, column2: string | Raw): JoinClause; - orOn(raw: Raw): JoinClause; - orOn(callback: JoinCallback): JoinClause; - orOn(columns: { [key: string]: string | Raw }): JoinClause; - orOn(column1: string, column2: string): JoinClause; - orOn(column1: string, raw: Raw): JoinClause; - orOn(column1: string, operator: string, column2: string | Raw): JoinClause; - onIn(column1: string, values: any[]): JoinClause; - andOnIn(column1: string, values: any[]): JoinClause; - orOnIn(column1: string, values: any[]): JoinClause; - onNotIn(column1: string, values: any[]): JoinClause; - andOnNotIn(column1: string, values: any[]): JoinClause; - orOnNotIn(column1: string, values: any[]): JoinClause; - onNull(column1: string): JoinClause; - andOnNull(column1: string): JoinClause; - orOnNull(column1: string): JoinClause; - onNotNull(column1: string): JoinClause; - andOnNotNull(column1: string): JoinClause; - orOnNotNull(column1: string): JoinClause; - onExists(callback: QueryCallback): JoinClause; - andOnExists(callback: QueryCallback): JoinClause; - orOnExists(callback: QueryCallback): JoinClause; - onNotExists(callback: QueryCallback): JoinClause; - andOnNotExists(callback: QueryCallback): JoinClause; - orOnNotExists(callback: QueryCallback): JoinClause; - onBetween(column1: string, range: [any, any]): JoinClause; - andOnBetween(column1: string, range: [any, any]): JoinClause; - orOnBetween(column1: string, range: [any, any]): JoinClause; - onNotBetween(column1: string, range: [any, any]): JoinClause; - andOnNotBetween(column1: string, range: [any, any]): JoinClause; - orOnNotBetween(column1: string, range: [any, any]): JoinClause; - using(column: string | string[] | Raw | { [key: string]: string | Raw }): JoinClause; - type(type: string): JoinClause; - } - - interface JoinRaw { - (tableName: string, binding?: Value): QueryBuilder; - } - - interface With extends WithRaw, WithWrapped { - } - - interface WithRaw { - (alias: string, raw: Raw): QueryBuilder; - (alias: string, sql: string, bindings?: Value[] | object): QueryBuilder; - } - - interface WithSchema { - (schema: string): QueryBuilder; - } - - interface WithWrapped { - (alias: string, queryBuilder: QueryBuilder): QueryBuilder; - (alias: string, callback: (queryBuilder: QueryBuilder) => any): QueryBuilder; - } - - interface Where extends WhereRaw, WhereWrapped, WhereNull { - (raw: Raw): QueryBuilder; - (callback: QueryCallback): QueryBuilder; - (object: object): QueryBuilder; - (columnName: string, value: Value | null): QueryBuilder; - (columnName: string, operator: string, value: Value | QueryBuilder | null): QueryBuilder; - (left: Raw, operator: string, right: Value | QueryBuilder | null): QueryBuilder; - } - - interface WhereRaw extends RawQueryBuilder { - (condition: boolean): QueryBuilder; - } - - interface WhereWrapped { - (callback: QueryCallback): QueryBuilder; - } - - interface WhereNull { - (columnName: string): QueryBuilder; - } - - interface WhereBetween { - (columnName: string, range: [Value, Value]): QueryBuilder; - } - - interface WhereExists { - (callback: QueryCallback): QueryBuilder; - (query: QueryBuilder): QueryBuilder; - } - - interface WhereNull { - (columnName: string): QueryBuilder; - } - - interface WhereIn { - (columnName: string, values: Value[] | QueryBuilder | QueryCallback): QueryBuilder; - (columnNames: string[], values: Value[][] | QueryBuilder | QueryCallback): QueryBuilder; - } - - interface GroupBy extends RawQueryBuilder, ColumnNameQueryBuilder { - } - - interface OrderBy { - (columnName: string, direction?: string): QueryBuilder; - } - - interface Union { - (callback: QueryCallback | QueryBuilder | Raw, wrap?: boolean): QueryBuilder; - (callbacks: Array, wrap?: boolean): QueryBuilder; - (...callbacks: Array): QueryBuilder; - // (...callbacks: QueryCallback[], wrap?: boolean): QueryInterface; - } - - interface Having extends RawQueryBuilder, WhereWrapped { - (tableName: string, column1: string, operator: string, column2: string): QueryBuilder; - } - - interface HavingIn { - (columnName: string, values: Value[]): QueryBuilder; - } - - // commons - - interface ColumnNameQueryBuilder { - (...columnNames: ColumnName[]): QueryBuilder; - (columnNames: ColumnName[]): QueryBuilder; - } - - interface RawQueryBuilder { - (sql: string, ...bindings: Array): QueryBuilder; - (sql: string, bindings: Array | ValueMap): QueryBuilder; - (raw: Raw): QueryBuilder; - } - - // Raw - - interface Raw extends events.EventEmitter, ChainableInterface { - wrap(before: string, after: string): Raw; - } - - interface RawBuilder { - (value: Value): Raw; - (sql: string, ...bindings: Array): Raw; - (sql: string, bindings: Array | ValueMap): Raw; - } - - // - // QueryBuilder - // - - type QueryCallback = (this: QueryBuilder, builder: QueryBuilder) => void; - type QueryCallbackWithArgs = (this: QueryBuilder, builder: QueryBuilder, ...args: any[]) => void; - - interface QueryBuilder extends QueryInterface, ChainableInterface { - or: QueryBuilder; - and: QueryBuilder; - - // TODO: Promise? - columnInfo(column?: string): Bluebird; - - forUpdate(): QueryBuilder; - forShare(): QueryBuilder; - - toSQL(): Sql; - - on(event: string, callback: (...args: any[]) => void): QueryBuilder; - } - - interface Sql { - method: string; - options: any; - bindings: Value[]; - sql: string; - } - - // - // Chainable interface - // - - interface ChainableInterface extends Bluebird { - toQuery(): string; - options(options: { [key: string]: any }): this; - connection(connection: any): this; - debug(enabled: boolean): this; - transacting(trx: Transaction): this; - stream(handler: (readable: stream.PassThrough) => any): Bluebird; - stream(options: { [key: string]: any }, handler: (readable: stream.PassThrough) => any): Bluebird; - stream(options?: { [key: string]: any }): stream.PassThrough; - // tslint:disable-next-line no-unnecessary-generics - pipe(writable: T, options?: { [key: string]: any }): stream.PassThrough; - } - - interface Transaction extends Knex { - savepoint(transactionScope: (trx: Transaction) => any): Bluebird; - commit(value?: any): QueryBuilder; - rollback(error?: any): QueryBuilder; - } - - // - // Schema builder - // - - interface SchemaBuilder extends ChainableInterface { - createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; - createTableIfNotExists(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; - alterTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; - renameTable(oldTableName: string, newTableName: string): Bluebird; - dropTable(tableName: string): SchemaBuilder; - hasTable(tableName: string): Bluebird; - hasColumn(tableName: string, columnName: string): Bluebird; - table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Bluebird; - dropTableIfExists(tableName: string): SchemaBuilder; - raw(statement: string): SchemaBuilder; - withSchema(schemaName: string): SchemaBuilder; - } - - interface TableBuilder { - increments(columnName?: string): ColumnBuilder; - bigIncrements(columnName?: string): ColumnBuilder; - dropColumn(columnName: string): TableBuilder; - dropColumns(...columnNames: string[]): TableBuilder; - renameColumn(from: string, to: string): ColumnBuilder; - integer(columnName: string): ColumnBuilder; - bigInteger(columnName: string): ColumnBuilder; - text(columnName: string, textType?: string): ColumnBuilder; - string(columnName: string, length?: number): ColumnBuilder; - float(columnName: string, precision?: number, scale?: number): ColumnBuilder; - decimal(columnName: string, precision?: number | null, scale?: number): ColumnBuilder; - boolean(columnName: string): ColumnBuilder; - date(columnName: string): ColumnBuilder; - dateTime(columnName: string): ColumnBuilder; - time(columnName: string): ColumnBuilder; - timestamp(columnName: string, standard?: boolean): ColumnBuilder; - timestamps(useTimestampType?: boolean, makeDefaultNow?: boolean): ColumnBuilder; - binary(columnName: string, length?: number): ColumnBuilder; - enum(columnName: string, values: Value[], options?: EnumOptions): ColumnBuilder; - enu(columnName: string, values: Value[], options?: EnumOptions): ColumnBuilder; - json(columnName: string): ColumnBuilder; - jsonb(columnName: string): ColumnBuilder; - uuid(columnName: string): ColumnBuilder; - comment(val: string): TableBuilder; - specificType(columnName: string, type: string): ColumnBuilder; - primary(columnNames: string[]): TableBuilder; - index(columnNames: Array, indexName?: string, indexType?: string): TableBuilder; - unique(columnNames: Array, indexName?: string): TableBuilder; - foreign(column: string, foreignKeyName?: string): ForeignConstraintBuilder; - foreign(columns: string[], foreignKeyName?: string): MultikeyForeignConstraintBuilder; - dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder; - dropUnique(columnNames: Array, indexName?: string): TableBuilder; - dropPrimary(constraintName?: string): TableBuilder; - dropIndex(columnNames: Array, indexName?: string): TableBuilder; - dropTimestamps(): ColumnBuilder; - } - - // tslint:disable-next-line no-empty-interface - interface CreateTableBuilder extends TableBuilder { - } - - interface MySqlTableBuilder extends CreateTableBuilder { - engine(val: string): CreateTableBuilder; - charset(val: string): CreateTableBuilder; - collate(val: string): CreateTableBuilder; - } - - // tslint:disable-next-line no-empty-interface - interface AlterTableBuilder extends TableBuilder { - } - - // tslint:disable-next-line no-empty-interface - interface MySqlAlterTableBuilder extends AlterTableBuilder { - } - - interface ColumnBuilder { - index(indexName?: string): ColumnBuilder; - primary(constraintName?: string): ColumnBuilder; - unique(indexName?: string): ColumnBuilder; - references(columnName: string): ReferencingColumnBuilder; - onDelete(command: string): ColumnBuilder; - onUpdate(command: string): ColumnBuilder; - defaultTo(value: Value): ColumnBuilder; - unsigned(): ColumnBuilder; - notNullable(): ColumnBuilder; - nullable(): ColumnBuilder; - comment(value: string): ColumnBuilder; - alter(): ColumnBuilder; - } - - interface ForeignConstraintBuilder { - references(columnName: string): ReferencingColumnBuilder; - } - - interface MultikeyForeignConstraintBuilder { - references(columnNames: string[]): ReferencingColumnBuilder; - } - - interface PostgreSqlColumnBuilder extends ColumnBuilder { - index(indexName?: string, indexType?: string): ColumnBuilder; - } - - interface ReferencingColumnBuilder extends ColumnBuilder { - inTable(tableName: string): ColumnBuilder; - } - - // tslint:disable-next-line no-empty-interface - interface AlterColumnBuilder extends ColumnBuilder { - } - - interface MySqlAlterColumnBuilder extends AlterColumnBuilder { - first(): AlterColumnBuilder; - after(columnName: string): AlterColumnBuilder; - } - - interface EnumOptions { - useNative: boolean; - enumName: string; - } - - // - // Configurations - // - - interface ColumnInfo { - defaultValue: Value; - type: string; - maxLength: number; - nullable: boolean; - } - - interface Config { - debug?: boolean; - client?: string | typeof Client; - dialect?: string; - version?: string; - connection?: string | ConnectionConfig | MariaSqlConnectionConfig | - MySqlConnectionConfig | MsSqlConnectionConfig | Sqlite3ConnectionConfig | SocketConnectionConfig; - pool?: PoolConfig; - migrations?: MigratorConfig; - postProcessResponse?: (result: any, queryContext: any) => any; - wrapIdentifier?: (value: string, origImpl: (value: string) => string, queryContext: any) => string; - seeds?: SeedsConfig; - acquireConnectionTimeout?: number; - useNullAsDefault?: boolean; - searchPath?: string | string[]; - asyncStackTraces?: boolean; - } - - interface ConnectionConfig { - host: string; - user: string; - password: string; - database: string; - domain?: string; - instanceName?: string; - debug?: boolean; - requestTimeout?: number; - } - - interface MsSqlConnectionConfig { - user: string; - password: string; - server: string; - database: string; - options: MsSqlOptionsConfig; - } - - // Config object for mariasql: https://github.com/mscdex/node-mariasql#client-methods - interface MariaSqlConnectionConfig { - user?: string; - password?: string; - host?: string; - port?: number; - unixSocket?: string; - protocol?: string; - db?: string; - keepQueries?: boolean; - multiStatements?: boolean; - connTimeout?: number; - pingInterval?: number; - secureAuth?: boolean; - compress?: boolean; - ssl?: boolean | MariaSslConfiguration; - local_infile?: boolean; - read_default_file?: string; - read_default_group?: string; - charset?: string; - streamHWM?: number; - } - - interface MariaSslConfiguration { - key?: string; - cert?: string; - ca?: string; - capath?: string; - cipher?: string; - rejectUnauthorized?: boolean; - } - - // Config object for mysql: https://github.com/mysqljs/mysql#connection-options - interface MySqlConnectionConfig { - host?: string; - port?: number; - localAddress?: string; - socketPath?: string; - user?: string; - password?: string; - database?: string; - charset?: string; - timezone?: string; - connectTimeout?: number; - stringifyObjects?: boolean; - insecureAuth?: boolean; - typeCast?: any; - queryFormat?: (query: string, values: any) => string; - supportBigNumbers?: boolean; - bigNumberStrings?: boolean; - dateStrings?: boolean; - debug?: boolean; - trace?: boolean; - multipleStatements?: boolean; - flags?: string; - ssl?: string | MariaSslConfiguration; - } - - /** Used with SQLite3 adapter */ - interface Sqlite3ConnectionConfig { - filename: string; - debug?: boolean; - } - - interface MsSqlOptionsConfig { - encrypt?: boolean; - port?: number; - domain?: string; - connectionTimeout?: number; - requestTimeout?: number; - stream?: boolean; - parseJSON?: boolean; - pool?: PoolConfig; - } - - interface SocketConnectionConfig { - socketPath: string; - user: string; - password: string; - database: string; - debug?: boolean; - } - - interface PoolConfig { - name?: string; - create?: (...args: any[]) => void; - afterCreate?: (...args: any[]) => void; - destroy?: (...args: any[]) => void; - beforeDestroy?: (...args: any[]) => void; - min?: number; - max?: number; - refreshIdle?: boolean; - idleTimeoutMillis?: number; - reapIntervalMillis?: number; - returnToHead?: boolean; - priorityRange?: number; - validate?: (...args: any[]) => void; - log?: boolean; - - // generic-pool v3 configs - maxWaitingClients?: number; - testOnBorrow?: boolean; - acquireTimeoutMillis?: number; - fifo?: boolean; - autostart?: boolean; - evictionRunIntervalMillis?: number; - numTestsPerRun?: number; - softIdleTimeoutMillis?: number; - Promise?: any; - } - - interface MigratorConfig { - database?: string; - directory?: string; - extension?: string; - tableName?: string; - disableTransactions?: boolean; - } - - interface SeedsConfig { - directory?: string; - } - - interface Migrator { - make(name: string, config?: MigratorConfig): Bluebird; - latest(config?: MigratorConfig): Bluebird; - rollback(config?: MigratorConfig): Bluebird; - status(config?: MigratorConfig): Bluebird; - currentVersion(config?: MigratorConfig): Bluebird; - } - - interface FunctionHelper { - now(): Raw; - } - - // - // Clients - // - - class Client extends events.EventEmitter { - constructor(config: Config); - config: Config; - dialect: string; - driverName: string; - connectionSettings: object; - - acquireRawConnection(): Promise; - destroyRawConnection(connection: any): Promise; - validateConnection(connection: any): Promise; - } -} - -export = Knex; diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts deleted file mode 100644 index 1ff232e4a7..0000000000 --- a/types/knex/knex-tests.ts +++ /dev/null @@ -1,1223 +0,0 @@ -import Knex = require('knex'); -import { WriteStream } from 'fs'; - -// Initializing the Library -let knex = Knex({ - client: 'sqlite3', - connection: { - filename: "./mydb.sqlite" - } -}); - -knex = Knex({ - debug: true, - client: 'mysql', - connection: { - socketPath : '/path/to/socket.sock', - user : 'your_database_user', - password : 'your_database_password', - database : 'myapp_test' - } -}); - -knex = Knex({ - debug: true, - client: 'pg', - version: '9.5', - connection: { - user : 'your_database_user', - password: 'your_database_password', - server : 'your_database_server', - options : { - database: 'myapp_test' - } - } -}); - -knex = Knex({ - debug: true, - client: 'mssql', - connection: { - user : 'your_database_user', - password: 'your_database_password', - server : 'your_database_server', - options : { - database: 'myapp_test' - } - } -}); - -// Mariasql configuration -knex = Knex({ - debug: true, - client: 'mariasql', - connection: { - host : '127.0.0.1', - user : 'your_database_user', - password : 'your_database_password', - db : 'myapp_test' - } -}); - -// Mysql configuration -knex = Knex({ - debug: true, - client: 'mysql', - connection: { - host : '127.0.0.1', - user : 'your_database_user', - password : 'your_database_password', - db : 'myapp_test', - trace: false - } -}); - -// Pooling -knex = Knex({ - client: "mysql", - connection: { - host: "127.0.0.1", - user: "your_database_user", - password: "your_database_password", - database: "myapp_test" - }, - pool: { - min: 0, - max: 7, - afterCreate: (connection: any, callback: (...args: any[]) => void) => callback(null, connection), - beforeDestroy: (connection: any, callback: (...args: any[]) => void) => callback(null, connection) - } -}); - -// acquireConnectionTimeout -knex = Knex({ - debug: true, - client: 'mysql', - connection: { - socketPath : '/path/to/socket.sock', - user : 'your_database_user', - password : 'your_database_password', - database : 'myapp_test' - }, - acquireConnectionTimeout: 60000, -}); - -// Pure Query Builder without a connection -knex = Knex({}); - -// Pure Query Builder without a connection, using a specific flavour of SQL -knex = Knex({ - client: 'pg' -}); - -// searchPath -knex = Knex({ - client: 'pg', - searchPath: 'public', -}); -knex = Knex({ - client: 'pg', - searchPath: ['public', 'private'], -}); - -// postProcessResponse -knex = Knex({ - client: 'pg', - postProcessResponse(result, queryContext) { - return result; - } -}); - -// wrapIdentifier -knex = Knex({ - client: 'pg', - wrapIdentifier(value, origImpl, queryContext) { - return origImpl(value + 'foo'); - } -}); - -// useNullAsDefault -knex = Knex({ - client: 'sqlite', - useNullAsDefault: true, -}); - -// Using custom client -class TestClient extends Knex.Client {} - -knex = Knex({ - client: TestClient, -}); - -knex('books').insert({title: 'Test'}).returning('*').toString(); - -// Migrations -knex = Knex({ - client: 'mysql', - connection: { - host : '127.0.0.1', - user : 'your_database_user', - password : 'your_database_password', - database : 'myapp_test' - }, - migrations: { - tableName: 'migrations' - }, - seeds: { - directory: 'seeds' - } -}); - -// Knex Query Builder -knex.select('title', 'author', 'year').from('books'); -knex.select({ name: 'title', writer: 'author' }).from(knex.raw('books')); -knex.select().table('books'); - -knex.avg('sum_column1').from(function() { - this.sum('column1 as sum_column1').from('t1').groupBy('column1').as('t1'); -}).as('ignored_alias'); - -knex.column('title', 'author', 'year').select().from('books'); -knex.column(['title', 'author', 'year']).select().from('books'); -knex.column('title', { by: 'author' }, 'year').select().from('books'); -knex.column({ title: 'title', by: 'author', published: 'year' }).select().from('books'); -knex.select('*').from('users'); - -knex('users').where({ - first_name: 'Test', - last_name: 'User' -}).select('id'); - -knex('users').where('id', 1); - -knex('users').where(function() { - this.where('id', 1).orWhere('id', '>', 10); -}).orWhere({name: 'Tester'}); - -knex('users').where('votes', '>', 100); - -// Let null be used in a two or 3 parameter where filter -knex('users').where('votes', null); -knex('users').where('votes', 'is not', null); - -// Using Raw in where -knex('users').where(knex.raw('votes + 1'), '>', 101); -knex('users').where(knex.raw('votes + 1'), '>', knex.raw('100 + 1')); -knex('users').where('votes', '>', knex.raw('100 + 1')); - -let subquery = knex('users').where('votes', '>', 100).andWhere('status', 'active').orWhere('name', 'John').select('id'); -knex('accounts').where('id', 'in', subquery); - -knex.select('name').from('users') - .whereIn('id', [1, 2, 3]) - .orWhereIn('id', [4, 5, 6]); - -subquery = knex.select('id').from('accounts'); -knex.select('name').from('users') - .whereIn('account_id', subquery); - -knex('users') - .where('name', '=', 'John') - .orWhere(function() { - this.where('votes', '>', 100).andWhere('title', '<>', 'Admin'); - }); - -knex('users').whereNotIn('id', [1, 2, 3]); - -knex('users').where('name', 'like', '%Test%').orWhereNotIn('id', [1, 2, 3]); - -knex('users').whereNull('updated_at'); - -knex('users').whereNotNull('created_at'); - -knex('users').whereExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); -}); - -knex('users').whereExists(knex.select('*').from('accounts').whereRaw('users.account_id = accounts.id')); - -knex('users').whereNotExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); -}); - -knex('users').whereBetween('votes', [1, 100]); - -knex('users').whereNotBetween('votes', [1, 100]); - -knex('users').whereRaw('id = ?', [1]); -knex('users').whereRaw('id = :id', { id: 1 }); -knex('users').whereRaw('id = :id', { id: knex('users').select('id').limit(1) }); - -// Aggregate functions can use string/object parameters -knex('users').count(); -knex('users').count('*'); -knex('users').count('id', 'votes'); -knex('users').count({count: '*'}); -knex('users').count({count: ['id', 'votes']}); -knex('users').count({count: knex.raw('*')}); -knex('users').count(knex.raw('id')); - -knex('users').countDistinct('votes'); -knex('users').countDistinct(knex.raw('votes')); -knex('users').countDistinct({votes: 'votes'}); -knex('users').countDistinct({votes: knex.raw('votes')}); - -knex('users').avg('id'); -knex('users').avg('id', 'votes'); -knex('users').avg({avg: 'id'}); -knex('users').avg({avg: ['id', 'votes']}); -knex('users').avg({ab: knex.raw('a + b')}); -knex('users').avg(knex.raw('votes')); - -knex('users').avgDistinct('votes'); -knex('users').avgDistinct(knex.raw('votes')); -knex('users').avgDistinct({votes: 'votes'}); -knex('users').avgDistinct({votes: knex.raw('votes')}); - -knex('users').max('id'); -knex('users').max('id', 'votes'); -knex('users').max({max: 'id'}); -knex('users').max({max: ['id', 'votes']}); -knex('users').max({ab: knex.raw('a + b')}); -knex('users').max(knex.raw('votes')); - -knex('users').min('id'); -knex('users').min('id', 'votes'); -knex('users').min({min: 'id'}); -knex('users').min({min: ['id', 'votes']}); -knex('users').min({ab: knex.raw('a + b')}); -knex('users').min(knex.raw('votes')); - -knex('users').sum('id'); -knex('users').sum('id', 'votes'); -knex('users').sum({sum: 'id'}); -knex('users').sum({sum: ['id', 'votes']}); -knex('users').sum({ab: knex.raw('a + b')}); -knex('users').sum(knex.raw('votes')); - -knex('users').sumDistinct('votes'); -knex('users').sumDistinct(knex.raw('votes')); -knex('users').sumDistinct({votes: 'votes'}); -knex('users').sumDistinct({votes: knex.raw('votes')}); - -// Join methods -knex('users') - .join('contacts', 'users.id', '=', 'contacts.user_id') - .select('users.id', 'contacts.phone'); - -knex('users') - .join('contacts', { 'users.id': 12355 }) - .select('users.id', 'contacts.phone'); - -knex('users') - .join('contacts', 'users.id', 'contacts.user_id') - .select('users.id', 'contacts.phone'); - -knex('users') - .join(knex('contacts').select('user_id', 'phone').as('contacts'), 'users.id', 'contacts.user_id') - .select('users.id', 'contacts.phone'); - -knex('users') - .join(knex('contacts').select('user_id', 'phone').as('contacts'), { 'users.id': 'contacts.user_id' }) - .select('users.id', 'contacts.phone'); - -knex.select('*').from('users').join(knex('accounts').select('id', 'owner_id').as('accounts'), function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').join('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').join('accounts', function(join: Knex.JoinClause) { - if (this !== join) { - throw new Error("join() callback call semantics wrong"); - } - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('user').join('contacts', function() { - this.on('users.id', '=', knex.raw(7)); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onIn('contacts.id', [7, 15, 23, 41]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnIn('contacts.id', [7, 15, 23, 41]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnIn('contacts.id', [7, 15, 23, 41]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotIn('contacts.id', [7, 15, 23, 41]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNotIn('contacts.id', [7, 15, 23, 41]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNotIn('contacts.id', [7, 15, 23, 41]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNull('contacts.email'); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNull('contacts.email'); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNull('contacts.email'); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotNull('contacts.email'); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNotNull('contacts.email'); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNotNull('contacts.email'); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNotExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNotExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onBetween('contacts.id', [5, 30]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnBetween('contacts.id', [5, 30]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnBetween('contacts.id', [5, 30]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotBetween('contacts.id', [5, 30]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNotBetween('contacts.id', [5, 30]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNotBetween('contacts.id', [5, 30]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('accounts', (join: Knex.JoinClause) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').join('accounts', 'accounts.type', knex.raw('?', ['admin'])); - -knex.raw('? ON CONFLICT DO NOTHING', [knex('account').insert([{}])]); -knex.raw('select * from users where id = ? OR id = ?', - 1, - knex('users').select('id').limit(1), -); -knex.raw('select * from users where id = :user_id', { user_id: 1 }); -knex.raw('select * from users where id = :user_id_query', { - user_id_query: knex('ids').select('id').limit(1) -}); - -knex.from('users').innerJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.table('users').innerJoin('accounts', 'users.id', '=', 'accounts.user_id'); - -knex('users').innerJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex('users').innerJoin('accounts', (join: Knex.JoinClause) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').leftJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('users').leftJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').leftJoin('accounts', (join: Knex.JoinClause) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').leftJoin('accounts', (join) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id') - .andOn((join2) => { - join2.on('col1', 'col2').orOn('col3', 'col4'); - }); -}); - -knex.select('*').from('users').leftOuterJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('users').leftOuterJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').rightJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('users').rightJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').rightJoin('accounts', (join: Knex.JoinClause) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').rightOuterJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('users').rightOuterJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').outerJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('users').outerJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').outerJoin('accounts', (join: Knex.JoinClause) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').fullOuterJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('users').fullOuterJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').fullOuterJoin('accounts', (join: Knex.JoinClause) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').crossJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('accounts').joinRaw('natural full join table1').where('id', 1); - -knex.select('*').from('accounts').join(knex.raw('natural full join table1')).where('id', 1); - -knex.select('*').from('accounts') - .join(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .leftJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .leftOuterJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .rightJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .rightOuterJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .innerJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .crossJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .fullOuterJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .outerJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); - -knex('customers') - .distinct('first_name', 'last_name') - .select(); - -knex('users').groupBy('count'); - -knex.select('year', knex.raw('SUM(profit)')).from('sales').groupByRaw('year WITH ROLLUP'); - -knex('users').orderBy('name', 'desc'); - -knex.select('*').from('table').orderByRaw('col NULLS LAST DESC'); - -knex('books').insert({title: 'Slaughterhouse Five'}); - -knex('coords').insert([{x: 20}, {y: 30}, {x: 10, y: 20}]); - -knex.insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}], 'id').into('books'); -knex.insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}], ['id', 'title']).into('books'); - -knex('books') - .returning('id') - .insert({title: 'Slaughterhouse Five'}); - -knex('books') - .returning('id') - .insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}]); - -knex.batchInsert('books', [{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}], 200); -knex.batchInsert('books', [{title: 'Catcher In The Rye'}, {title: 'Pride And Prejudice'}]); -knex.queryBuilder().table('books'); - -knex('books').where('published_date', '<', 2000).update({status: 'archived'}); -knex('books').where('published_date', '<', 2000).update({status: 'archived'}, 'id'); -knex('books').where('published_date', '<', 2000).update({status: 'archived'}, ['id', 'title']); - -knex('books').update('title', 'Slaughterhouse Five'); -knex('books').update('title', 'Slaughterhouse Five', 'id'); -knex('books').update('title', 'Slaughterhouse Five', ['id', 'title']); - -knex('accounts').where('activated', false).del(); -knex('accounts').where('activated', false).del('id'); -knex('accounts').where('activated', false).del(['id', 'title']); -knex('accounts').where('activated', false).delete(); -knex('accounts').where('activated', false).delete('id'); -knex('accounts').where('activated', false).delete(['id', 'title']); - -knex.with('old_books', (qb) => { - qb.select('*').from('books').where('published_date', '<', 1970); -}).select('*').from('old_books'); - -knex.with('new_books', knex.raw('select * from books where published_date >= 2016')) - .select('*').from('new_books'); - -knex.with('new_books', 'select * from books where published_date >= :year', { year: 2016 }) - .select('*').from('new_books'); - -knex.with('new_books', 'select * from books where published_date >= ?', [2016]) - .select('*').from('new_books'); - -knex.with('new_books', knex.select('*').from('books').where("published_date", ">=", 2016)) - .select('*').from('new_books'); - -knex.withRaw('recent_books', 'select * from books where published_date >= :year', { year: 2013 }) - .select('*').from('recent_books'); - -knex.withRaw('recent_books', knex.raw('select * from books where published_date >= ?', [2013])) - .select('*').from('recent_books'); - -knex.withWrapped("antique_books", (qb) => { - qb.select('*').from('books').where('published_date', '<', 1899); -}).select('*').from('antique_books'); - -knex.withWrapped('new_books', knex.select('*').from('books').where("published_date", ">=", 2016)) - .select('*').from('new_books'); - -const someExternalMethod: (...args: any[]) => void = () => {}; - -knex.transaction((trx) => { - knex('books').transacting(trx).insert({name: 'Old Books'}) - .then((resp) => { - const id = resp[0]; - someExternalMethod(id, trx); - }) - .then(trx.commit) - .catch(trx.rollback); -}).then(() => { - console.log('Transaction complete.'); -}).catch((err) => { - console.error(err); -}); - -knex.transaction((trx) => { - knex('tableName') - .transacting(trx) - .forUpdate() - .select('*'); - - knex('tableName') - .transacting(trx) - .forShare() - .select('*'); -}); - -const transactionReturnValue = knex.transaction((trx) => { - return knex("table") - .insert({ foo: "bar" }) - .returning(["id"]) - .then((result) => { - return result[0].id as number; - }); -}); - -// Tests that the transaction has kept the type of its return value by referencing a method of number -transactionReturnValue.then(value => value.toExponential); - -knex('users').count('active'); - -knex('users').min('age'); - -knex('users').min('age as a'); - -knex('users').max('age'); - -knex('users').max('age as a'); - -knex('users').sum('products'); - -knex('users').sum('products as p'); - -knex('users').avg('age'); - -knex('users').avg('age as a'); - -knex('accounts') - .where('userid', '=', 1) - .increment('balance', 10); - -knex('accounts').where('userid', '=', 1).decrement('balance', 5); - -knex('accounts').truncate(); - -knex.table('users').first('id').then((ids) => { - console.log(ids); -}); - -knex.table('users').first('id', 'name').then((row) => { - console.log(row); -}); - -knex.table('users').first(knex.raw('round(sum(products)) as p')).then((row) => { - console.log(row); -}); - -knex.table('users').orderBy('name', 'desc').clearOrder().orderBy('id', 'asc').then((rows) => { - console.log(rows); -}); - -knex.table('users').select('*').clearSelect().select('id').then((rows) => { - console.log(rows); -}); - -knex('accounts').where('userid', '=', 1).clearWhere().select().then((rows) => { - console.log(rows); -}); - -// Using trx as a query builder: -knex.transaction((trx) => { - const info: any = {}; - const books: any[] = [ - {title: 'Canterbury Tales'}, - {title: 'Moby Dick'}, - {title: 'Hamlet'} - ]; - - return trx - .insert({name: 'Old Books'}, 'id') - .into('catalogues') - .then((ids) => { - return Promise.all(books.map((book: any) => { - book.catalogue_id = ids[0]; - // Some validation could take place here. - return trx.insert(info).into('books'); - })); - }); -}) -.then((inserts) => { - console.log(inserts.length + ' new books saved.'); -}) -.catch((error) => { - // If we get here, that means that neither the 'Old Books' catalogues insert, - // nor any of the books inserts will have taken place. - console.error(error); -}); - -// Using trx as a transaction object: -knex.transaction<{ length: number }>((trx) => { - trx.raw(''); - - trx.on('query-error', (error: Error) => { - console.error(error); - }); - - trx.savepoint((nestedTrx) => { - nestedTrx.rollback(new Error('something went terribly wrong')); - }); - - trx.transaction((nestedTrx) => { - nestedTrx.commit(); - }); - - const info: any = {}; - const books: any[] = [ - {title: 'Canterbury Tales'}, - {title: 'Moby Dick'}, - {title: 'Hamlet'} - ]; - - knex.insert({name: 'Old Books'}, 'id') - .into('catalogues') - .transacting(trx) - .then((ids) => { - return Promise.all(books.map((book: any) => { - book.catalogue_id = ids[0]; - - // Some validation could take place here. - - return knex.insert(info).into('books').transacting(trx); - })); - }) - .then(trx.commit) - .catch(trx.rollback); -}) -.then((inserts) => { - console.log(inserts.length + ' new books saved.'); -}) -.catch((error) => { - // If we get here, that means that neither the 'Old Books' catalogues insert, - // nor any of the books inserts will have taken place. - console.error(error); -}); - -// transacting handles undefined -knex.insert({ name: 'Old Books'}).transacting(undefined); - -knex.schema.withSchema("public").hasTable("table"); // $ExpectType Bluebird - -knex.schema.createTable('users', (table) => { - table.increments(); - table.string('name'); - table.enu('favorite_color', ['red', 'blue', 'green']); - table.timestamps(); - table.timestamp('created_at').defaultTo(knex.fn.now()); - table.timestamps(true, true); -}); - -knex.schema.alterTable('users', (table) => { - table.string('role').nullable(); -}); - -knex.schema.renameTable('users', 'old_users'); - -knex.schema.dropTable('users'); - -knex.schema.hasTable('users').then((exists) => { - if (!exists) { - return knex.schema.createTable('users', (t) => { - t.increments('id').primary(); - t.string('first_name', 100); - t.string('last_name', 100); - t.text('bio'); - }); - } -}); - -const tableName = ''; -const columnName = ''; -knex.schema.hasColumn(tableName, columnName); - -knex.schema.dropTableIfExists('users'); - -knex.schema.table('users', (table) => { - table.dropColumn('name'); - table.string('first_name'); - table.string('last_name'); -}); - -knex.schema.raw("SET sql_mode='TRADITIONAL'") -.table('users', (table) => { - table.dropColumn('name'); - table.string('first_name'); - table.string('last_name'); - table.dropUnique(["name1", "name2"], "index_name"); - table.dropUnique(["name1", "name2"]); - table.dropPrimary(); - table.dropPrimary("constraint_name"); -}); - -knex('users') - .select(knex.raw('count(*) as user_count, status')) - .where(knex.raw(1)) - .orWhere(knex.raw('status <> ?', [1])) - .groupBy('status'); - -knex.raw('select * from users where id = ?', [1]).then((resp) => { - // ... - }); - -(() => { - const subcolumn = knex.raw('select avg(salary) from employee where dept_no = e.dept_no') - .wrap('(', ') avg_sal_dept'); - - knex.select('e.lastname', 'e.salary', subcolumn) - .from('employee as e') - .whereRaw('dept_no = e.dept_no'); -})(); - -(() => { - const subcolumn = knex.avg('salary') - .from('employee') - .whereRaw('dept_no = e.dept_no') - .as('avg_sal_dept'); - - knex.select('e.lastname', 'e.salary', subcolumn) - .from('employee as e') - .whereRaw('dept_no = e.dept_no'); -})(); - -const x = 1; -knex.select('name').from('users') - .where('id', '>', 20) - .andWhere('id', '<', 200) - .limit(10) - .offset(x) - .then((rows) => { - return rows.map((r: any) => r.name); - }) - .then((names: any) => { - return knex.select('id').from('nicknames').whereIn('nickname', names); - }) - .then((rows) => { - console.log(rows); - }) - .catch((error) => { - console.error(error); - }); - -knex.select('*').from('users').where({name: 'Tim'}) - .then((rows) => { - return knex.insert({user_id: rows[0].id, name: 'Test'}, 'id').into('accounts'); - }).then((id) => { - console.log('Inserted Account ' + id); - }).catch((error) => { - console.error(error); - }); - -knex.insert({id: 1, name: 'Test'}, 'id').into('accounts') - .catch((error) => { - console.error(error); - }).then(() => { - return knex.select('*').from('accounts').where('id', 1); - }).then((rows) => { - console.log(rows[0]); - }).catch((error) => { - console.error(error); - }); - -const query: any = () => {}; -query.then((x: any) => { - // doSideEffectsHere(x); - return x; -}); - -knex.select('name').from('users').limit(10).then((rows: any[]): string[] => { - return rows.map((row: any): string => { - return row.name; - }); -}).then((names: string[]) => { - console.log(names); -}).catch((e: Error) => { - console.error(e); -}); - -knex.select('name').from('users').limit(10).then((rows: any[]) => { - return rows.reduce((memo: any, row: any) => { - memo.names.push(row.name); - memo.count++; - return memo; - }, {count: 0, names: []}); -}).then((obj: any) => { - console.log(obj); -}).catch((e: Error) => { - console.error(e); -}); - -knex.select('name').from('users') - .limit(10) - .then(console.log.bind(console)) - .catch(console.error.bind(console)); - -const values: any[] = []; - -knex.insert(values).into('users') - .then(() => { - return {inserted: true}; - }); - -knex.select('name').from('users') - .where('id', '>', 20) - .andWhere('id', '<', 200) - .limit(10) - .offset(x); - -// Retrieve the stream: -let stream = knex.select('*').from('users').stream(); -const writableStream: NodeJS.WritableStream = new WriteStream(); -stream.pipe(writableStream); - -// With options: -stream = knex.select('*').from('users').stream({highWaterMark: 5}); -stream.pipe(writableStream); - -// Use as a promise: -(() => { - knex - .select("*") - .from("users") - .where(knex.raw("id = ?", [1])) - .stream((stream: any) => { - stream.pipe(writableStream); - }) - .then(() => { - // ... - }) - .catch((e: Error) => { - console.error(e); - }); -})(); - -stream = knex.select('*').from('users').pipe(writableStream); -const app: any = () => {}; - -knex.select('*') - .from('users') - .on('query', (data: any) => { - app.log(data); - }) - .then(() => { - // ... - }); - -knex.select('*').from('users').where(knex.raw('id = ?', [1])).toString(); - -knex.select('*').from('users').where(knex.raw('id = ?', [1])).toSQL(); - -// -// Callback functions -// -knex('users') - .select('*') - .join('contacts', function(builder) { - this.on(function(builder: any) { - let self: Knex.JoinClause = this; - self = builder; - }).andOn(function(builder: any) { - let self: Knex.JoinClause = this; - self = builder; - }).orOn(function(builder: any) { - let self: Knex.JoinClause = this; - self = builder; - }).onExists(function(builder: any) { - let self: Knex.QueryBuilder = this; - self = builder; - }).orOnExists(function(builder: any) { - let self: Knex.QueryBuilder = this; - self = builder; - }).andOnExists(function(builder: any) { - let self: Knex.QueryBuilder = this; - self = builder; - }).onNotExists(function(builder: any) { - let self: Knex.QueryBuilder = this; - self = builder; - }).andOnNotExists(function(builder: any) { - let self: Knex.QueryBuilder = this; - self = builder; - }).orOnNotExists(function(builder: any) { - let self: Knex.QueryBuilder = this; - self = builder; - }); - }).where(function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).orWhere(function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).andWhere(function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).whereIn('column', function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).orWhereIn('column', function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).whereNotIn('column', function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).orWhereNotIn('column', function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).whereWrapped(function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).union(function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).unionAll(function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).modify(function(builder, aBool) { - let self: Knex.QueryBuilder = this; - self = builder; - }, true); - -// -// Migrations -// -const name = "test"; -const config = { - directory: "./migrations", - extension: "js", - tableName: "knex_migrations", - disableTransactions: false -}; -knex.migrate.make(name, config); -knex.migrate.make(name); - -knex.migrate.latest(config); -knex.migrate.latest(); - -knex.migrate.rollback(config); -knex.migrate.rollback(); - -knex.migrate.currentVersion(config); -knex.migrate.currentVersion(); - -knex.seed.make(name, config); -knex.seed.make(name); - -knex.seed.run(config); -knex.seed.run(); - -knex.schema - .dropTableIfExists('A') - .createTable('A', table => { - table.integer('C').unsigned().references('B.id').notNullable(); - table.integer('D').primary('PK').notNullable(); - table.string('E').unique('UX').nullable(); - table.foreign('E', 'FK').references('F.id'); - table.timestamp('T', false).notNullable(); - }); - -// creating table in MySQL with binary primary key with known field length -knex.schema.createTable('testTable', (table) => { - table.binary('binaryKey', 16).primary(); // will make table with binaryKey type BINARY(16) -}); - -// allow creating decimal column that can store that can store numbers of any -// precision and scale. (Only supported for Oracle, SQLite, Postgres) -knex = Knex({ - client: 'pg' -}); - -knex.schema - .dropTableIfExists('testTable') - .createTable('testTable', (table) => { - table.decimal('dec', null); - }) - .dropTable('testTable'); - -// allow specifying an alias for a table name -knex.schema - .dropTableIfExists('foo') - .dropTableIfExists('bar') - .createTable('foo', (table) => { - table.uuid('id').primary(); - }) - .createTable('bar', (table) => { - table.uuid('id').primary(); - }); - -knex({ - table1: 'foo', - table2: 'bar' -}) - .select({ - table1Id: 'table1.id', - table2Id: 'table2.id' - }); - -knex('characters') - .select() - .whereIn(['name', 'class'], [['Bar', 'Fighter'], ['Foo', 'Druid']]); - -knex('characters') - .select() - .whereIn('name', knex('characters').select('name')); -knex('characters') - .select() - .whereIn(['name', 'class'], knex('characters').select('name', 'class')); - -knex('characters') - .select() - .whereIn('name', function() { - this.select('name').from('characters'); - }); -knex('characters') - .select() - .whereIn(['name', 'class'], function() { - this.select('name', 'class').from('characters'); - }); - -knex('characters') - .select() - .where({ name: 'Bar', class: 'Fighter' }) - .union(knex('characters').select().where({ name: 'Foo', class: 'Druid' })); -knex('characters') - .select() - .where({ name: 'Bar', class: 'Fighter' }) - .union([knex('characters').select().where({ name: 'Foo', class: 'Druid' })]); -knex('characters') - .select() - .where({ name: 'Bar', class: 'Fighter' }) - .union( - knex('characters').select().where({ name: 'Foo', class: 'Druid' }), - knex('characters').select().where({ name: 'Baz', class: 'Paladin' }) - ); diff --git a/types/knex/tsconfig.json b/types/knex/tsconfig.json deleted file mode 100644 index 8f0b7771d9..0000000000 --- a/types/knex/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "knex-tests.ts" - ] -} \ No newline at end of file diff --git a/types/knex/tslint.json b/types/knex/tslint.json deleted file mode 100644 index 604d5950cf..0000000000 --- a/types/knex/tslint.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "unified-signatures": false, - "callable-types": false - } -} From 68e69031cd0e28214e879a65548fa039f15decf9 Mon Sep 17 00:00:00 2001 From: "Matt R. Wilson" Date: Thu, 14 Mar 2019 16:35:37 -0600 Subject: [PATCH 016/337] Add knex as dependency for needing packages. Allows these types to still require knex now that it self bundles its types. --- types/bookshelf/package.json | 6 ++++++ types/knex-postgis/package.json | 6 ++++++ types/mock-knex/package.json | 6 ++++++ types/schwifty/package.json | 1 + 4 files changed, 19 insertions(+) create mode 100644 types/bookshelf/package.json create mode 100644 types/knex-postgis/package.json create mode 100644 types/mock-knex/package.json diff --git a/types/bookshelf/package.json b/types/bookshelf/package.json new file mode 100644 index 0000000000..7bd76f13f8 --- /dev/null +++ b/types/bookshelf/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "knex": "^0.16.1" + } +} diff --git a/types/knex-postgis/package.json b/types/knex-postgis/package.json new file mode 100644 index 0000000000..7bd76f13f8 --- /dev/null +++ b/types/knex-postgis/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "knex": "^0.16.1" + } +} diff --git a/types/mock-knex/package.json b/types/mock-knex/package.json new file mode 100644 index 0000000000..7bd76f13f8 --- /dev/null +++ b/types/mock-knex/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "knex": "^0.16.1" + } +} diff --git a/types/schwifty/package.json b/types/schwifty/package.json index 01df4a95e3..4361a26f8b 100644 --- a/types/schwifty/package.json +++ b/types/schwifty/package.json @@ -1,6 +1,7 @@ { "private": true, "dependencies": { + "knex": "^0.16.1", "objection": "^1.1.9" } } From daa465cfb164f3b206d7a4d4f2fa4e8804256d89 Mon Sep 17 00:00:00 2001 From: Ryan Mehta Date: Thu, 14 Mar 2019 15:36:15 -0700 Subject: [PATCH 017/337] remove skip from express-jwt --- types/express-jwt/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/express-jwt/index.d.ts b/types/express-jwt/index.d.ts index d1029849cc..52d7d901ec 100644 --- a/types/express-jwt/index.d.ts +++ b/types/express-jwt/index.d.ts @@ -37,7 +37,6 @@ declare namespace jwt { export interface Options { secret: secretType | SecretCallback | SecretCallbackLong; userProperty?: string; - skip?: string[]; credentialsRequired?: boolean; isRevoked?: IsRevokedCallback; requestProperty?: string; From cfb1d9966748fca729a6a692a1e68f8c0601c108 Mon Sep 17 00:00:00 2001 From: Florian Topf Date: Fri, 15 Mar 2019 14:58:59 +0100 Subject: [PATCH 018/337] Added additional property for type 'array' --- types/revalidator/index.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/revalidator/index.d.ts b/types/revalidator/index.d.ts index dd249d2afc..ec172c2be2 100644 --- a/types/revalidator/index.d.ts +++ b/types/revalidator/index.d.ts @@ -88,6 +88,8 @@ declare module Revalidator { conform?: (value: any, data?: T) => boolean; /**Value is valid only if the dependent value is valid */ dependencies?: string; + /**Property to describe items for type: 'array' */ + items?: ISchema|JSONSchema } } @@ -95,4 +97,4 @@ declare var revalidator: Revalidator.RevalidatorStatic; declare module "revalidator" { export = revalidator; -} \ No newline at end of file +} From 49311e0283a9859a79d2cdd70ed52163204a30a3 Mon Sep 17 00:00:00 2001 From: Jarrett Meyer Date: Fri, 15 Mar 2019 10:36:26 -0400 Subject: [PATCH 019/337] Bump version in first line --- types/d3-sankey/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/d3-sankey/index.d.ts b/types/d3-sankey/index.d.ts index f5394a1b26..d4ba68d820 100644 --- a/types/d3-sankey/index.d.ts +++ b/types/d3-sankey/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3-sankey module 0.7 +// Type definitions for D3JS d3-sankey module 0.11.0 // Project: https://github.com/d3/d3-sankey/ // Definitions by: Tom Wanzek , Alex Ford // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 193843ef52d8024eab5028635da07e59f68a444c Mon Sep 17 00:00:00 2001 From: jwooden Date: Fri, 15 Mar 2019 11:07:30 -0400 Subject: [PATCH 020/337] mssql: Add missing Request.pause and Request.resume types --- types/mssql/index.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index 085ab122c1..4c12f876c1 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -7,6 +7,7 @@ // Jørgen Elgaard Larsen // Peter Keuter // David Gasperoni +// Jeff Wooden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -281,6 +282,8 @@ export declare class Request extends events.EventEmitter { public bulk(table: Table): Promise; public bulk(table: Table, callback: (err: Error, rowCount: any) => void): void; public cancel(): void; + public pause(): boolean; + public resume(): boolean; } export declare class RequestError implements Error { From 0a90d3ca198db1b2157c260984d27a2da9b22661 Mon Sep 17 00:00:00 2001 From: Jarrett Meyer Date: Fri, 15 Mar 2019 13:53:21 -0400 Subject: [PATCH 021/337] Fixes version in index.d.ts header --- types/d3-sankey/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/d3-sankey/index.d.ts b/types/d3-sankey/index.d.ts index d4ba68d820..3f10e2d1ae 100644 --- a/types/d3-sankey/index.d.ts +++ b/types/d3-sankey/index.d.ts @@ -1,10 +1,10 @@ -// Type definitions for D3JS d3-sankey module 0.11.0 +// Type definitions for D3JS d3-sankey module 0.11 // Project: https://github.com/d3/d3-sankey/ // Definitions by: Tom Wanzek , Alex Ford // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Last module patch version validated against: 0.11.0 +// Last module patch version validated against: 0.11 import { Link } from 'd3-shape'; From 33963c49d45aaa372614673df0bd4106ffaec3c0 Mon Sep 17 00:00:00 2001 From: michaeltnguyen Date: Fri, 15 Mar 2019 16:58:17 -0500 Subject: [PATCH 022/337] Fix onRowClick callback params --- types/react-virtualized/dist/es/Table.d.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/types/react-virtualized/dist/es/Table.d.ts b/types/react-virtualized/dist/es/Table.d.ts index b66fac389b..d63d593b6e 100644 --- a/types/react-virtualized/dist/es/Table.d.ts +++ b/types/react-virtualized/dist/es/Table.d.ts @@ -183,11 +183,7 @@ export class Column extends Component { } export type RowMouseEventHandlerParams = { - rowData: { - columnData: object; - id: string; - index: number; - }; + rowData: any index: number; event: React.MouseEvent; }; From a23739dd3d700b890b5c6a6ca01b84bf3a14ae58 Mon Sep 17 00:00:00 2001 From: michaeltnguyen Date: Fri, 15 Mar 2019 17:10:32 -0500 Subject: [PATCH 023/337] Update react-virtualized version in index.d.ts --- types/react-virtualized/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-virtualized/index.d.ts b/types/react-virtualized/index.d.ts index c105c4db2f..1fd2fb0b4f 100644 --- a/types/react-virtualized/index.d.ts +++ b/types/react-virtualized/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-virtualized 9.18 +// Type definitions for react-virtualized 9.21 // Project: https://github.com/bvaughn/react-virtualized // Definitions by: Kalle Ott // John Gunther From d1fa05328f971ef375afbfe43d56bc40dfa559b4 Mon Sep 17 00:00:00 2001 From: William Boman Date: Sat, 16 Mar 2019 12:31:00 +0100 Subject: [PATCH 024/337] types/domurl: add missing default export, also fix bad tests --- types/domurl/domurl-tests.ts | 8 +++++--- types/domurl/index.d.ts | 13 ++++++++----- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/types/domurl/domurl-tests.ts b/types/domurl/domurl-tests.ts index 2de93bcc20..e00aa7e1ba 100644 --- a/types/domurl/domurl-tests.ts +++ b/types/domurl/domurl-tests.ts @@ -1,13 +1,15 @@ -interface UModel extends QueryString { +import Url = require("domurl"); + +interface UModel { a: any; b: string; } -interface U2Model extends QueryString { +interface U2Model { a: any; } -interface U3Model extends QueryString { +interface U3Model { foo: string; } diff --git a/types/domurl/index.d.ts b/types/domurl/index.d.ts index d0b7896d61..9de60d45b1 100644 --- a/types/domurl/index.d.ts +++ b/types/domurl/index.d.ts @@ -3,14 +3,15 @@ // Definitions by: Mikhus // Definitions: https://github.com/Mikhus/DefinitelyTyped -declare class QueryString { - constructor(qs?: string); - toString: () => string; +// + +declare namespace domurl { + type QueryString = T; } declare class Url { constructor(url?: string); - query: T; + query: domurl.QueryString; protocol: string; user: string; pass: string; @@ -26,5 +27,7 @@ declare class Url { paths: (paths?: [string]) => [string]; isEmptyQuery: () => boolean; queryLength: () => number; - clearQuery: () => Url; + clearQuery: () => Url<{}>; } + +export = Url; From cfde12269ccf42b9c1db2a04e260a4f8ed4ccf62 Mon Sep 17 00:00:00 2001 From: Richard Lea Date: Sun, 10 Mar 2019 01:01:16 +0900 Subject: [PATCH 025/337] fix(inquirer): update api definitions to 6.x Signed-off-by: Richard Lea --- types/inquirer/index.d.ts | 147 +++++++++++++++++------------- types/inquirer/inquirer-tests.ts | 111 +++++++++++----------- types/inquirer/package.json | 6 ++ types/yeoman-generator/index.d.ts | 1 + 4 files changed, 143 insertions(+), 122 deletions(-) create mode 100644 types/inquirer/package.json diff --git a/types/inquirer/index.d.ts b/types/inquirer/index.d.ts index 74aee08ed3..d61b2adde4 100644 --- a/types/inquirer/index.d.ts +++ b/types/inquirer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Inquirer.js +// Type definitions for Inquirer.js 6.x // Project: https://github.com/SBoudrias/Inquirer.js // Definitions by: Qubo // Parvez @@ -9,27 +9,26 @@ // Justin Rockwood // Keith Kelly // Junyoung Clare Jang +// Richard Lea // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 -/// +// TypeScript Version: 2.8 import through = require('through'); +import { Observable } from 'rxjs'; +import * as readline from 'readline'; declare namespace inquirer { - type Prompts = { [name: string]: PromptModule }; + type Prompts = { [name: string]: prompts.Base }; type ChoiceType = string | objects.ChoiceOption | objects.Separator; type Questions = | Question | ReadonlyArray> - | Rx.Observable>; - interface OutputStreamOption { - output: NodeJS.WriteStream - } - interface InputStreamOption { - input: NodeJS.ReadStream - } - type StreamOptions = InputStreamOption | OutputStreamOption | (InputStreamOption & OutputStreamOption); + | Observable>; + type StreamOptions = { + input?: NodeJS.ReadStream, + output?: NodeJS.WriteStream, + }; interface Inquirer { restoreDefaultPrompts(): void; @@ -47,28 +46,25 @@ declare namespace inquirer { /** * Public CLI helper interface * @param questions Questions settings array - * @param cb Callback being passed the user answers * @return */ - prompt(questions: Questions, cb: (answers: T) => any): ui.Prompt; - prompt(questions: Questions): Promise; + prompt: PromptModule; prompts: Prompts; Separator: objects.SeparatorStatic; ui: { BottomBar: ui.BottomBar; - Prompt: ui.Prompt; + Prompt: ui.PromptUI; }; } interface PromptModule { - (questions: Questions): Promise; - (questions: Questions, cb: (answers: T) => any): ui.Prompt; + (questions: Questions): Promise & { ui: ui.PromptUI }; /** * Register a prompt type * @param name Prompt type name * @param prompt Prompt constructor */ - registerPrompt(name: string, prompt: PromptModule): ui.Prompt; + registerPrompt(name: string, prompt: prompts.Base): PromptModule; /** * Register the defaults provider prompts */ @@ -111,9 +107,9 @@ declare namespace inquirer { * (to save in the answers hash). Values can also be a Separator. */ choices?: - | ReadonlyArray - | ((answers: T) => ReadonlyArray) - | ((answers: T) => Promise>); + | ReadonlyArray + | ((answers: T) => ReadonlyArray) + | ((answers: T) => Promise>); /** * Receive the user input and should return true if the value is valid, and an error message (String) * otherwise. If false is returned, a default error message is provided. @@ -161,32 +157,88 @@ declare namespace inquirer { [key: string]: any; } + /** + * Corresponding to the answer object creation in: + * https://github.com/SBoudrias/Inquirer.js/blob/ff075f587ef78504f0eae4ee5ca0656432429026/packages/inquirer/lib/ui/prompt.js#L88 + */ + interface Answer { + name: string, + answer: any, + } + + namespace prompts { + /** + * Base prompt implementation + * Should be extended by prompt types. + * + * @interface Base + */ + interface Base { + new (question: Question, rl: readline.Interface, answers: Answers): Base; + /** + * Start the Inquiry session and manage output value filtering + * + * @returns {Promise} + * @memberof Base + */ + run(): Promise; + /** + * Called when the UI closes. Override to do any specific cleanup necessary + */ + close(): void; + /** + * Generate the prompt question string + */ + getQuestion(): string; + } + } + namespace ui { + /** * Base interface class other can inherits from */ - interface Prompt extends BaseUI { - new (promptModule: Prompts): Prompt; + interface BaseUI { + rl: readline.Interface; + new(opt: StreamOptions): BaseUI; + /** + * Handle the ^C exit + * @return {null} + */ + onForceClose(): void; + /** + * Close the interface and cleanup listeners + */ + close(): void; + } + /** + * Base interface class other can inherits from + */ + interface PromptUI extends BaseUI { + process: Observable; + new(prompts: Prompts, opt: StreamOptions): PromptUI; + run(questions: Questions): Promise; /** * Once all prompt are over */ onCompletion(): void; - processQuestion(question: Question): any; - fetchAnswer(question: Question): any; - setDefaultType(question: Question): any; - filterIfRunnable(question: Question): any; + processQuestion(question: Question): Observable>; + fetchAnswer(question: Question): Observable>; + setDefaultType(question: Question): Observable>; + filterIfRunnable(question: Question): Observable>; } /** * Sticky bottom bar user interface */ - interface BottomBar extends BaseUI { - new (opt?: BottomBarOption): BottomBar; + interface BottomBar extends BaseUI { + new(opt?: StreamOptions & { bottomBar?: string }): BottomBar; /** * Render the prompt to screen * @return self */ render(): BottomBar; + clean(): BottomBar; /** * Update the bottom bar content and rerender * @param bottomBar Bottom bar content @@ -194,10 +246,11 @@ declare namespace inquirer { */ updateBottomBar(bottomBar: string): BottomBar; /** - * Rerender the prompt + * Write out log data + * @param {String} data - The log data to be output * @return self */ - writeLog(data: any): BottomBar; + writeLog(data: string): BottomBar; /** * Make sure line end on a line feed * @param str Input string @@ -212,36 +265,6 @@ declare namespace inquirer { log: through.ThroughStream; } - interface BottomBarOption { - bottomBar?: string; - } - /** - * Base interface class other can inherits from - */ - interface BaseUI { - new (opt: TOpt): void; - /** - * Handle the ^C exit - * @return {null} - */ - onForceClose(): void; - /** - * Close the interface and cleanup listeners - */ - close(): void; - /** - * Handle and propagate keypress events - */ - onKeypress(s: string, key: Key): void; - } - - interface Key { - sequence: string; - name: string; - meta: boolean; - shift: boolean; - ctrl: boolean; - } } namespace objects { diff --git a/types/inquirer/inquirer-tests.ts b/types/inquirer/inquirer-tests.ts index 4c8ba9491f..95f8d442a6 100644 --- a/types/inquirer/inquirer-tests.ts +++ b/types/inquirer/inquirer-tests.ts @@ -3,11 +3,10 @@ import inquirer = require("inquirer"); inquirer.prompt( [ /* Pass your questions in here */ - ], - function(answers: inquirer.Answers) { - // Use user feedback for... whatever!! - } -); + ] +).then((answers: inquirer.Answers) => { + // Use user feedback for... whatever!! +}); // // examples/bottom-bar.js @@ -87,11 +86,10 @@ inquirer.prompt<{ toppings: string }>( return true; } } - ], - function(answers) { - console.log(JSON.stringify(answers, null, " ")); - } -); + ] +).then(answers => { + console.log(JSON.stringify(answers, null, " ")); +}); // // examples/expand.js @@ -134,11 +132,10 @@ inquirer.prompt( } ] } - ], - function(answers: inquirer.Answers) { - console.log(JSON.stringify(answers, null, " ")); - } -); + ] +).then((answers: inquirer.Answers) => { + console.log(JSON.stringify(answers, null, " ")); +}); // // examples/input.js @@ -184,9 +181,9 @@ var questions = [ } ]; -inquirer.prompt(questions, function(answers) { - console.log(JSON.stringify(answers, null, " ")); -}); +inquirer.prompt(questions).then( + answers => console.log(JSON.stringify(answers, null, " ")) +); // // examples/list.js @@ -222,11 +219,10 @@ inquirer.prompt( return val.toLowerCase(); } } - ], - function(answers: inquirer.Answers) { - console.log(JSON.stringify(answers, null, " ")); - } -); + ] +).then((answers: inquirer.Answers) => { + console.log(JSON.stringify(answers, null, " ")); +}); // // examples/long-list.js @@ -263,11 +259,10 @@ inquirer.prompt( paginated: true, choices: choices } - ], - function(answers: inquirer.Answers) { - console.log(JSON.stringify(answers, null, " ")); - } -); + ] +).then((answers: inquirer.Answers) => { + console.log(JSON.stringify(answers, null, " ")); +}); // // examples/nested-call.js @@ -286,16 +281,15 @@ inquirer.prompt( name: "chocolate", message: "What's your favorite chocolate?", choices: ["Mars", "Oh Henry", "Hershey"] - }, - function(answers: inquirer.Answers) { - inquirer.prompt({ - type: "list", - name: "beverage", - message: "And your favorite beverage?", - choices: ["Pepsi", "Coke", "7up", "Mountain Dew", "Red Bull"] - }); } -); +).then((answers: inquirer.Answers) => { + inquirer.prompt({ + type: "list", + name: "beverage", + message: "And your favorite beverage?", + choices: ["Pepsi", "Coke", "7up", "Mountain Dew", "Red Bull"] + }); +}); // // examples/password.js @@ -315,11 +309,10 @@ inquirer.prompt( message: "Enter your git password", name: "password" } - ], - function(answers: inquirer.Answers) { - console.log(JSON.stringify(answers, null, " ")); - } -); + ] +).then((answers: inquirer.Answers) => { + console.log(JSON.stringify(answers, null, " ")); +}); // // examples/pizza.js @@ -421,7 +414,7 @@ var questions2 = [ } ]; -inquirer.prompt(questions, function(answers) { +inquirer.prompt(questions).then(answers => { console.log("\nOrder receipt:"); console.log(JSON.stringify(answers, null, " ")); }); @@ -460,11 +453,10 @@ inquirer.prompt( return val.toLowerCase(); } } - ], - function(answers: inquirer.Answers) { - console.log(JSON.stringify(answers, null, " ")); - } -); + ] +).then((answers: inquirer.Answers) => { + console.log(JSON.stringify(answers, null, " ")); +}); // // examples/recursive.js @@ -495,9 +487,8 @@ var questions3 = [ ]; function ask() { - inquirer.prompt<{ tvShow: string; askAgain: boolean }>(questions3, function( - answers - ) { + inquirer.prompt<{ tvShow: string; askAgain: boolean }>(questions3) + .then((answers) => { output2.push(answers.tvShow); if (answers.askAgain) { ask(); @@ -560,7 +551,7 @@ function likesFood(aFood: string) { }; } -inquirer.prompt(questions, function(answers) { +inquirer.prompt(questions).then(answers => { console.log(JSON.stringify(answers, null, " ")); }); @@ -579,11 +570,10 @@ inquirer.prompt( message: 'What do you want to do?', choices: immutableChoices } - ], - function(answers: inquirer.Answers) { - console.log(JSON.stringify(answers, null, ' ')); - } -); + ] +).then((answers: inquirer.Answers) => { + console.log(JSON.stringify(answers, null, ' ')); +}); // // Other tests not covered in the examples provided with inquirer @@ -667,9 +657,10 @@ var questions = [ } ]; -inquirer.createPromptModule({ output: process.stderr })(questions, function(answers) { - console.log(JSON.stringify(answers, null, " ")); -}); +inquirer.createPromptModule({ output: process.stderr })(questions) + .then(answers => { + console.log(JSON.stringify(answers, null, " ")); + }); // Work with JS inquirer but rejected by typing. inquirer.prompt([ diff --git a/types/inquirer/package.json b/types/inquirer/package.json new file mode 100644 index 0000000000..021b40d754 --- /dev/null +++ b/types/inquirer/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "rxjs": ">=6.4.0" + } +} diff --git a/types/yeoman-generator/index.d.ts b/types/yeoman-generator/index.d.ts index fe39171825..0332eab033 100644 --- a/types/yeoman-generator/index.d.ts +++ b/types/yeoman-generator/index.d.ts @@ -7,6 +7,7 @@ // Arthur Corenzan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 +/// import { EventEmitter } from 'events'; import * as inquirer from 'inquirer'; From 545ee9c7869a6be3481ab3d92ad097c1bbfaa606 Mon Sep 17 00:00:00 2001 From: AntoineDoubovetzky Date: Sun, 17 Mar 2019 12:03:35 +0100 Subject: [PATCH 026/337] create react-scrollable-anchor package --- types/react-scrollable-anchor/index.d.ts | 26 ++++++++++ .../react-scrollable-anchor-tests.tsx | 47 +++++++++++++++++++ types/react-scrollable-anchor/tsconfig.json | 24 ++++++++++ types/react-scrollable-anchor/tslint.json | 1 + 4 files changed, 98 insertions(+) create mode 100644 types/react-scrollable-anchor/index.d.ts create mode 100644 types/react-scrollable-anchor/react-scrollable-anchor-tests.tsx create mode 100644 types/react-scrollable-anchor/tsconfig.json create mode 100644 types/react-scrollable-anchor/tslint.json diff --git a/types/react-scrollable-anchor/index.d.ts b/types/react-scrollable-anchor/index.d.ts new file mode 100644 index 0000000000..9459918b15 --- /dev/null +++ b/types/react-scrollable-anchor/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for react-scrollable-anchor 0.6 +// Project: https://github.com/gabergg/react-scrollable-anchor +// Definitions by: Antoine DOUBOVETZKY +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export interface ScrollableAnchorProps { + id: string; + children?: React.ReactNode; +} + +declare const ScrollableAnchor: React.ComponentType; + +export interface ConfigureAnchorsOptions { + offset?: number; + scrollDuration?: number; + keepLastAnchorHash?: boolean; +} + +export default ScrollableAnchor; +export function goToTop(): void; +export function configureAnchors(options: ConfigureAnchorsOptions): void; +export function goToAnchor(anchorId: string, saveHashUpdate?: boolean): void; +export function removeHash(): void; diff --git a/types/react-scrollable-anchor/react-scrollable-anchor-tests.tsx b/types/react-scrollable-anchor/react-scrollable-anchor-tests.tsx new file mode 100644 index 0000000000..984a01f741 --- /dev/null +++ b/types/react-scrollable-anchor/react-scrollable-anchor-tests.tsx @@ -0,0 +1,47 @@ +import * as React from 'react'; +import ScrollableAnchor, { goToAnchor, goToTop, removeHash, configureAnchors } from "react-scrollable-anchor"; + +/* + * goToAnchor + */ +// $ExpectType void +goToAnchor("one"); +// $ExpectError +goToAnchor(1); + +/* + * goToTop + */ +// $ExpectType void +goToTop(); +// $ExpectError +goToTop(1); + +/* + * removeHash + */ +// $ExpectType void +removeHash(); +// $ExpectError +removeHash(1); + +/* + * configureAnchors + */ +// $ExpectType void +configureAnchors({ offset: 500, scrollDuration: 1000, keepLastAnchorHash: true }); +// $ExpectError +configureAnchors(); +// $ExpectError +configureAnchors({ wrongKey: 1 }); +// $ExpectError +configureAnchors({ offset: 'string' }); +// $ExpectError +configureAnchors({ scrollDuration: 'string' }); +// $ExpectError +configureAnchors({ keepLastAnchorHash: 3 }); + +// $ExpectError +
Test
; + +
Test
; diff --git a/types/react-scrollable-anchor/tsconfig.json b/types/react-scrollable-anchor/tsconfig.json new file mode 100644 index 0000000000..198bad7412 --- /dev/null +++ b/types/react-scrollable-anchor/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "strictFunctionTypes": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-scrollable-anchor-tests.tsx" + ] +} diff --git a/types/react-scrollable-anchor/tslint.json b/types/react-scrollable-anchor/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-scrollable-anchor/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f7b7ec584b8a0d4a861c562cba859e46944eaa2a Mon Sep 17 00:00:00 2001 From: Jeroen Claassens Date: Sun, 17 Mar 2019 13:44:23 +0100 Subject: [PATCH 027/337] Remove leven --- notNeededPackages.json | 6 ++++++ types/leven/index.d.ts | 8 -------- types/leven/leven-tests.ts | 7 ------- types/leven/tsconfig.json | 23 ----------------------- types/leven/tslint.json | 1 - 5 files changed, 6 insertions(+), 39 deletions(-) delete mode 100644 types/leven/index.d.ts delete mode 100644 types/leven/leven-tests.ts delete mode 100644 types/leven/tsconfig.json delete mode 100644 types/leven/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index 812d1f9f1b..2df1cad4ad 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -1068,6 +1068,12 @@ "sourceRepoURL": "https://github.com/stevemao/left-pad", "asOfVersion": "1.2.0" }, + { + "libraryName": "leven", + "typingsPackageName": "leven", + "sourceRepoURL": "https://github.com/sindresorhus/leven", + "asOfVersion": "3.0.0" + }, { "libraryName": "Linq.JS", "typingsPackageName": "linq", diff --git a/types/leven/index.d.ts b/types/leven/index.d.ts deleted file mode 100644 index bd7e0ba4aa..0000000000 --- a/types/leven/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for leven 2.1 -// Project: https://github.com/sindresorhus/leven -// Definitions by: Jan Alonzo -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare function leven(a: string, b: string): number; - -export = leven; diff --git a/types/leven/leven-tests.ts b/types/leven/leven-tests.ts deleted file mode 100644 index 4ca0406529..0000000000 --- a/types/leven/leven-tests.ts +++ /dev/null @@ -1,7 +0,0 @@ -import leven = require('leven'); - -leven('baz', 'bar'); -// => "1" - -leven('foo', 'bar'); -// => "3" diff --git a/types/leven/tsconfig.json b/types/leven/tsconfig.json deleted file mode 100644 index 14d505d892..0000000000 --- a/types/leven/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "leven-tests.ts" - ] -} \ No newline at end of file diff --git a/types/leven/tslint.json b/types/leven/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/leven/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } From b2a02eb2c6c8ce9dd8b2935d10d42e107e1cac2a Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sun, 17 Mar 2019 15:19:14 +0100 Subject: [PATCH 028/337] improve(slick-slider): add type for Slick instance itself --- types/slick-carousel/index.d.ts | 276 +++++++++++++++++++++++++++++++- 1 file changed, 275 insertions(+), 1 deletion(-) diff --git a/types/slick-carousel/index.d.ts b/types/slick-carousel/index.d.ts index b92b1e9930..02ab392268 100644 --- a/types/slick-carousel/index.d.ts +++ b/types/slick-carousel/index.d.ts @@ -1,11 +1,124 @@ // Type definitions for stick 1.6.0 // Project: http://kenwheeler.github.io/slick/ // Definitions by: John Gouigouix +// Hugo Alliaume // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// +interface JQuerySlick extends JQuerySlickInitials { + defaults: JQuerySlickOptions; + options: JQuerySlickOptions; + originalSettings: JQuerySlickOptions; + initials: JQuerySlickInitials; + + /** + * Default: null + */ + activeBreakpoint: number | null; + + /** + * Default: null + */ + animType: 'OTransform' | 'MozTransform' | 'webkitTransform' | 'msTransform' | 'transform' | false | null; + + /** + * Default: null + */ + animProp: null; + + /** + * Default: [] + */ + breakpoints: number[]; + + /** + * Default: {} + */ + breakpointSettings: { [breakpoint: number]: JQuerySlickOptions }; + + /** + * Default: false + */ + cssTransitions: boolean; + + /** + * Default: false + */ + focussed: boolean; + + /** + * Default: false + */ + interrupted: boolean; + + /** + * Default: 'hidden' + */ + hidden: 'mozHidden' | 'webkitHidden' | 'hidden'; + + /** + * Default: true + */ + paused: boolean; + + /** + * Default: null + */ + positionProp: 'top' | 'left' | null; + + /** + * Default: null + */ + respondTo: 'window' | 'slider' | 'min' | null; + + /** + * Default: 1 + */ + rowCount: number; + + /** + * Default: true + */ + shouldClick: boolean; + + /** + * Default: $(element) + */ + $slider: JQuery; + + /** + * Default: null + */ + $slidesCache: JQuery | null; + + /** + * Default: null + */ + transformType: '-o-transform' | '-moz-transform' | '-webkit-transform' | '-ms-transform' | 'transition' | null; + + /** + * Default: null + */ + transitionType: 'OTransition' | 'MozTransition' | 'webkitTransition' | 'msTransition' | 'transition' | null; + + /** + * Default: 'visibilitychange' + */ + visibilityChange: 'visibilitychange' | 'mozvisibilitychange' | 'webkitvisibilitychange'; + + /** + * Default: 0 + */ + windowWidth: number; + + /** + * Default: null + */ + windowTimer: number | null; +} + interface JQuerySlickOptions { /** @@ -298,9 +411,170 @@ interface JQuerySlickOptions { * Default: 1000 */ zIndex?: number; - + } +interface JQuerySlickInitials { + /** + * When there is an animation running. + * Default: false + */ + animating: boolean; + + /** + * When they user is dragging a slide. + * Default: false + */ + dragging: boolean; + + /** + * Internal `setInterval` identifier. + * Default: null + */ + autoPlayTimer: number|null; + + /** + * The current direction (`0` for left and down, `1` for right and up). + * Default: 0 + */ + currentDirection: number; + + /** + * Default: null + */ + currentLeft: number|null; + + /** + * The index of the current slide. + * Default: 0 + */ + currentSlide: number; + + /** + * The direction (`0` for left and down, `1` for right and up). + * Default: null + */ + direction: number; + + /** + * jQuery instance that contains the "dots". + * Default: null + */ + $dots: JQuery | null; + + /** + * The list's width in pixels. + * Default: null + */ + listWidth: number|null; + + /** + * The list's height in pixels. + * Default: null + */ + listHeight: number|null; + + /** + * (actually it's not used in Slick, so I don't know what it is...) + * Default: 0 + */ + loadIndex: number; + + /** + * jQuery instance that contains the "next arrow". + * Default: null + */ + $nextArrow: JQuery | null; + + /** + * jQuery instance that contains the "prev arrow". + * Default: null + */ + $prevArrow: JQuery | null; + + /** + * When they user is scrolling a slide. + * Default: false + */ + scrolling: boolean; + + /** + * The number of slides. + * Default: null + */ + slideCount: number | null; + + /** + * The slide's width in pixels. + * Default: null + */ + slideWidth: Number | null; + + /** + * jQuery instance that contains the "slide track". + * Default: null + */ + $slideTrack: JQuery | null; + + /** + * jQuery instance that contains the "slides". + * Default: null + */ + $slides: JQuery | null; + + /** + * When the slider is sliding. + * Default: false + */ + sliding: boolean; + + /** + * Slide offset in pixels. + * Default: 0 + */ + slideOffset: number; + + /** + * Default: null + */ + swipeLeft: number | null; + + /** + * Default: false + */ + swiping: boolean; + + /** + * jQuery instance that contains the "list". + * Default: null + */ + $list: null; + + /** + * Object that contains properties relative to "touch" behavior. + */ + touchObject: { + startX?: number; + startY?: number; + curX?: number; + curY?: number; + swipeLength?: number; + edgeHit?: boolean; + minSwipe?: number; + fingerCount?: number; + verticalSwiping?: boolean; + }; + + /** + * Default: false + */ + transformsEnabled: boolean; + + /** + * Default: false + */ + unslicked: boolean; +} interface JQuery { From 0c85c7ee5d9832b6295d4e33e30aec07275468f9 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sun, 17 Mar 2019 15:21:46 +0100 Subject: [PATCH 029/337] improve(slick-slider): use the new type as return type for a method --- types/slick-carousel/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/slick-carousel/index.d.ts b/types/slick-carousel/index.d.ts index 02ab392268..00b16ef69c 100644 --- a/types/slick-carousel/index.d.ts +++ b/types/slick-carousel/index.d.ts @@ -695,6 +695,6 @@ interface JQuery { * Get Slick Object * @param methodName The name of the method */ - slick(methodName: "getSlick"): Object; + slick(methodName: "getSlick"): JQuerySlick; } From a055ce78a5580204cf9279f9bee77358796233ba Mon Sep 17 00:00:00 2001 From: Richard Lea Date: Sun, 17 Mar 2019 21:04:36 +0900 Subject: [PATCH 030/337] fix(yeoman): rxjs dependency and typescript version TypeScript 2.8 is required for the dependency of rxjs 6 +, where conditional types are in usage, which is a main difference with the ancient rx library and this change point would make this library break without upgrade to typescript 2.8 Signed-off-by: Richard Lea --- types/yeoman-generator/index.d.ts | 7 ++++--- types/yeoman-generator/package.json | 6 ++++++ types/yeoman-test/index.d.ts | 2 +- 3 files changed, 11 insertions(+), 4 deletions(-) create mode 100644 types/yeoman-generator/package.json diff --git a/types/yeoman-generator/index.d.ts b/types/yeoman-generator/index.d.ts index 0332eab033..7d461e7b78 100644 --- a/types/yeoman-generator/index.d.ts +++ b/types/yeoman-generator/index.d.ts @@ -5,12 +5,13 @@ // Ika // Joshua Cherry // Arthur Corenzan +// Richard Lea // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 -/// +// TypeScript Version: 2.8 import { EventEmitter } from 'events'; import * as inquirer from 'inquirer'; +import { Observable } from 'rxjs'; type Callback = (err: any) => void; @@ -21,7 +22,7 @@ declare namespace Generator { */ store?: boolean; } - type Questions = Question | Question[] | Rx.Observable; + type Questions = Question | Question[] | Observable; type Answers = inquirer.Answers; class Storage { diff --git a/types/yeoman-generator/package.json b/types/yeoman-generator/package.json new file mode 100644 index 0000000000..021b40d754 --- /dev/null +++ b/types/yeoman-generator/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "rxjs": ">=6.4.0" + } +} diff --git a/types/yeoman-test/index.d.ts b/types/yeoman-test/index.d.ts index acccfba1bb..3312f748ff 100644 --- a/types/yeoman-test/index.d.ts +++ b/types/yeoman-test/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/yeoman/yeoman-test, http://yeoman.io/authoring/testing.html // Definitions by: Ika // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import { EventEmitter } from 'events'; import Generator = require('yeoman-generator'); From 448b80df33285e2b90ff23f1aec9d7aa2284b574 Mon Sep 17 00:00:00 2001 From: Andrej Mihajlov Date: Sun, 17 Mar 2019 17:35:32 +0100 Subject: [PATCH 031/337] Update index.d.ts --- types/opentok/index.d.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/types/opentok/index.d.ts b/types/opentok/index.d.ts index 85b9794316..58fdfaa7ba 100644 --- a/types/opentok/index.d.ts +++ b/types/opentok/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/opentok/opentok-node // Definitions by: Seth Westphal // Anthony Messerschmidt +// Andrej Mihajlov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'opentok' { @@ -81,13 +82,13 @@ declare module 'opentok' { class OpenTok { constructor(apiKey: string, apiSecret: string); - public createSession(options: OpenTok.SessionOptions, callback: (err: Error, session: OpenTok.Session) => void): void; + public createSession(options: OpenTok.SessionOptions, callback: (error: Error | null, session?: OpenTok.Session) => void): void; public generateToken(sessionId: string, options: OpenTok.TokenOptions): OpenTok.Token; - public startArchive(sessionId: string, options: OpenTok.ArchiveOptions, callback: (err: Error, archive: OpenTok.Archive) => void): void; - public stopArchive(archiveId: string, callback: (err: Error, archive: OpenTok.Archive) => void): void; - public getArchive(archiveId: string, callback: (err: Error, archive: OpenTok.Archive) => void): void; - public deleteArchive(archiveId: string, callback: (err: Error) => void): void; - public listArchives(options: OpenTok.ListArchivesOptions, callback: (err: Error, archives: OpenTok.Archive[], totalCount: number) => void): void; + public startArchive(sessionId: string, options: OpenTok.ArchiveOptions, callback: (error: Error | null, archive?: OpenTok.Archive) => void): void; + public stopArchive(archiveId: string, callback: (error: Error | null, archive?: OpenTok.Archive) => void): void; + public getArchive(archiveId: string, callback: (error: Error | null, archive?: OpenTok.Archive) => void): void; + public deleteArchive(archiveId: string, callback: (error: Error | null) => void): void; + public listArchives(options: OpenTok.ListArchivesOptions, callback: (error: Error | null, archives?: OpenTok.Archive[], totalCount?: number) => void): void; } export = OpenTok; From 927e8941861dc491281ffafd7c1aa2e07b47982c Mon Sep 17 00:00:00 2001 From: Aleksandr Terentev Date: Mon, 18 Mar 2019 19:56:18 +0300 Subject: [PATCH 032/337] fix types for enzyme's hasClass --- types/enzyme/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 71238871c7..20e25853f9 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -88,7 +88,7 @@ export interface CommonWrapper

> { /** * Returns whether or not the current node has a className prop including the passed in class name. */ - hasClass(className: string): boolean; + hasClass(className: string | RegExp): boolean; /** * Returns whether or not the current node matches a provided selector. From fc665e5df4265c7674162066a39a918890c5ce14 Mon Sep 17 00:00:00 2001 From: Alec Larson Date: Mon, 18 Mar 2019 14:45:48 -0400 Subject: [PATCH 033/337] [lolex] make TClock default to Clock Remove the need for explicit type annotations by defaulting to "lolex.Clock" --- types/lolex/index.d.ts | 12 ++++++------ types/lolex/lolex-tests.ts | 5 +++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/types/lolex/index.d.ts b/types/lolex/index.d.ts index 1a33a60c7d..5eed89d978 100644 --- a/types/lolex/index.d.ts +++ b/types/lolex/index.d.ts @@ -128,7 +128,7 @@ export interface LolexClock extends GlobalTimers = TClock & InstalledMethods; +type InstalledClock = TClock & InstalledMethods; /** * Creates a clock. @@ -268,7 +268,7 @@ type InstalledClock = TClock & InstalledMethods; * @type TClock Type of clock to create. * @remarks The default epoch is 0. */ -export declare function createClock(now?: number | Date, loopLimit?: number): TClock; +export declare function createClock(now?: number | Date, loopLimit?: number): TClock; export interface LolexInstallOpts { /** @@ -312,12 +312,12 @@ export interface LolexInstallOpts { * @param toFake Names of methods that should be faked. * @type TClock Type of clock to create. */ -export declare function install(opts?: LolexInstallOpts): InstalledClock; +export declare function install(opts?: LolexInstallOpts): InstalledClock; export interface LolexWithContext { timers: GlobalTimers; - createClock: (now?: number | Date, loopLimit?: number) => TClock; - install: (opts?: LolexInstallOpts) => InstalledClock; + createClock: (now?: number | Date, loopLimit?: number) => TClock; + install: (opts?: LolexInstallOpts) => InstalledClock; withGlobal: (global: Object) => LolexWithContext; } diff --git a/types/lolex/lolex-tests.ts b/types/lolex/lolex-tests.ts index d09cfcc042..f808283e5b 100644 --- a/types/lolex/lolex-tests.ts +++ b/types/lolex/lolex-tests.ts @@ -138,3 +138,8 @@ nodeInstalledClock.uninstall(); // Clocks should be typed to have unbound method signatures that can be passed around const { clearTimeout } = browserClock; clearTimeout(0); + +// TClock of InstalledClock is optional. +let installedClock: lolex.InstalledClock; +installedClock = nodeInstalledClock; +installedClock = browserInstalledClock; From a50f818644109f3890c22e0ef5e33015038c3b71 Mon Sep 17 00:00:00 2001 From: Alec Larson Date: Mon, 18 Mar 2019 14:57:53 -0400 Subject: [PATCH 034/337] [lolex] set minimum version to 2.3 --- types/lolex/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/lolex/index.d.ts b/types/lolex/index.d.ts index 5eed89d978..703b0b9809 100644 --- a/types/lolex/index.d.ts +++ b/types/lolex/index.d.ts @@ -5,6 +5,7 @@ // Rogier Schouten // Yishai Zehavi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /** * Names of clock methods that may be faked by install. From 72c711715ae94a1492d78d821aa03e9db1cbc610 Mon Sep 17 00:00:00 2001 From: Diamond Lewis Date: Mon, 18 Mar 2019 14:22:58 -0500 Subject: [PATCH 035/337] 2.2.1 --- types/parse/index.d.ts | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index b87a9f5f56..008ce67def 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for parse 2.1.0 +// Type definitions for parse 2.2.1 // Project: https://parseplatform.org/ // Definitions by: Ullisen Media Group // David Poetzsch-Heffter @@ -8,6 +8,7 @@ // Otherwise SAS // Andrew Goldis // Alexandre Hétu Rivard +// Diamond Lewis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -959,6 +960,22 @@ subscription.on('close', () => {}); */ function setAsyncStorage(AsyncStorage: any): void; + /** + * Gets all contents from Local Datastore. + */ + function dumpLocalDatastore(): any; + + /** + * Enable pinning in your application. + * This must be called before your application can use pinning. + */ + function enableLocalDatastore(): void; + + /** + * Flag that indicates whether Local Datastore is enabled. + */ + function isLocalDatastoreEnabled(): any; + } declare module "parse/node" { From 0c4fe5b002bb833f01eb0c253db4bd0a5ba0ba02 Mon Sep 17 00:00:00 2001 From: Haseeb Majid Date: Mon, 18 Mar 2019 22:54:01 +0000 Subject: [PATCH 036/337] Updated Definition --- types/react-native-canvas/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-native-canvas/index.d.ts b/types/react-native-canvas/index.d.ts index 559b986ba8..65b80277ee 100644 --- a/types/react-native-canvas/index.d.ts +++ b/types/react-native-canvas/index.d.ts @@ -176,8 +176,8 @@ export class Image { export class ImageData { constructor(canvas: Canvas, data: number[], height: number, width: number); readonly data: number[]; - readonly height: number; - readonly width: number; + readonly height: number | undefined; + readonly width: number | undefined; } export class Path2D { From 519e5f209c4d39667b3f7cb9185a77c881d97808 Mon Sep 17 00:00:00 2001 From: Diamond Lewis Date: Mon, 18 Mar 2019 19:30:22 -0500 Subject: [PATCH 037/337] add missing features --- types/parse/index.d.ts | 64 ++++++++++++++++++++++++++++------- types/parse/parse-tests.ts | 69 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 118 insertions(+), 15 deletions(-) diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index 1aa9cb1546..6c3aa122f1 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -266,19 +266,26 @@ declare namespace Parse { constructor(className?: string, options?: any); constructor(attributes?: string[], options?: any); - static extend(className: string, protoProps?: any, classProps?: any): any; - static fromJSON(json: any, override: boolean): any; - + static createWithoutData(id: string): T; + static destroyAll(list: T[], options?: Object.DestroyAllOptions): Promise; + static extend(className: string, protoProps?: any, classProps?: any): any; static fetchAll(list: T[], options: Object.FetchAllOptions): Promise; static fetchAllIfNeeded(list: T[], options: Object.FetchAllOptions): Promise; - static destroyAll(list: T[], options?: Object.DestroyAllOptions): Promise; - static saveAll(list: T[], options?: Object.SaveAllOptions): Promise; + static fetchAllWithInclude(list: any, keys: any, options: any): any; + static fromJSON(json: any, override: boolean): any; + static pinAll(objects: Object[]): Promise; + static pinAllWithName(name: string, objects: Object[]): Promise; static registerSubclass(className: string, clazz: new (options?: any) => T): void; - static createWithoutData(id: string): T; + static saveAll(list: T[], options?: Object.SaveAllOptions): Promise; + static unPinAll(objects: any): Promise; + static unPinAllObjects(): Promise; + static unPinAllObjectsWithName(name: string): Promise; + static unPinAllWithName(...args: any[]): Promise; - initialize(): void; add(attr: string, item: any): this; - addUnique(attr: string, item: any): any; + addAll(attr: string, items: any[]): this; + addAllUnique(attr: string, items: any[]): this; + addUnique(attr: string, item: any): this; change(options: any): this; changedAttributes(diff: any): boolean; clear(options: any): any; @@ -286,21 +293,29 @@ declare namespace Parse { destroy(options?: Object.DestroyOptions): Promise; dirty(attr?: string): boolean; dirtyKeys(): string[]; + equals(other: any): boolean; escape(attr: string): string; existed(): boolean; fetch(options?: Object.FetchOptions): Promise; + fetchFromLocalDatastore(): Promise | void; + fetchWithInclude(keys: string[], options?: any): Promise; get(attr: string): any | undefined; getACL(): ACL | undefined; has(attr: string): boolean; hasChanged(attr: string): boolean; increment(attr: string, amount?: number): any; + initialize(): void; isNew(): boolean; + isPinned(...args: any[]): Promise; isValid(): boolean; op(attr: string): any; + pin(): Promise; + pinWithName(name: string): Promise; previous(attr: string): any; previousAttributes(): any; relation(attr: string): Relation; remove(attr: string, item: any): any; + removeAll(attr: string, items: any): any; revert(): void; save(attrs?: { [key: string]: any } | null, options?: Object.SaveOptions): Promise; save(key: string, value: any, options?: Object.SaveOptions): Promise; @@ -309,6 +324,8 @@ declare namespace Parse { set(attrs: object, options?: Object.SetOptions): boolean; setACL(acl: ACL, options?: SuccessFailureOptions): boolean; toPointer(): Pointer; + unPin(): Promise; + unPinWithName(name: string): Promise; unset(attr: string, options?: any): any; validate(attrs: any, options?: SuccessFailureOptions): boolean; } @@ -331,6 +348,11 @@ declare namespace Parse { } } + class Polygon extends BaseObject { + constructor(arg1: GeoPoint[] | number[][]); + containsPoint(point: GeoPoint): boolean; + equals(other: Polygon | any): boolean; + } /** * Every Parse application installed on a device registered for * push notifications has an associated Installation object. @@ -415,18 +437,23 @@ declare namespace Parse { constructor(objectClass: string); constructor(objectClass: new (...args: any[]) => T); + static and(...args: Query[]): Query; + static fromJSON(className: any, json: any): Query; + static nor(...args: Query[]): Query; static or(...var_args: Query[]): Query; - aggregate(pipeline: Query.AggregationOptions|Query.AggregationOptions[]): Query; addAscending(key: string): Query; addAscending(key: string[]): Query; addDescending(key: string): Query; addDescending(key: string[]): Query; ascending(key: string): Query; ascending(key: string[]): Query; + aggregate(pipeline: Query.AggregationOptions|Query.AggregationOptions[]): Query; + containedBy(key: string, values: any[]): Query; containedIn(key: string, values: any[]): Query; contains(key: string, substring: string): Query; containsAll(key: string, values: any[]): Query; + containsAllStartingWith(key: string, values: any[]): Query; count(options?: Query.CountOptions): Promise; descending(key: string): Query; descending(key: string[]): Query; @@ -440,12 +467,16 @@ declare namespace Parse { exists(key: string): Query; find(options?: Query.FindOptions): Promise; first(options?: Query.FirstOptions): Promise; + fromLocalDatastore(): void; + fromPin(): void; + fromPinWithName(name: string): void; fullText(key: string, value: string, options?: Query.FullTextOptions): Query; get(objectId: string, options?: Query.GetOptions): Promise; greaterThan(key: string, value: any): Query; greaterThanOrEqualTo(key: string, value: any): Query; include(key: string): Query; include(keys: string[]): Query; + includeAll(): Query; lessThan(key: string, value: any): Query; lessThanOrEqualTo(key: string, value: any): Query; limit(n: number): Query; @@ -455,13 +486,17 @@ declare namespace Parse { near(key: string, point: GeoPoint): Query; notContainedIn(key: string, values: any[]): Query; notEqualTo(key: string, value: any): Query; + polygonContains(key: string, point: GeoPoint): Query; select(...keys: string[]): Query; skip(n: number): Query; + sortByTextScore(): any; startsWith(key: string, prefix: string): Query; subscribe(): LiveQuerySubscription; + withJSON(json: any): any; withinGeoBox(key: string, southwest: GeoPoint, northeast: GeoPoint): Query; withinKilometers(key: string, point: GeoPoint, maxDistance: number): Query; withinMiles(key: string, point: GeoPoint, maxDistance: number): Query; + withinPolygon(key: string, points: GeoPoint[]): Query; withinRadians(key: string, point: GeoPoint, maxDistance: number): Query; } @@ -599,6 +634,7 @@ subscription.on('close', () => {}); class Config extends Object { static get(options?: SuccessFailureOptions): Promise; static current(): Config; + static save(attr: any): Promise; get(attr: string): any; escape(attr: string): any; @@ -622,15 +658,16 @@ subscription.on('close', () => {}); */ class User extends Object { + static allowCustomUserClass(isAllowed: boolean): void; + static become(sessionToken: string, options?: SuccessFailureOptions): Promise; static current(): User | undefined; static currentAsync(): 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; - static become(sessionToken: string, options?: SuccessFailureOptions): Promise; static requestPasswordReset(email: string, options?: SuccessFailureOptions): Promise; static extend(protoProps?: any, classProps?: any): any; + static hydrate(userJSON: any): Promise; signUp(attrs: any, options?: SignUpOptions): Promise; logIn(options?: SuccessFailureOptions): Promise; @@ -965,7 +1002,7 @@ subscription.on('close', () => {}); /** * Gets all contents from Local Datastore. */ - function dumpLocalDatastore(): any; + function dumpLocalDatastore(): Promise<{ [key: string]: any }>; /** * Enable pinning in your application. @@ -976,8 +1013,9 @@ subscription.on('close', () => {}); /** * Flag that indicates whether Local Datastore is enabled. */ - function isLocalDatastoreEnabled(): any; + function isLocalDatastoreEnabled(): boolean; + function setLocalDatastoreController(controller: any): void; } declare module "parse/node" { diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index 1c430b1807..1b91772746 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -14,6 +14,10 @@ class Game extends Parse.Object { } } +function test_config() { + Parse.Config.save({ foo: 'bar' }); +} + function test_object() { const game = new Game(); @@ -51,10 +55,18 @@ function test_object() { gameScore.increment("score"); gameScore.addUnique("skills", "flying"); gameScore.addUnique("skills", "kungfu"); - + gameScore.addAll("skills", ["kungfu"]); + gameScore.addAllUnique("skills", ["kungfu"]); + gameScore.remove('skills', 'flying'); + gameScore.removeAll('skills', ["kungFu"]); game.set("gameScore", gameScore); const gameCopy = Game.fromJSON(JSON.parse(JSON.stringify(game)), true); + + const object = new Parse.Object('TestObject'); + object.equals(gameScore); + object.fetchWithInclude(['key1', 'key2']); + } function test_query() { @@ -87,6 +99,7 @@ function test_query() { // Restricts to wins >= 50 query.greaterThanOrEqualTo("wins", 50); + query.containedBy('place', ['1', '2']); // Finds scores from any of Jonathan, Dario, or Shawn query.containedIn("playerName", ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]); @@ -109,13 +122,15 @@ function test_query() { // Find objects where the array in arrayKey contains all of the elements 2, 3, and 4. query.containsAll("arrayKey", [2, 3, 4]); + query.containsAllStartingWith("arrayKey", [2, 3, 4]); query.startsWith("name", "Big Daddy's"); query.equalTo("score", gameScore); query.exists("score"); query.include("score"); query.include(["score.team"]); - + query.includeAll(); + query.sortByTextScore(); // Find objects that match the aggregation pipeline query.aggregate({ group:{ @@ -254,6 +269,12 @@ function test_user_acl_roles() { // The token could not be validated. }); + Parse.User.hydrate({}).then(function (user) { + // The current user is now set to user. + }, function (error) { + // The token could not be validated. + }); + const game = new Game(); game.set("score", new GameScore()); game.setACL(new Parse.ACL(Parse.User.current())); @@ -517,3 +538,47 @@ function test_query_subscribe() { // unsubscribe subscription.unsubscribe(); } + +function test_serverURL() { + Parse.serverURL = 'http://localhost:1337/parse'; +} +function test_polygon() { + const point = new Parse.GeoPoint(1,2); + const polygon1 = new Parse.Polygon([[0,0], [1,0], [1,1], [0,1]]); + const polygon2 = new Parse.Polygon([point, point, point]); + polygon1.equals(polygon2); + polygon1.containsPoint(point); + + const query = new Parse.Query('TestObject'); + query.polygonContains('key', point); + query.withinPolygon('key', [point, point, point]); +} + +async function test_local_datastore() { + Parse.enableLocalDatastore(); + const name = 'test_pin'; + const obj = new Parse.Object('TestObject'); + await obj.pin(); + await obj.unPin(); + await obj.isPinned(); + await obj.pinWithName(name); + await obj.unPinWithName(name); + await obj.fetchFromLocalDatastore(); + + await Parse.Object.pinAll([obj]); + await Parse.Object.unPinAll([obj]); + await Parse.Object.pinAllWithName(name, [obj]); + await Parse.Object.unPinAllWithName(name, [obj]); + await Parse.Object.unPinAllObjects(); + await Parse.Object.unPinAllObjectsWithName(name); + + const flag = Parse.isLocalDatastoreEnabled(); + const LDS = await Parse.dumpLocalDatastore(); + + const query = new Parse.Query('TestObject'); + query.fromPin(); + query.fromPinWithName(name); + query.fromLocalDatastore(); + + Parse.setLocalDatastoreController({}); +} From c1201dbdcf1684648584009efbc3c9d907ba62c8 Mon Sep 17 00:00:00 2001 From: Farzad Majidfayyaz Date: Mon, 18 Mar 2019 22:49:03 -0400 Subject: [PATCH 038/337] Add types for 'clui' package --- types/clui/clui-tests.ts | 96 ++++++++++++++++++++++++ types/clui/index.d.ts | 157 +++++++++++++++++++++++++++++++++++++++ types/clui/tsconfig.json | 24 ++++++ types/clui/tslint.json | 1 + 4 files changed, 278 insertions(+) create mode 100644 types/clui/clui-tests.ts create mode 100644 types/clui/index.d.ts create mode 100644 types/clui/tsconfig.json create mode 100644 types/clui/tslint.json diff --git a/types/clui/clui-tests.ts b/types/clui/clui-tests.ts new file mode 100644 index 0000000000..1968b10cba --- /dev/null +++ b/types/clui/clui-tests.ts @@ -0,0 +1,96 @@ +import { Gauge, Line, LineBuffer, Progress, Sparkline, Spinner } from 'clui'; +import * as clc from 'cli-color'; + +// LineBuffer +const outputBuffer = new LineBuffer({ + x: 0, + y: 0, + width: 'console', + height: 'console' +}); + +new Line(outputBuffer) + .column('Title Placehole', 20, [clc.green]) + .fill() + .store(); + +new Line(outputBuffer) + .fill() + .store(); + +new Line(outputBuffer) + .column('Suscipit', 20, [clc.cyan]) + .column('Voluptatem', 20, [clc.cyan]) + .column('Nesciunt', 20, [clc.cyan]) + .column('Laudantium', 11, [clc.cyan]) + .fill() + .store(); + +for (let l = 0; l < 20; l++) { + new Line(outputBuffer) + .column((Math.random() * 100).toFixed(3), 20) + .column((Math.random() * 100).toFixed(3), 20) + .column((Math.random() * 100).toFixed(3), 20) + .column((Math.random() * 100).toFixed(3), 11) + .fill() + .store(); +} + +outputBuffer.output(); + +// Line +new Line() + .padding(2) + .column('Column One', 20, [clc.cyan]) + .column('Column Two', 20, [clc.cyan]) + .column('Column Three', 20, [clc.cyan]) + .column('Column Four', 20, [clc.cyan]) + .fill() + .output(); + +new Line() + .padding(2) + .column((Math.random() * 100).toFixed(3), 20) + .column((Math.random() * 100).toFixed(3), 20) + .column((Math.random() * 100).toFixed(3), 20) + .column((Math.random() * 100).toFixed(3), 20) + .fill() + .output(); + +// Gauge +const total = 33660133376; +const free = 17763860480; +const used = total - free; +const human = Math.ceil(used / 1000000) + ' MB'; + +console.log(Gauge(used, total, 20, total * 0.8, human)); + +// Sparkline +const reqsPerSec = [10, 12, 3, 7, 12, 9, 23, 10, 9, 19, 16, 18, 12, 12]; + +console.log(Sparkline(reqsPerSec, 'reqs/sec')); + +// Progress +const thisProgressBar = new Progress(20); +console.log(thisProgressBar.update(10, 30)); + +// or + +const thisPercentBar = new Progress(20); +console.log(thisPercentBar.update(0.4)); + +// Spinner +const countdown = new Spinner('Exiting in 10 seconds... ', ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷']); + +countdown.start(); + +let n = 10; +const interval = setInterval(() => { + n--; + countdown.message(`Exiting in ${n} seconds...`); + if (n === 0) { + console.log('\n'); + countdown.stop(); + clearInterval(interval); + } +}, 1000); diff --git a/types/clui/index.d.ts b/types/clui/index.d.ts new file mode 100644 index 0000000000..339ac031d9 --- /dev/null +++ b/types/clui/index.d.ts @@ -0,0 +1,157 @@ +// Type definitions for clui 0.3 +// Project: https://github.com/nathanpeck/clui#readme +// Definitions by: Farzad Majidfayyaz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as clc from 'cli-color'; + +export interface LineBufferOptions { + x?: number; + y?: number; + width?: number | 'console'; + height?: number | 'console'; + scroll?: number; +} + +export class LineBuffer { + /** + * Creates an object for buffering a group of text lines and then outputting them + * @param options Values to build the buffer + */ + constructor(options: LineBufferOptions); + + /** + * Return the height of the `LineBuffer`, when specified as `console` + */ + height(): number; + + /** + * Return the width of the `LineBuffer`, when specified as `console` + */ + width(): number; + + /** + * Put a `Line` object into the `LineBuffer` + * @param line The line object to put into the buffer + */ + addLine(line: Line): void; + + /** + * If you don't have enough lines in the buffer, this will fill the reset of + * the lines with empty spaces + */ + fill(): void; + + /** + * Draw the `LineBuffer` to screen + */ + output(): void; +} + +/** + * This chainable object can be used to generate a line of text with columns, padding, and fill + */ +export class Line { + /** + * Create a new instance of Line object + * @param buffer Object to be used as buffer + */ + constructor(buffer?: LineBuffer); + + /** + * Output `width` characters of blank space + * @param width Number of characters to print + */ + padding(width: number): Line; + + /** + * Output text within a column of the specified width + * @param text Text to print + * @param width Width of the column + * @param styles List of `cli-color` styles to apply + */ + column(text: string, width: number, styles?: clc.Format[]): Line; + + /** + * At the end of a line, fill the rest of the columns to the right edge + */ + fill(): Line; + + /** + * Print the generated line of text to the console + */ + output(): Line; + + /** + * Return the contents of this line as a string + */ + contents(): string; + + /** + * Store this line into the buffer + */ + store(): void; +} + +/** + * Creates a basic horizontal gauge to the screen + * @param value The current value of the metric being displayed by this gauge + * @param maxValue The highest possible value of the metric being displayed + * @param guageWidth How many columns widt to draw the gauge + * @param dangerZone The point after which the value will be drawn in red because it's too high + * @param suffix A value to output after the gauge itself + */ +export function Gauge( + value: number, + maxValue: number, + guageWidth: number, + dangerZone: number, + suffix: string, +): string; + +/** + * A simple command line sparkline that draws a series of values, and highlights the peak for the period + * @param values An array of values to go into the sparkline + * @param suffix A suffix to use when drawing the current and max values at the end of the sparkline + */ +export function Sparkline(values: number[], suffix: string): string; + +export class Progress { + /** + * Creates a progress bar + * @param length The desired length of the progress bar in characters + */ + constructor(length: number); + + /** + * Returns the progress bar min/max context to write to stdout + * @param currentValueOrPercent Current value (or percent) of the progress bar + * @param maxValue Maximum value of the progress bar + */ + update(currentValueOrPercent: number, maxValue?: number): string; +} + +export class Spinner { + /** + * Creates a new spinner + * @param statusText The default text to display while the spinner is spinning + * @param style Array of graphical characters used to draw the spinner + */ + constructor(statusText: string, style?: string[]); + + /** + * Show the spinner on the screen + */ + start(): void; + + /** + * Update the status message that follows the spinner + * @param statusMessage Message to be displayed + */ + message(statusMessage: string): void; + + /** + * Erase the spinner from the screen + */ + stop(): void; +} diff --git a/types/clui/tsconfig.json b/types/clui/tsconfig.json new file mode 100644 index 0000000000..05235b1de8 --- /dev/null +++ b/types/clui/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "clui-tests.ts" + ] +} diff --git a/types/clui/tslint.json b/types/clui/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clui/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From fdc13d05d3fb31de472d1c8f2035659c1a8e000e Mon Sep 17 00:00:00 2001 From: Jack Works Date: Tue, 19 Mar 2019 13:24:53 +0800 Subject: [PATCH 039/337] Update to include Gun.SEA & user APIs --- types/gun/gun-tests.ts | 48 ++++++++++ types/gun/index.d.ts | 204 ++++++++++++++++++++++++++++++++++++----- 2 files changed, 230 insertions(+), 22 deletions(-) diff --git a/types/gun/gun-tests.ts b/types/gun/gun-tests.ts index d196fba695..3c9eb0e55e 100644 --- a/types/gun/gun-tests.ts +++ b/types/gun/gun-tests.ts @@ -28,7 +28,9 @@ interface AppState { object: { num: number; str: string; + /** Comment test */ bool: boolean; + specstr: 'a' | 'b'; obj: { arr2: Array<{ foo: number; bar: string }>; }; @@ -47,6 +49,9 @@ app.get('object') .get('obj') .get('arr2') .set({ foo: 1, bar: '2' }); +app.get('object').put({ + bool: true +}); app.get('object') .get('bool') @@ -70,3 +75,46 @@ app.get('chatRoom').time!(msg => { }, 20); // $ExpectError app.get('object').time!({ a: 1 }); + +class X { + val: string; + b() {} +} +interface BadState { + // Top level primitives + a: 1; + b: { + // Ban functions + c: () => void; + // Ban class + d: typeof X; + // Recursive check for banned types + e: { + f: () => void; + }; + }; + // Filter, remove functions on prototype. + c: X; +} +const bad = new Gun(); +// $ExpectError +bad.get('a').put(1); +bad.get('b') + .get('c') + // $ExpectError + .put(() => {}); +bad.get('b') + .get('d') + // $ExpectError + .put(X); + +bad.get('b').put({ + // $ExpectError + c: () => {}, + // $ExpectError + d: X, + // $ExpectError + e: { + f: () => {} + } +}); diff --git a/types/gun/index.d.ts b/types/gun/index.d.ts index 51d02b68d5..176521acaa 100644 --- a/types/gun/index.d.ts +++ b/types/gun/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for gun 0.9 +// Type definitions for gun 0.9.9999991 // Project: https://github.com/amark/gun#readme // Definitions by: Jack Works // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -12,6 +12,30 @@ declare namespace Gun { /** Gun does not accept Array value, so we need extract to make types correct */ type AllowArray = ArrayOf extends never ? T : ArrayOf; type DisallowArray = ArrayOf extends never ? T : never; + /** These types cannot be stored on Gun */ + + type AlwaysDisallowedType = T extends (...args: any[]) => void + ? never + : T extends { new (...args: any[]): any } + ? never + : AccessObject; + type AccessObject = T extends object + ? { [key in keyof T]: (AlwaysDisallowedType extends never ? never : AccessObject) } + : T; + /** These types cannot be stored on Gun's root level */ + type DisallowPrimitives = Open extends false + ? T + : T extends string + ? never + : T extends number + ? never + : T extends boolean + ? never + : T extends null + ? never + : T extends undefined + ? never + : T; type ArrayAsRecord = ArrayOf extends never ? DataType : Record; /** * options['module name'] allows you to pass options to a 3rd party module. @@ -45,7 +69,8 @@ declare namespace Gun { }>; type Saveable = Partial | string | number | boolean | null | ChainReference; type AckCallback = (ack: { err: Error; ok: any } | { err: undefined; ok: string }) => void; - interface ChainReference { + interface ChainReference { + //#region API /** * Save data into gun, syncing it with your connected peers. * @@ -59,7 +84,10 @@ declare namespace Gun { * * @param callback invoked on each acknowledgment */ - put(data: DisallowArray, callback?: AckCallback): ChainReference; + put( + data: Partial>>>, + callback?: AckCallback + ): ChainReference; /** * Where to read data from. * @param key The key is the ID or property name of the data that you saved from earlier @@ -83,7 +111,7 @@ declare namespace Gun { /** the key, ID, or property name of the data. */ paramB: Record<'off' | 'to' | 'next' | 'the' | 'on' | 'as' | 'back' | 'rid' | 'id', any> ) => void - ): ChainReference; + ): ChainReference; /** * Change the configuration of the gun database instance. * @param options The options argument is the same object you pass to the constructor. @@ -115,7 +143,10 @@ declare namespace Gun { * To remove a listener call .off() on the same property or node. */ on( - callback: (data: ArrayAsRecord, key: ReferenceKey) => void, + callback: ( + data: DisallowPrimitives>>, + key: ReferenceKey + ) => void, option?: { change: boolean } | boolean ): ChainReference; /** @@ -123,7 +154,10 @@ declare namespace Gun { * @returns In the document, it said the return value may change in the future. Don't rely on it. */ once( - callback?: (data: (ArrayAsRecord) | undefined, key: ReferenceKey) => void, + callback?: ( + data: (DisallowPrimitives>>) | undefined, + key: ReferenceKey + ) => void, option?: { wait: number } ): ChainReference; /** @@ -136,11 +170,13 @@ declare namespace Gun { * **This means only objects, for now, are supported.** */ set( - data: DataType extends Array - ? U extends { [key: string]: any; [key: number]: any } - ? ArrayOf + data: AlwaysDisallowedType< + DataType extends Array + ? U extends { [key: string]: any; [key: number]: any } + ? ArrayOf + : never : never - : never, + >, callback?: AckCallback ): ChainReference>; /** @@ -157,8 +193,8 @@ declare namespace Gun { * Remove **all** listener on this node. */ off(): void; - - // Extended API + //#endregion + //#region Extended API /** * * Path does the same thing as `.get` but has some conveniences built in. @@ -256,15 +292,76 @@ declare namespace Gun { ): ChainReference; /** Pushes data to a Timegraph with it's time set to Gun.state()'s time */ time?(data: ArrayOf): void; + //#endregion + //#region User + /** + * Creates a new user and calls callback upon completion. + * @param alias Username or Alias which can be used to find a user. + * @param pass Passphrase that will be extended with PBKDF2 to make it a secure way to login. + * @param cb Callback that is to be called upon creation of the user. + * @param opt Option Object containing options for creation. (In gun options are added at end of syntax. opt is rarely used, hence is added at the end.) + */ + create( + alias: string, + pass: string, + cb?: (ack: { ok: 0; pub: string } | { err: string }) => void, + opt?: {} + ): ChainReference; + /** + * Authenticates a user, previously created via User.create. + * @param alias Username or Alias which can be used to find a user. + * @param pass Passphrase for the user + * @param cb Callback that is to be called upon authentication of the user. + * @param opt Option Object containing options for authentiaction. (In gun options are added at end of syntax. opt is rarely used, hence is added at the end.) + */ + auth( + alias: string, + pass: string, + cb?: ( + ack: + | { + ack: 2; + get: string; + on: (...args: [unknown, unknown, unknown]) => unknown; + put: { alias: string; auth: any; epub: string; pub: string }; + sea: CryptoKeyPair; + soul: string; + } + | { err: string } + ) => void, + opt?: {} + ): ChainReference; + /** + * Returns the key pair in the form of an object as below. + */ + pair(): CryptoKeyPair; + /** + * Log out currently authenticated user. Parameters are unused in the current implementation. + * @param opt unused in current implementation. + * @param cb unused in current implementation. + */ + leave(opt?: never, cb?: never): ChainReference; + /** + * Deletes a user from the current gun instance and propagates the delete to other peers. + * @param alias Username or alias. + * @param pass Passphrase for the user. + * @param cb Callback that is called when the user was successfully deleted. + */ + delete(alias: string, pass: string, cb?: (ack: { ok: 0 }) => void): Promise; + /** + * Recall saves a users credentials in sessionStorage of the browser. As long as the tab of your app is not closed the user stays logged in, even through page refreshes and reloads. + * @param opt option object If you want to use browser sessionStorage to allow users to stay logged in as long as the session is open, set opt.sessionStorage to true + * @param cb internally the callback is passed on to the user.auth function to logged the user back in. Refer to user.auth for callback documentation. + */ + recall(opt?: { sessionStorage: boolean }, cb?: Parameters[2]): ChainReference; + /** + * @param publicKey If you know a users publicKey you can get his user graph and see any unencrypted data he may have stored there. + */ + user(publicKey?: string): ChainReference; + //#endregion } - interface GunSEA { - // There is no the only content in the api document. - user: { - create(alias: string, passphrase: string, callback: (...args: any[]) => void): any; - }; - } - + type CryptoKeyPair = Record<'pub' | 'priv' | 'epub' | 'epriv', string>; interface Constructor { /** * @description @@ -274,8 +371,12 @@ declare namespace Gun { * * or you can pass in an array of URLs to sync with multiple peers. */ - (options?: string | string[] | ConstructorOptions): ChainReference & GunSEA; - new (options?: string | string[] | ConstructorOptions): ChainReference & GunSEA; + (options?: string | string[] | ConstructorOptions): ChainReference; + new (options?: string | string[] | ConstructorOptions): ChainReference< + DataType, + any, + 'pre_root' + >; node: { /** Returns true if data is a gun node, otherwise false. */ is(anything: any): anything is ChainReference; @@ -289,7 +390,66 @@ declare namespace Gun { ify(json: any): any; }; /** @see https://gun.eco/docs/SEA */ - SEA: any; + SEA: { + /** If you want SEA to throw while in development, turn SEA.throw = true on, but please do not use this in production. */ + throw?: boolean; + /** Last known error */ + err?: Error; + /** + * This gives you a Proof of Work (POW) / Hashing of Data + * @param data The data to be hashed, work to be performed on. + * @param pair (salt) You can pass pair of keys to use as salt. Salt will prevent others to pre-compute the work, + * so using your public key is not a good idea. If it is not specified, it will be random, + * which ruins your chance of ever being able to re-derive the work deterministically + * @param callback function to executed upon execution of proof + * @param opt default: {name: 'PBKDF2', encode: 'base64'} + */ + work( + data: any, + pair?: any, + callback?: (data: string | void) => void, + opt?: Partial<{ + name: 'SHA-256' | 'PBKDF2'; + encode: 'base64' | 'base32' | 'base16'; + /** iterations to use on subtle.deriveBits */ + iterations: number; + salt: any; + hash: string; + length: any; + }> + ): Promise; + /** + * This generates a cryptographically secure public/private key pair - be careful not to leak the private keys! + * Note: API subject to change we may change the parameters to accept data and work, in addition to generation. + * You will need this for most of SEA's API, see those method's examples. + * The default cryptographic primitives for the asymmetric keys are ECDSA for signing and ECDH for encryption. + */ + pair(cb: (data: CryptoKeyPair) => void, opt?: {}): Promise; + /** + * Adds a signature to a message, for data that you want to prevent attackers tampering with. + * @param data is the content that you want to prove is authorized. + * @param pair is from .pair. + */ + sign(data: any, pair: CryptoKeyPair): Promise; + /** + * Gets the data if and only if the message can be verified as coming from the person you expect. + * @param message is what comes from .sign. + * @param pair from .pair or its public key text (pair.pub). + */ + verify(message: any, pair: CryptoKeyPair | string): Promise; + /** + * Takes some data that you want to keep secret and encrypts it so nobody else can read it. + * @param data is the content that you want to encrypt. + * @param pair from .pair or a passphrase you want to use as a cypher to encrypt with. + */ + encrypt(data: any, pair: CryptoKeyPair | string): Promise; + /** + * Read the secret data, if and only if you are allowed to. + * @param message is what comes from .encrypt. + * @param pair from .pair or the passphrase to decypher the message. + */ + decrypt(message: any, pair: CryptoKeyPair | string): Promise; + }; } } declare const Gun: Gun.Constructor; From 15fac8e23bdc87dfcedb1536b2aec6c4b6399bad Mon Sep 17 00:00:00 2001 From: Jack Works Date: Tue, 19 Mar 2019 13:37:33 +0800 Subject: [PATCH 040/337] Fix errors --- types/gun/gun-tests.ts | 14 ++++---------- types/gun/index.d.ts | 7 ++++--- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/types/gun/gun-tests.ts b/types/gun/gun-tests.ts index 3c9eb0e55e..e399414e0a 100644 --- a/types/gun/gun-tests.ts +++ b/types/gun/gun-tests.ts @@ -108,13 +108,7 @@ bad.get('b') // $ExpectError .put(X); -bad.get('b').put({ - // $ExpectError - c: () => {}, - // $ExpectError - d: X, - // $ExpectError - e: { - f: () => {} - } -}); +// $ExpectError +bad.get('b').put({ c: () => {}, d: X, e: { f: () => {} } }); +// $ExpectError +bad.get('c').put(new X()); diff --git a/types/gun/index.d.ts b/types/gun/index.d.ts index 176521acaa..0cba9d6620 100644 --- a/types/gun/index.d.ts +++ b/types/gun/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for gun 0.9.9999991 +// Type definitions for gun 0.9 // Project: https://github.com/amark/gun#readme // Definitions by: Jack Works // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.9 +// TypeScript Version: 3.1 declare const cons: Gun.Constructor; export = cons; @@ -69,6 +69,7 @@ declare namespace Gun { }>; type Saveable = Partial | string | number | boolean | null | ChainReference; type AckCallback = (ack: { err: Error; ok: any } | { err: undefined; ok: string }) => void; + type Parameters any> = T extends (...args: infer P) => any ? P : never; interface ChainReference { //#region API /** @@ -407,7 +408,7 @@ declare namespace Gun { work( data: any, pair?: any, - callback?: (data: string | void) => void, + callback?: (data: string | undefined) => void, opt?: Partial<{ name: 'SHA-256' | 'PBKDF2'; encode: 'base64' | 'base32' | 'base16'; From ff10b33772450788c1a0bb82c0f519618549e29c Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Tue, 19 Mar 2019 07:35:01 +0100 Subject: [PATCH 041/337] chore(slick): add some new tests --- types/slick-carousel/slick-carousel-tests.ts | 26 ++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/types/slick-carousel/slick-carousel-tests.ts b/types/slick-carousel/slick-carousel-tests.ts index 3cf05a2e0c..ff4a4991f6 100644 --- a/types/slick-carousel/slick-carousel-tests.ts +++ b/types/slick-carousel/slick-carousel-tests.ts @@ -233,3 +233,29 @@ $("#diaporama").slick({ waitForAnimate: true, zIndex: 1000 }); + +// -------------------------------------------------------- +// ------------- TEST ACCESSING SLICK INSTANCE ------------ +// -------------------------------------------------------- + +// $ExpectedType: JQuerySlick +$("#diaporama").slick("getSlick"); + +$("#diaporama").on('beforeChange', function(event, slick: JQuerySlick, currentSlide: number, nextSlide: number) { + slick.defaults; // $ExpectedType JQuerySlickOptions + slick.options; // $ExpectedType JQuerySlickOptions + slick.originalSettings; // $ExpectedType JQuerySlickOptions + slick.initials; // $ExpectedType JQuerySlickInitials + + // Some properties of `initials` object (that are merged to the Slick instance) + slick.animating; // $ExpectedType boolean + slick.initials.animating; // $ExpectedType boolean + slick.dragging; // $ExpectedType boolean + slick.initials.dragging; // $ExpectedType boolean + slick.scrolling; // $ExpectedType boolean + slick.initials.scrolling; // $ExpectedType boolean + slick.sliding; // $ExpectedType boolean + slick.initials.sliding; // $ExpectedType boolean + slick.swiping; // $ExpectedType boolean + slick.initials.swiping; // $ExpectedType boolean +}); From 4eb9a90d847e96eebadbeafdc9b4381b8999f394 Mon Sep 17 00:00:00 2001 From: breeze9527 Date: Tue, 19 Mar 2019 15:27:33 +0800 Subject: [PATCH 042/337] Added type definitions for amap-js-api-indoor-map(IndoorMap plugin of amap-js-api) --- .../amap-js-api-indoor-map-tests.ts | 114 ++++++++++++++++++ types/amap-js-api-indoor-map/index.d.ts | 111 +++++++++++++++++ types/amap-js-api-indoor-map/tsconfig.json | 24 ++++ types/amap-js-api-indoor-map/tslint.json | 3 + 4 files changed, 252 insertions(+) create mode 100644 types/amap-js-api-indoor-map/amap-js-api-indoor-map-tests.ts create mode 100644 types/amap-js-api-indoor-map/index.d.ts create mode 100644 types/amap-js-api-indoor-map/tsconfig.json create mode 100644 types/amap-js-api-indoor-map/tslint.json diff --git a/types/amap-js-api-indoor-map/amap-js-api-indoor-map-tests.ts b/types/amap-js-api-indoor-map/amap-js-api-indoor-map-tests.ts new file mode 100644 index 0000000000..f6efc2dc54 --- /dev/null +++ b/types/amap-js-api-indoor-map/amap-js-api-indoor-map-tests.ts @@ -0,0 +1,114 @@ +// $ExpectType IndoorMap +new AMap.IndoorMap(); +// $ExpectType IndoorMap +new AMap.IndoorMap({}); +// $ExpectType IndoorMap +const indoorMap = new AMap.IndoorMap({ + zIndex: 1, + opacity: 0.5, + cursor: 'cursor', + hideFloorBar: false, + alaysShow: true +}); + +// $ExpectType void +indoorMap.showIndoorMap('indoorMapId'); +// $ExpectType void +indoorMap.showIndoorMap('indoorMapId', (error, result) => { + // $ExpectType Error | null + error; + // $ExpectType SearchResult + result; + // $ExpectType string + result.id; + // $ExpectType 0 | 1 + result.status; + if (result.status === 0) { + // $ExpectType Building + const building = result.building; + { + // $ExpectType number + building.floor; + // $ExpectType FloorDetails + const floorDetails = building.floor_details; + { + // $ExpectType number[] + floorDetails.floor_indexs; + // $ExpectType string[] + floorDetails.floor_names; + // $ExpectType string[] + floorDetails.floor_nonas; + } + // $ExpectType string + building.id; + // $ExpectType LngLat + building.lnglat; + // $ExpectType string + building.name; + } + } else { + // $ExpectType Error + result.error; + } +}); +// $ExpectType void +indoorMap.showIndoorMap('indoorMapId', 1); +// $ExpectType void +indoorMap.showIndoorMap('indoorMapId', 1, () => { }); +// $ExpectType void +indoorMap.showIndoorMap('indoorMapId', 1, 'shopId'); +// $ExpectType void +indoorMap.showIndoorMap('indoorMapId', 1, 'shopId', () => { }); +// $ExpectType void +indoorMap.showIndoorMap('indoorMapId', 1, 'shopId', true); +// $ExpectType void +indoorMap.showIndoorMap('indoorMapId', 1, 'shopId', true, () => { }); + +let floor: undefined | false; +floor = indoorMap.showFloor(1); +floor = indoorMap.showFloor(1, true); + +// $ExpectType void +indoorMap.showFloorBar(); + +// $ExpectType void +indoorMap.hideFloorBar(); + +// $ExpectType void +indoorMap.hideLabels(); + +// $ExpectType string | null +indoorMap.getSelectedBuildingId(); + +// $ExpectType Building | null +const building = indoorMap.getSelectedBuilding(); +if (building) { + // $ExpectType number + building.floor; + // $ExpectType FloorDetails + building.floor_details; + // $ExpectType string + building.id; + // $ExpectType LngLat + building.lnglat; + // $ExpectType string + building.name; +} + +indoorMap.on('complete', (event: AMap.IndoorMap.EventMap['complete']) => { + // $ExpectType "complete" + event.type; +}); + +indoorMap.on('click', (event: AMap.IndoorMap.EventMap['click']) => { + // $ExpectType string + event.building_id; + // $ExpectType number + event.floor; + // $ExpectType LngLat + event.lnglat; + // $ExpectType Shop + event.shop; + // $ExpectType "click" + event.type; +}); diff --git a/types/amap-js-api-indoor-map/index.d.ts b/types/amap-js-api-indoor-map/index.d.ts new file mode 100644 index 0000000000..b19082e926 --- /dev/null +++ b/types/amap-js-api-indoor-map/index.d.ts @@ -0,0 +1,111 @@ +// Type definitions for non-npm package amap-js-api-indoor-map 1.4 +// Project: https://lbs.amap.com/api/javascript-api/reference/indoormap +// Definitions by: breeze9527 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +declare namespace AMap { + namespace IndoorMap { + interface EventMap { + complete: Event<'complete'>; + click: MouseEvent<'click'>; + + floor_complete: Event<'floor_complete', SearchResult>; + mouseover: MouseEvent<'mouseover'>; + mouseout: MouseEvent<'mouseout'>; + } + type MouseEvent = Event; + interface Options extends Layer.Options { + zIndex?: number; + opacity?: number; + cursor?: string; + hideFloorBar?: boolean; + alaysShow?: boolean; + // internal + visible?: boolean; + featurezIndex?: number; + zooms?: [number, number]; + disableIconRender?: boolean; + disableLabelRender?: boolean; + disableHoverMarker?: boolean; + autoLoadBuildingsInTile?: boolean; + } + interface FloorDetails { + floor_indexs: number[]; + floor_nonas: string[]; + floor_names: string[]; + } + type ShopCategory = 'public' | 'connection' | 'shop'; + interface Shop { + id: string; + poiId: string; + building_id: string; + name: string; + lnglat: LngLat; + category: ShopCategory; + } + interface Building { + id: string; + name: string; + lnglat: LngLat; + floor: number; + floor_details: FloorDetails; + } + interface SearchSuccessResult { + id: string; + status: 0; + building: Building; + } + interface SearchErrorResult { + id: string; + status: 1; + error: Error; + } + type SearchResult = SearchSuccessResult | SearchErrorResult; + } + + class IndoorMap extends Layer { + constructor(options?: IndoorMap.Options); + showIndoorMap( + indoorId: string, + floor?: number, + shopId?: string, + noMove?: boolean, + callback?: (error: null | Error, result: IndoorMap.SearchResult) => void + ): void; + showIndoorMap( + indoorId: string, + floor?: number, + shopId?: string, + callback?: (error: null | Error, result: IndoorMap.SearchResult) => void + ): void; + showIndoorMap( + indoorId: string, + floor?: number, + callback?: (error: null | Error, result: IndoorMap.SearchResult) => void + ): void; + showIndoorMap( + indoorId: string, + callback?: (error: null | Error, result: IndoorMap.SearchResult) => void + ): void; + + showFloor(floor: number, noMove?: boolean): false | undefined; + showFloorBar(): void; + hideFloorBar(): void; + showLabels(): void; + hideLabels(): void; + getSelectedBuildingId(): string | null; + getSelectedBuilding(): IndoorMap.Building | null; + + // internal + getFloorBar(): void; + setSelectedBuildingId(id: string): void; + } +} diff --git a/types/amap-js-api-indoor-map/tsconfig.json b/types/amap-js-api-indoor-map/tsconfig.json new file mode 100644 index 0000000000..da736c3c7b --- /dev/null +++ b/types/amap-js-api-indoor-map/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noEmit": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "amap-js-api-indoor-map-tests.ts" + ] +} diff --git a/types/amap-js-api-indoor-map/tslint.json b/types/amap-js-api-indoor-map/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/amap-js-api-indoor-map/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From f635e16c61f236b1feab4e75ac4b12f066b118ef Mon Sep 17 00:00:00 2001 From: Jeow Li Huan Date: Mon, 18 Mar 2019 19:16:00 +0800 Subject: [PATCH 043/337] [react-alert] Update react-alert to 5.2. --- types/react-alert/index.d.ts | 100 ++++++++++++++++++------ types/react-alert/react-alert-tests.tsx | 90 +++++++++++---------- 2 files changed, 126 insertions(+), 64 deletions(-) diff --git a/types/react-alert/index.d.ts b/types/react-alert/index.d.ts index 6c94da77b0..5334de3571 100644 --- a/types/react-alert/index.d.ts +++ b/types/react-alert/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-alert 4.0 +// Type definitions for react-alert 5.2 // Project: https://github.com/schiehll/react-alert // Definitions by: Yue Yang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,16 +8,49 @@ import * as React from 'react'; export type AlertPosition = | 'top left' - | 'top right' | 'top center' + | 'top right' + | 'middle left' + | 'middle' + | 'middle right' | 'bottom left' - | 'bottom right' - | 'bottom center'; + | 'bottom center' + | 'bottom right'; + +export interface Positions { + TOP_LEFT: 'top left'; + TOP_CENTER: 'top center'; + TOP_RIGHT: 'top right'; + MIDDLE_LEFT: 'middle left'; + MIDDLE: 'middle'; + MIDDLE_RIGHT: 'middle right'; + BOTTOM_LEFT: 'bottom left'; + BOTTOM_CENTER: 'bottom center'; + BOTTOM_RIGHT: 'bottom right'; +} + +export const positions: Positions; export type AlertType = 'info' | 'success' | 'error'; + +export interface Types { + INFO: 'info'; + SUCCESS: 'success'; + ERROR: 'error'; +} + +export const types: Types; + export type AlertTransition = 'fade' | 'scale'; -export interface ProviderOptions { +export interface Transitions { + FADE: 'fade'; + SCALE: 'scale'; +} + +export const transitions: Transitions; + +export interface AlertProviderProps extends React.HTMLAttributes { /** * The margin of each alert * @@ -49,18 +82,33 @@ export interface ProviderOptions { */ transition?: AlertTransition; /** - * The z-index of alerts + * The style of the alert container * - * Default value: 100 + * Default z-index value: 100 */ - zIndex?: number; + containerStyle?: React.CSSProperties; + /** + * The alert component for each message + */ + template: React.ComponentType; + /** + * Custom context to separate alerts. + */ + context?: React.Context; } -export class Provider extends React.Component {} +export interface AlertComponentProps { + id: string; + message: React.ReactNode; + options: AlertCustomOptionsWithType; + close(): void; +} -export const Alert: React.Consumer; +export interface AlertComponentPropsWithStyle extends AlertComponentProps { + style: React.CSSProperties; +} + +export class Provider extends React.Component {} export interface AlertCustomOptions { /** @@ -70,28 +118,32 @@ export interface AlertCustomOptions { /** * Callback that will be executed after this alert open */ - onOpen?(): undefined; + onOpen?(): void; /** * Callback that will be executed after this alert is removed */ - onClose?(): undefined; + onClose?(): void; } export interface AlertCustomOptionsWithType extends AlertCustomOptions { type?: AlertType; } -export interface InjectedAlertProp { +export interface AlertManager { + root?: HTMLElement; + alerts: AlertComponentProps[]; show( - message?: string, + message?: React.ReactNode, options?: AlertCustomOptionsWithType - ): InjectedAlertProp; - remove(alert: InjectedAlertProp): undefined; - success(message?: string, options?: AlertCustomOptions): InjectedAlertProp; - error(message?: string, options?: AlertCustomOptions): InjectedAlertProp; - info(message?: string, options?: AlertCustomOptions): InjectedAlertProp; + ): AlertComponentProps; + remove(alert: AlertComponentProps): void; + success(message?: React.ReactNode, options?: AlertCustomOptions): AlertComponentProps; + error(message?: React.ReactNode, options?: AlertCustomOptions): AlertComponentProps; + info(message?: React.ReactNode, options?: AlertCustomOptions): AlertComponentProps; } -export function withAlert

( - c: React.ComponentType

-): React.ComponentType>>; +export function withAlert

(context?: React.Context): + (c: React.ComponentType

) => + React.ComponentType>>; + +export function useAlert(context?: React.Context): AlertManager; diff --git a/types/react-alert/react-alert-tests.tsx b/types/react-alert/react-alert-tests.tsx index c6088a52a8..64a4e5cf97 100644 --- a/types/react-alert/react-alert-tests.tsx +++ b/types/react-alert/react-alert-tests.tsx @@ -1,20 +1,28 @@ import * as React from 'react'; import { + AlertComponentPropsWithStyle, + AlertManager, Provider as AlertProvider, - Alert, + AlertProviderProps, + useAlert, withAlert, - AlertPosition, - AlertTransition, - ProviderOptions, - InjectedAlertProp } from 'react-alert'; -class AppWithoutAlert extends React.Component<{ alert: InjectedAlertProp }> { +class AppWithoutAlert extends React.Component<{ alert: AlertManager }> { render() { return ( - )} - - ); - } -} +const App = withAlert(customContext)(AppWithoutAlert); -class AlertTemplate extends React.Component { +const AlertHook = (): JSX.Element => { + const alert = useAlert(); + return ( + + ); +}; + +class AlertTemplate extends React.Component { render() { // the style contains only the margin given as offset // options contains all alert given options @@ -63,28 +76,25 @@ class AlertTemplate extends React.Component { } } -const options: ProviderOptions = { - position: 'bottom center' as AlertPosition, +const options: AlertProviderProps = { + position: 'bottom center', timeout: 5000, offset: '30px', - transition: 'scale' as AlertTransition + transition: 'scale', + context: customContext, + className: 'cssClass', + template: AlertTemplate, + containerStyle: { + margin: 5, + }, }; class Root extends React.Component { render() { return ( - + - - ); - } -} - -class RootAlert extends React.Component { - render() { - return ( - - + ); } From 1f5666e4e012bc7e96a881a1f74a8b846bd0ae72 Mon Sep 17 00:00:00 2001 From: AntoineDoubovetzky Date: Tue, 19 Mar 2019 11:57:46 +0100 Subject: [PATCH 044/337] update default import --- types/react-scrollable-anchor/index.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/react-scrollable-anchor/index.d.ts b/types/react-scrollable-anchor/index.d.ts index 9459918b15..234c6db9c0 100644 --- a/types/react-scrollable-anchor/index.d.ts +++ b/types/react-scrollable-anchor/index.d.ts @@ -11,7 +11,6 @@ export interface ScrollableAnchorProps { children?: React.ReactNode; } -declare const ScrollableAnchor: React.ComponentType; export interface ConfigureAnchorsOptions { offset?: number; @@ -19,7 +18,7 @@ export interface ConfigureAnchorsOptions { keepLastAnchorHash?: boolean; } -export default ScrollableAnchor; +export default class ScrollableAnchor extends React.Component { } export function goToTop(): void; export function configureAnchors(options: ConfigureAnchorsOptions): void; export function goToAnchor(anchorId: string, saveHashUpdate?: boolean): void; From b8c3bc11908e8998a66f6b1b495d2317cf46bbb9 Mon Sep 17 00:00:00 2001 From: Damien SOREL Date: Tue, 19 Mar 2019 12:53:27 +0100 Subject: [PATCH 045/337] Rename test file --- .../{jest-console-tests.ts => wordpress__jest-console-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename types/wordpress__jest-console/{jest-console-tests.ts => wordpress__jest-console-tests.ts} (100%) diff --git a/types/wordpress__jest-console/jest-console-tests.ts b/types/wordpress__jest-console/wordpress__jest-console-tests.ts similarity index 100% rename from types/wordpress__jest-console/jest-console-tests.ts rename to types/wordpress__jest-console/wordpress__jest-console-tests.ts From e25963aeeccd01c8c6281f97cc77e9fbb6c78d40 Mon Sep 17 00:00:00 2001 From: Aditya Srinivasan Date: Tue, 19 Mar 2019 20:06:26 +0800 Subject: [PATCH 046/337] Type-Parameterize React.ReactElement --- types/react-beautiful-dnd/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/react-beautiful-dnd/index.d.ts b/types/react-beautiful-dnd/index.d.ts index 926a8f7e9f..6c9334c670 100644 --- a/types/react-beautiful-dnd/index.d.ts +++ b/types/react-beautiful-dnd/index.d.ts @@ -105,7 +105,7 @@ export interface DroppableProvidedProps { } export interface DroppableProvided { innerRef(element: HTMLElement | null): any; - placeholder?: React.ReactElement | null; + placeholder?: React.ReactElement | null; droppableProps: DroppableProvidedProps; } @@ -122,7 +122,7 @@ export interface DroppableProps { isDropDisabled?: boolean; isCombineEnabled?: boolean; direction?: 'vertical' | 'horizontal'; - children(provided: DroppableProvided, snapshot: DroppableStateSnapshot): React.ReactElement; + children(provided: DroppableProvided, snapshot: DroppableStateSnapshot): React.ReactElement; } export class Droppable extends React.Component { } @@ -176,7 +176,7 @@ export interface DraggableProvided { // will be removed after move to react 16 innerRef(element?: HTMLElement | null): any; - placeholder?: React.ReactElement | null; + placeholder?: React.ReactElement | null; } export interface DraggableStateSnapshot { @@ -205,7 +205,7 @@ export interface DraggableProps { index: number; isDragDisabled?: boolean; disableInteractiveElementBlocking?: boolean; - children(provided: DraggableProvided, snapshot: DraggableStateSnapshot): React.ReactElement; + children(provided: DraggableProvided, snapshot: DraggableStateSnapshot): React.ReactElement; type?: TypeId; shouldRespectForceTouch?: boolean; } From abbb7c22b5b650aa46d69fe885713259206a490f Mon Sep 17 00:00:00 2001 From: lloiser Date: Tue, 19 Mar 2019 14:15:09 +0100 Subject: [PATCH 047/337] [counterpart] add translate method --- types/counterpart/counterpart-tests.ts | 2 ++ types/counterpart/index.d.ts | 1 + 2 files changed, 3 insertions(+) diff --git a/types/counterpart/counterpart-tests.ts b/types/counterpart/counterpart-tests.ts index db9f1cf5d6..850b026ecf 100644 --- a/types/counterpart/counterpart-tests.ts +++ b/types/counterpart/counterpart-tests.ts @@ -2,6 +2,8 @@ import * as counterpart from 'counterpart'; counterpart('translation.to.be.used'); counterpart(['translation', 'to', 'be', 'used']); +counterpart.translate('translation.to.be.used'); +counterpart.translate(['translation', 'to', 'be', 'used']); counterpart.setSeparator('*'); diff --git a/types/counterpart/index.d.ts b/types/counterpart/index.d.ts index f09ad0708c..3fd0caeac7 100644 --- a/types/counterpart/index.d.ts +++ b/types/counterpart/index.d.ts @@ -9,6 +9,7 @@ type LocaleChangeHandler = (newLocale: string, oldLocale: string) => void; interface Counterpart { (key: string|string[], options?: object): string; + translate(key: string|string[], options?: object): string; setSeparator(value: string): string; onTranslationNotFound(callback: NotFoundHandler): void; From 5e4e3674a18da019f21a14d349f83d6b558ef9c2 Mon Sep 17 00:00:00 2001 From: AntoineDoubovetzky Date: Tue, 19 Mar 2019 15:02:36 +0100 Subject: [PATCH 048/337] remove consecutive blank line --- types/react-scrollable-anchor/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/react-scrollable-anchor/index.d.ts b/types/react-scrollable-anchor/index.d.ts index 234c6db9c0..ea495dd0f7 100644 --- a/types/react-scrollable-anchor/index.d.ts +++ b/types/react-scrollable-anchor/index.d.ts @@ -11,7 +11,6 @@ export interface ScrollableAnchorProps { children?: React.ReactNode; } - export interface ConfigureAnchorsOptions { offset?: number; scrollDuration?: number; From 4ad4a3c54fb6aacb080186cb1d00f1ddc4e30f69 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Tue, 19 Mar 2019 09:18:03 -0700 Subject: [PATCH 049/337] Update project urls from npm --- types/restify/index.d.ts | 2 +- types/storybook-addon-jsx/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/restify/index.d.ts b/types/restify/index.d.ts index 5dad7503b6..0df229f1cc 100644 --- a/types/restify/index.d.ts +++ b/types/restify/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for restify 7.2 -// Project: https://github.com/restify/node-restify, http://restifyjs.com +// Project: https://github.com/restify/node-restify, http://restify.com // Definitions by: Bret Little // Steve Hipwell // Leandro Almeida diff --git a/types/storybook-addon-jsx/index.d.ts b/types/storybook-addon-jsx/index.d.ts index e3fbd63368..c4371d4c07 100644 --- a/types/storybook-addon-jsx/index.d.ts +++ b/types/storybook-addon-jsx/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for storybook-addon-jsx 5.4 -// Project: https://github.com/storybooks/storybook +// Project: https://github.com/storybooks/addon-jsx // Definitions by: James Newell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 From 9e9949c5b0ababa9207ec1f5d916feeb6ae49e6f Mon Sep 17 00:00:00 2001 From: Andrew Leedham Date: Tue, 19 Mar 2019 16:03:49 +0000 Subject: [PATCH 050/337] fix(node-fetch): make systemError optional --- types/node-fetch/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/node-fetch/index.d.ts b/types/node-fetch/index.d.ts index 03ae639d26..8883dc1b9d 100644 --- a/types/node-fetch/index.d.ts +++ b/types/node-fetch/index.d.ts @@ -4,6 +4,7 @@ // Niklas Lindgren // Vinay Bedre // Antonio Román +// Andrew Leedham // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -134,7 +135,7 @@ export class Body { export class FetchError extends Error { name: "FetchError"; - constructor(message: string, type: string, systemError: string); + constructor(message: string, type: string, systemError?: string); type: string; code?: string; errno?: string; From 576c81e41be1cae94d85ccfc955aaf86afc80f3d Mon Sep 17 00:00:00 2001 From: Andrew Leedham Date: Tue, 19 Mar 2019 16:16:37 +0000 Subject: [PATCH 051/337] test(node-fetch): added FetchError test --- types/node-fetch/node-fetch-tests.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/node-fetch/node-fetch-tests.ts b/types/node-fetch/node-fetch-tests.ts index d35114f60a..165ac24800 100644 --- a/types/node-fetch/node-fetch-tests.ts +++ b/types/node-fetch/node-fetch-tests.ts @@ -1,4 +1,4 @@ -import fetch, { Headers, Request, RequestInit, Response } from 'node-fetch'; +import fetch, { Headers, Request, RequestInit, Response, FetchError } from 'node-fetch'; import { Agent } from "http"; function test_fetchUrlWithOptions() { @@ -82,3 +82,8 @@ function test_isRedirect() { fetch.isRedirect(301); fetch.isRedirect(201); } + +function test_FetchError() { + new FetchError('message', 'type', 'systemError'); + new FetchError('message', 'type'); +} From 0229272d2c2503197792bd89104d5d9455edc9d3 Mon Sep 17 00:00:00 2001 From: Luis Paulo Date: Tue, 19 Mar 2019 16:43:44 +0000 Subject: [PATCH 052/337] Added the definition file for the 'child-process-promise' package --- .../child-process-promise-tests.ts | 15 +++ types/child-process-promise/index.d.ts | 113 ++++++++++++++++++ types/child-process-promise/tsconfig.json | 22 ++++ types/child-process-promise/tslint.json | 1 + 4 files changed, 151 insertions(+) create mode 100644 types/child-process-promise/child-process-promise-tests.ts create mode 100644 types/child-process-promise/index.d.ts create mode 100644 types/child-process-promise/tsconfig.json create mode 100644 types/child-process-promise/tslint.json diff --git a/types/child-process-promise/child-process-promise-tests.ts b/types/child-process-promise/child-process-promise-tests.ts new file mode 100644 index 0000000000..c76f0c9a49 --- /dev/null +++ b/types/child-process-promise/child-process-promise-tests.ts @@ -0,0 +1,15 @@ +import * as cpp from "child-process-promise"; + +import { + ChildProcess +} from 'child_process'; + +const a = cpp.exec("echo \"Hello world!\""); +a.childProcess; // $ExpectType ChildProcess + +(async () => { + const at = await a; + at.childProcess; // $ExpectType ChildProcess + at.stdout; // $ExpectType string + at.stderr; // $ExpectType string +})(); \ No newline at end of file diff --git a/types/child-process-promise/index.d.ts b/types/child-process-promise/index.d.ts new file mode 100644 index 0000000000..2740c8e197 --- /dev/null +++ b/types/child-process-promise/index.d.ts @@ -0,0 +1,113 @@ +// Type definitions for child-process-promise 2.2.1 +// Project: https://github.com/TheDSCPL/types_child-process-promise +// Definitions by: Luis Paulo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.3.3 + +/// + +// import child_process = require('child_process'); +import { + ChildProcess, + ExecFileOptionsWithBufferEncoding, ExecFileOptionsWithOtherEncoding, + ExecFileOptionsWithStringEncoding, + ExecOptions, + ForkOptions, + SpawnOptions +} from 'child_process'; + +export = cpp; +export as namespace cpp; + +/** + * Simple wrapper around the child_process module that makes use of promises + */ +declare namespace cpp { + interface PromiseResult { + childProcess: ChildProcess, + stdout: Enc, + stderr: Enc + } + + interface SpawnPromiseResult extends PromiseResult { + code: number + } + + interface ChildProcessPromise extends Promise { + childProcess: ChildProcess + } + + export interface Options { + /** + * Pass an additional capture option to buffer the result of stdout and/or stderr + * Default: [] + */ + capture?: []|['stdout']|['stderr']|['stdout'|'stderr']|['stderr'|'stdout'], + /** + * Array of the numbers that should be interpreted as successful execution codes + * Default: [0] + */ + successfulExitCodes?: number[] + } + + export function exec( + command: Readonly, + options: Readonly + ): ChildProcessPromise>; + export function exec( + command: Readonly, + options: Readonly + ): ChildProcessPromise>; + export function exec( + command: Readonly, + options: Readonly + ): ChildProcessPromise>; + export function exec( + command: Readonly, + options?: Readonly + ): ChildProcessPromise>; + + export function execFile( + file: Readonly, + options: Readonly + ): ChildProcessPromise>; + export function execFile( + file: Readonly, + args: ReadonlyArray | null, + options: Readonly + ): ChildProcessPromise>; + export function execFile( + file: Readonly, + options: Readonly + ): ChildProcessPromise>; + export function execFile( + file: Readonly, + args: ReadonlyArray | null, + options: Readonly + ): ChildProcessPromise>; + export function execFile( + file: Readonly, + options: Readonly + ): ChildProcessPromise>; + export function execFile( + file: Readonly, + args: ReadonlyArray | null, + options: Readonly + ): ChildProcessPromise>; + export function execFile( + file: Readonly, + args?: ReadonlyArray | null + ): ChildProcessPromise>; + + export function spawn( + command: Readonly, + args?: ReadonlyArray | null, + options?: Readonly + ): ChildProcessPromise; + + export function fork( + modulePath: string, + args?: ReadonlyArray, + options?: Readonly + ): ChildProcessPromise; +} diff --git a/types/child-process-promise/tsconfig.json b/types/child-process-promise/tsconfig.json new file mode 100644 index 0000000000..0f3bf72033 --- /dev/null +++ b/types/child-process-promise/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "child-process-promise-tests.ts" + ] +} diff --git a/types/child-process-promise/tslint.json b/types/child-process-promise/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/child-process-promise/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ec8e6f7e5934335e597cfc3e7f450fa31742d21a Mon Sep 17 00:00:00 2001 From: Sean Genabe Date: Wed, 20 Mar 2019 04:10:15 +0800 Subject: [PATCH 053/337] add type definitions for then-eos --- types/then-eos/index.d.ts | 12 ++++++++++++ types/then-eos/then-eos-tests.ts | 10 ++++++++++ types/then-eos/tsconfig.json | 23 +++++++++++++++++++++++ types/then-eos/tslint.json | 1 + 4 files changed, 46 insertions(+) create mode 100644 types/then-eos/index.d.ts create mode 100644 types/then-eos/then-eos-tests.ts create mode 100644 types/then-eos/tsconfig.json create mode 100644 types/then-eos/tslint.json diff --git a/types/then-eos/index.d.ts b/types/then-eos/index.d.ts new file mode 100644 index 0000000000..bd44297d51 --- /dev/null +++ b/types/then-eos/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for then-eos 1.0 +// Project: https://github.com/meoguru/node-then-eos +// Definitions by: Sean Marvi Oliver Genabe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +type Stream = NodeJS.ReadableStream | NodeJS.WritableStream; + +declare function thenEos(stream: Stream): Promise; + +export = thenEos; diff --git a/types/then-eos/then-eos-tests.ts b/types/then-eos/then-eos-tests.ts new file mode 100644 index 0000000000..7715f88009 --- /dev/null +++ b/types/then-eos/then-eos-tests.ts @@ -0,0 +1,10 @@ +import eos = require("then-eos"); + +declare const readable: NodeJS.ReadableStream; +declare const writable: NodeJS.WritableStream; + +// $ExpectType Promise +eos(readable); + +// $ExpectType Promise +eos(writable); diff --git a/types/then-eos/tsconfig.json b/types/then-eos/tsconfig.json new file mode 100644 index 0000000000..4f0567eb78 --- /dev/null +++ b/types/then-eos/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "then-eos-tests.ts" + ] +} diff --git a/types/then-eos/tslint.json b/types/then-eos/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/then-eos/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 1f8ed6f5ad779578da893f39af5bdb2b28c9a73a Mon Sep 17 00:00:00 2001 From: James Lismore Date: Tue, 19 Mar 2019 16:48:21 -0400 Subject: [PATCH 054/337] Extend anchor props --- types/react-csv/components/Link.d.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/types/react-csv/components/Link.d.ts b/types/react-csv/components/Link.d.ts index 3e133095de..7719d1405e 100644 --- a/types/react-csv/components/Link.d.ts +++ b/types/react-csv/components/Link.d.ts @@ -1,5 +1,15 @@ import { Component } from "react"; import { CommonPropTypes } from "./CommonPropTypes"; -export default class Link extends Component { -} +type Omit = Pick>; + +interface LinkProps + extends CommonPropTypes, + Omit< + React.DetailedHTMLProps< + React.AnchorHTMLAttributes, + HTMLAnchorElement + >, + "onClick" + > {} +export default class Link extends Component {} From e2106c93e4b3b623ac63c62ed1fbedb29db43946 Mon Sep 17 00:00:00 2001 From: James Lismore Date: Tue, 19 Mar 2019 16:52:37 -0400 Subject: [PATCH 055/337] Add test --- types/react-csv/react-csv-tests.tsx | 263 +++++++++++++++++++++++----- 1 file changed, 216 insertions(+), 47 deletions(-) diff --git a/types/react-csv/react-csv-tests.tsx b/types/react-csv/react-csv-tests.tsx index a099d60626..4153879fea 100644 --- a/types/react-csv/react-csv-tests.tsx +++ b/types/react-csv/react-csv-tests.tsx @@ -3,16 +3,16 @@ import { render } from "react-dom"; import { CSVLink, CSVDownload } from "react-csv"; const headers = [ - {label: 'First Name', key: 'details.firstName'}, - {label: 'Last Name', key: 'details.lastName'}, - {label: 'Job', key: 'job'}, + { label: "First Name", key: "details.firstName" }, + { label: "Last Name", key: "details.lastName" }, + { label: "Job", key: "job" } ]; -const headersStrings = ['foo', 'bar']; +const headersStrings = ["foo", "bar"]; const data = [ - {details: {firstName: 'Ahmed', lastName: 'Tomi'}, job: 'manager'}, - {details: {firstName: 'John', lastName: 'Jones'}, job: 'developer'}, + { details: { firstName: "Ahmed", lastName: "Tomi" }, job: "manager" }, + { details: { firstName: "John", lastName: "Jones" }, job: "developer" } ]; const dataString = `firstname,lastname @@ -21,57 +21,226 @@ Raed,Labes Yezzi,Min l3b `; -const syncOnClickReturn = (event: React.MouseEventHandler) => { +const syncOnClickReturn = ( + event: React.MouseEventHandler +) => { window.console.log(event); return true; }; -const syncOnClickVoid = (event: React.MouseEventHandler) => window.console.log(event); -const asyncOnClickReturn = (event: React.MouseEventHandler, done: (proceed?: boolean) => void) => { +const syncOnClickVoid = (event: React.MouseEventHandler) => + window.console.log(event); +const asyncOnClickReturn = ( + event: React.MouseEventHandler, + done: (proceed?: boolean) => void +) => { window.console.log(event); done(true); }; -const asyncOnClickVoid = (event: React.MouseEventHandler, done: (proceed?: boolean) => void) => { +const asyncOnClickVoid = ( + event: React.MouseEventHandler, + done: (proceed?: boolean) => void +) => { window.console.log(event); done(); }; const node = document.getElementById("main"); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); +render(, node); +render(, node); +render(, node); +render(, node); +render(, node); +render(, node); +render( + , + node +); +render( + , + node +); +render( + , + node +); +render( + , + node +); +render( + , + node +); +render( + , + node +); +render( + , + node +); +render( + , + node +); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); -render(, node); +render(, node); +render(, node); +render(, node); +render(, node); +render(, node); +render( + , + node +); +render( + , + node +); +render( + , + node +); +render( + , + node +); +render( + , + node +); +render( + , + node +); +render( + , + node +); +render( + , + node +); From a5e81b2ecccc4122eb2335df655af28830f2ef91 Mon Sep 17 00:00:00 2001 From: Andrew Schmadel Date: Tue, 19 Mar 2019 17:06:59 -0400 Subject: [PATCH 056/337] add typings for pino isLevelEnabled() method --- types/pino/index.d.ts | 5 +++++ types/pino/pino-tests.ts | 1 + 2 files changed, 6 insertions(+) diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index 610ae076ee..ff4ba1f77c 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -444,6 +444,11 @@ declare namespace P { * Flushes the content of the buffer in extreme mode. It has no effect if extreme mode is not enabled. */ flush(): void; + + /** + * A utility method for determining if a given log level will write to the destination. + */ + isLevelEnabled(level: LevelWithSilent | string): boolean; } type LevelChangeEventListener = (lvl: LevelWithSilent | string, val: number, prevLvl: LevelWithSilent | string, prevVal: number) => void; diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index 3a6283c3e4..1a64f11d99 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -91,6 +91,7 @@ logstderr.error('on stderr instead of stdout'); log.useLevelLabels = true; log.info('lol'); log.level === 'info'; +const isEnabled: boolean = log.isLevelEnabled('info'); const extremeDest = pino.extreme(); const logExtreme = pino(extremeDest); From d732b0e367da866582fe23b5e06a8d6560142a11 Mon Sep 17 00:00:00 2001 From: borkaborka <4437770+borkaborka@users.noreply.github.com> Date: Tue, 19 Mar 2019 23:28:38 +0200 Subject: [PATCH 057/337] ClientConfig.ssl: TlsOptions -> ConnectionOptions according to: https://github.com/brianc/node-postgres/blob/6b8176e841584b76bcbd1972bf95e50558ba7395/lib/connection.js#L97 and node.js documentation of tls.connect(), this parameter must be of type ConnectionOptions and not TlsOptions --- types/pg/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/pg/index.d.ts b/types/pg/index.d.ts index 35ef7801b4..081213eb86 100644 --- a/types/pg/index.d.ts +++ b/types/pg/index.d.ts @@ -29,10 +29,10 @@ export interface Defaults extends ConnectionConfig { parseInt8?: boolean; } -import { TlsOptions } from "tls"; +import { ConnectionOptions } from "tls"; export interface ClientConfig extends ConnectionConfig { - ssl?: boolean | TlsOptions; + ssl?: boolean | ConnectionOptions; } export interface PoolConfig extends ClientConfig { From 8bf23e99f4844ceee88f99bf27a7201a4097a7ff Mon Sep 17 00:00:00 2001 From: Haseeb Majid Date: Tue, 19 Mar 2019 22:15:22 +0000 Subject: [PATCH 058/337] Corrected mistakes in definition Corrected mistake in definition, using mozilla documentation. --- types/react-native-canvas/index.d.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/types/react-native-canvas/index.d.ts b/types/react-native-canvas/index.d.ts index 65b80277ee..af79c05bde 100644 --- a/types/react-native-canvas/index.d.ts +++ b/types/react-native-canvas/index.d.ts @@ -165,19 +165,19 @@ export default class Canvas extends React.Component { } export class Image { - constructor(canvas: Canvas, height?: number, width?: number); + constructor(canvas: Canvas, height: number, width: number); crossOrigin: string | undefined; - height: number | undefined; - width: number | undefined; - src: string | undefined; + height: number; + width: number; + src: string; addEventListener: (event: string, func: (...args: any) => any) => void; } export class ImageData { - constructor(canvas: Canvas, data: number[], height: number, width: number); + constructor(canvas: Canvas, height: number, width: number, data?: number[], ); readonly data: number[]; - readonly height: number | undefined; - readonly width: number | undefined; + readonly height: number; + readonly width: number; } export class Path2D { From d38bf22b5faa6a55bf3955b560daa4d5e8a7ec02 Mon Sep 17 00:00:00 2001 From: Eugene Wang Date: Tue, 19 Mar 2019 18:27:14 -0400 Subject: [PATCH 059/337] Update index.d.ts --- types/geojson/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/geojson/index.d.ts b/types/geojson/index.d.ts index db8074e242..3a486b66b1 100644 --- a/types/geojson/index.d.ts +++ b/types/geojson/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for geojson 7946.0 +// Type definitions for non-npm package geojson 7946.0 // Project: https://geojson.org/ // Definitions by: Jacob Bruun // Arne Schubert From 619453a74056bea626029891b343e52a6168cbd5 Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Tue, 19 Mar 2019 23:34:08 +0100 Subject: [PATCH 060/337] [node] Add stream options autoDestroy, emitClose, defaultEncoding --- types/node/stream.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/node/stream.d.ts b/types/node/stream.d.ts index ab6730c83b..a43d668092 100644 --- a/types/node/stream.d.ts +++ b/types/node/stream.d.ts @@ -14,6 +14,7 @@ declare module "stream" { objectMode?: boolean; read?(this: Readable, size: number): void; destroy?(this: Readable, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean; } class Readable extends Stream implements NodeJS.ReadableStream { @@ -98,11 +99,14 @@ declare module "stream" { interface WritableOptions { highWaterMark?: number; decodeStrings?: boolean; + defaultEncoding?: string; objectMode?: boolean; + emitClose?: boolean; write?(this: Writable, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; writev?(this: Writable, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; final?(this: Writable, callback: (error?: Error | null) => void): void; + autoDestroy?: boolean; } class Writable extends Stream implements NodeJS.WritableStream { From 82620eab415844877df900c0b5d195ba26c0563b Mon Sep 17 00:00:00 2001 From: Jim Li Date: Tue, 19 Mar 2019 18:53:38 -0400 Subject: [PATCH 061/337] [react-dom] Change charCode to number Changed SyntheticEventData.charCode to number in order to match the properties listed here: https://reactjs.org/docs/events.html#keyboard-events --- types/react-dom/test-utils/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-dom/test-utils/index.d.ts b/types/react-dom/test-utils/index.d.ts index c6f46edd36..ea61a9c858 100644 --- a/types/react-dom/test-utils/index.d.ts +++ b/types/react-dom/test-utils/index.d.ts @@ -29,7 +29,7 @@ export interface SyntheticEventData extends OptionalEventProperties { clientX?: number; clientY?: number; changedTouches?: TouchList; - charCode?: boolean; + charCode?: number; clipboardData?: DataTransfer; ctrlKey?: boolean; deltaMode?: number; From 1b6ddb47bae373a8842363ab191b5d8e417203c4 Mon Sep 17 00:00:00 2001 From: Leandro Soares Date: Tue, 19 Mar 2019 00:07:43 +0000 Subject: [PATCH 062/337] Add redux seamless immutable --- types/redux-seamless-immutable/index.d.ts | 16 +++++++ types/redux-seamless-immutable/package.json | 6 +++ .../redux-seamless-immutable-tests.ts | 42 +++++++++++++++++++ types/redux-seamless-immutable/tsconfig.json | 23 ++++++++++ types/redux-seamless-immutable/tslint.json | 3 ++ 5 files changed, 90 insertions(+) create mode 100644 types/redux-seamless-immutable/index.d.ts create mode 100644 types/redux-seamless-immutable/package.json create mode 100644 types/redux-seamless-immutable/redux-seamless-immutable-tests.ts create mode 100644 types/redux-seamless-immutable/tsconfig.json create mode 100644 types/redux-seamless-immutable/tslint.json diff --git a/types/redux-seamless-immutable/index.d.ts b/types/redux-seamless-immutable/index.d.ts new file mode 100644 index 0000000000..63cd632676 --- /dev/null +++ b/types/redux-seamless-immutable/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for redux-seamless-immutable 0.4 +// Project: https://github.com/eadmundo/redux-seamless-immutable +// Definitions by: Leandro Soares +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.3 + +import { Reducer, Action } from "redux"; +import { Immutable } from "seamless-immutable"; + +export interface SeamlessReducers { + [reducerName: string]: Reducer; +} + +export function combineReducers(reducers: SeamlessReducers): Reducer; +export function routerReducer(state: T, action: Action): T; +export function stateTransformer(state: Immutable): T; diff --git a/types/redux-seamless-immutable/package.json b/types/redux-seamless-immutable/package.json new file mode 100644 index 0000000000..457ab3d31e --- /dev/null +++ b/types/redux-seamless-immutable/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "redux": "^4.0.1" + } +} \ No newline at end of file diff --git a/types/redux-seamless-immutable/redux-seamless-immutable-tests.ts b/types/redux-seamless-immutable/redux-seamless-immutable-tests.ts new file mode 100644 index 0000000000..cde40cd261 --- /dev/null +++ b/types/redux-seamless-immutable/redux-seamless-immutable-tests.ts @@ -0,0 +1,42 @@ +import { combineReducers, routerReducer, stateTransformer } from "redux-seamless-immutable"; +import { createStore, applyMiddleware, Action } from "redux"; +import { createLogger } from "redux-logger"; + +interface State { + prop1: boolean; + prop2: string; +} + +type GenericActionPayload = Action & { + payload: string; +}; + +function reducer1(state: State, action: GenericActionPayload): State { + const payload = action.payload; + return state; +} + +function reducer2(state: State, action: GenericActionPayload): State { + const payload = action.payload; + return state; +} + +// Test `combineReducers` and `routerReducer` +const combined = combineReducers({ + reducer1, + reducer2, + routerReducer +}); + +// Test `stateTransformer` +const loggerMiddleware = createLogger({ + stateTransformer +}); + +// Test integration with `createStore` +const store = createStore( + combined, + applyMiddleware( + loggerMiddleware + ) +); diff --git a/types/redux-seamless-immutable/tsconfig.json b/types/redux-seamless-immutable/tsconfig.json new file mode 100644 index 0000000000..c5cea671f6 --- /dev/null +++ b/types/redux-seamless-immutable/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", + "redux-seamless-immutable-tests.ts" + ] +} \ No newline at end of file diff --git a/types/redux-seamless-immutable/tslint.json b/types/redux-seamless-immutable/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/redux-seamless-immutable/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file From 669f49f4dd03b984f12fab42cba7c56feb5619cd Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Wed, 20 Mar 2019 00:23:25 +0100 Subject: [PATCH 063/337] [node] add util.types.isBigInt64Array, isBigUint64Array and isModuleNamespaceObject --- types/node/index.d.ts | 4 ++++ types/node/test/util.ts | 4 ++++ types/node/ts3.2/util.d.ts | 5 +++++ types/node/util.d.ts | 1 + types/node/v10/index.d.ts | 4 ++++ types/node/v10/node-tests.ts | 4 ++++ types/node/v10/ts3.2/util.d.ts | 5 +++++ types/node/v10/util.d.ts | 1 + 8 files changed, 28 insertions(+) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 498b54e52e..a2f2e583fe 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -92,4 +92,8 @@ declare module "util" { namespace promisify { const custom: symbol; } + namespace types { + function isBigInt64Array(value: any): boolean; + function isBigUint64Array(value: any): boolean; + } } diff --git a/types/node/test/util.ts b/types/node/test/util.ts index 14500161fd..0dd1843b9c 100644 --- a/types/node/test/util.ts +++ b/types/node/test/util.ts @@ -159,6 +159,10 @@ import { readFile } from 'fs'; const teEncodeRes: Uint8Array = te.encode("TextEncoder"); // util.types + let b: Boolean; + b = util.types.isBigInt64Array(15); + b = util.types.isBigUint64Array(15); + b = util.types.isModuleNamespaceObject(15); // tslint:disable-next-line:no-construct ban-types const maybeBoxed: number | Number = new Number(1); diff --git a/types/node/ts3.2/util.d.ts b/types/node/ts3.2/util.d.ts index e35ef8d0f1..a8b2487ef4 100644 --- a/types/node/ts3.2/util.d.ts +++ b/types/node/ts3.2/util.d.ts @@ -1,5 +1,6 @@ // tslint:disable-next-line:no-bad-reference /// + declare module "util" { namespace inspect { const custom: unique symbol; @@ -7,4 +8,8 @@ declare module "util" { namespace promisify { const custom: unique symbol; } + namespace types { + function isBigInt64Array(value: any): value is BigInt64Array; + function isBigUint64Array(value: any): value is BigUint64Array; + } } diff --git a/types/node/util.d.ts b/types/node/util.d.ts index 1adf10059f..05edbfcf5b 100644 --- a/types/node/util.d.ts +++ b/types/node/util.d.ts @@ -127,6 +127,7 @@ declare module "util" { function isInt32Array(object: any): object is Int32Array; function isMap(object: any): boolean; function isMapIterator(object: any): boolean; + function isModuleNamespaceObject(value: any): boolean; function isNativeError(object: any): object is Error; function isNumberObject(object: any): object is Number; function isPromise(object: any): boolean; diff --git a/types/node/v10/index.d.ts b/types/node/v10/index.d.ts index ea1d259bcb..8e650d7492 100644 --- a/types/node/v10/index.d.ts +++ b/types/node/v10/index.d.ts @@ -84,4 +84,8 @@ declare module "util" { namespace promisify { const custom: symbol; } + namespace types { + function isBigInt64Array(value: any): boolean; + function isBigUint64Array(value: any): boolean; + } } diff --git a/types/node/v10/node-tests.ts b/types/node/v10/node-tests.ts index 789b87b600..1e40139731 100644 --- a/types/node/v10/node-tests.ts +++ b/types/node/v10/node-tests.ts @@ -952,6 +952,10 @@ function bufferTests() { const teEncodeRes: Uint8Array = te.encode("TextEncoder"); // util.types + let b: Boolean; + b = util.types.isBigInt64Array(15); + b = util.types.isBigUint64Array(15); + b = util.types.isModuleNamespaceObject(15); // tslint:disable-next-line:no-construct ban-types const maybeBoxed: number | Number = new Number(1); diff --git a/types/node/v10/ts3.2/util.d.ts b/types/node/v10/ts3.2/util.d.ts index e35ef8d0f1..a8b2487ef4 100644 --- a/types/node/v10/ts3.2/util.d.ts +++ b/types/node/v10/ts3.2/util.d.ts @@ -1,5 +1,6 @@ // tslint:disable-next-line:no-bad-reference /// + declare module "util" { namespace inspect { const custom: unique symbol; @@ -7,4 +8,8 @@ declare module "util" { namespace promisify { const custom: unique symbol; } + namespace types { + function isBigInt64Array(value: any): value is BigInt64Array; + function isBigUint64Array(value: any): value is BigUint64Array; + } } diff --git a/types/node/v10/util.d.ts b/types/node/v10/util.d.ts index 9da88fe9cb..07c21bf47e 100644 --- a/types/node/v10/util.d.ts +++ b/types/node/v10/util.d.ts @@ -127,6 +127,7 @@ declare module "util" { function isInt32Array(object: any): object is Int32Array; function isMap(object: any): boolean; function isMapIterator(object: any): boolean; + function isModuleNamespaceObject(value: any): boolean; function isNativeError(object: any): object is Error; function isNumberObject(object: any): object is Number; function isPromise(object: any): boolean; From 98ed1d9bc96f3e45153ef797295a51496d728bbe Mon Sep 17 00:00:00 2001 From: Saxon Landers Date: Wed, 20 Mar 2019 13:08:11 +1100 Subject: [PATCH 064/337] Add MessageDescriptor support to i18n._ --- types/lingui__core/i18n.d.ts | 8 ++++++++ types/lingui__core/index.d.ts | 3 ++- types/lingui__core/lingui__core-tests.ts | 8 ++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/types/lingui__core/i18n.d.ts b/types/lingui__core/i18n.d.ts index a74ae7a7a0..6757b08142 100644 --- a/types/lingui__core/i18n.d.ts +++ b/types/lingui__core/i18n.d.ts @@ -6,6 +6,13 @@ export interface MessageOptions { formats?: object; } +export interface MessageDescriptor { + id: string; + defaults?: string; + values?: object; + formats?: object; +} + export interface LanguageData { plurals?: (n: number, pluralType?: "cardinal" | "ordinal") => string; } @@ -62,6 +69,7 @@ export class I18n { use(language: string): I18n; _(id: string, values?: object, messageOptions?: MessageOptions): string; + _(id: MessageDescriptor): string; pluralForm(n: number, pluralType?: "cardinal" | "ordinal"): string; } diff --git a/types/lingui__core/index.d.ts b/types/lingui__core/index.d.ts index c2243ba558..efb0fed409 100644 --- a/types/lingui__core/index.d.ts +++ b/types/lingui__core/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @lingui/core 2.2 +// Type definitions for @lingui/core 2.7 // Project: https://lingui.github.io/js-lingui/, https://github.com/lingui/js-lingui // Definitions by: Jeow Li Huan // Definitions: https://github.com/huan086/lingui-typings @@ -9,6 +9,7 @@ export { setupI18n, Catalog, Catalogs, + MessageDescriptor, MessageOptions, LanguageData, I18n diff --git a/types/lingui__core/lingui__core-tests.ts b/types/lingui__core/lingui__core-tests.ts index 09af3e1e4f..69a7a87a6e 100644 --- a/types/lingui__core/lingui__core-tests.ts +++ b/types/lingui__core/lingui__core-tests.ts @@ -4,6 +4,7 @@ import { Catalog, Catalogs, MessageOptions, + MessageDescriptor, LanguageData, I18n, date, @@ -16,6 +17,13 @@ const templateResult: string = i18n.t`${age} years old`; const templateIdResult: string = i18n.t('templateId')`${age} years old`; const translateResult: string = i18n._('age', { age }, { defaults: '{age} years old' }); +const descriptorBasicResult = i18n._({ id: 'basicDescriptor' }); +const descriptorResult = i18n._({ + id: 'ageDescriptor', + defaults: '{age} years old', + values: { age } +}); + const count = 42; const pluralResult: string = i18n.plural({ From 22388f546bb0d77c1d7f1ada7744d78e909a1225 Mon Sep 17 00:00:00 2001 From: Chives Date: Tue, 19 Mar 2019 11:15:38 -0700 Subject: [PATCH 065/337] Add typings for ResizeObserver global usage (via window.ResizeObserver) --- types/resize-observer-browser/index.d.ts | 8 +++++++- .../test/resize-observer-global.test.ts | 11 +++++++++++ .../resize-observer-module.test.ts} | 0 types/resize-observer-browser/tsconfig.json | 3 ++- 4 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 types/resize-observer-browser/test/resize-observer-global.test.ts rename types/resize-observer-browser/{resize-observer-browser-tests.ts => test/resize-observer-module.test.ts} (100%) diff --git a/types/resize-observer-browser/index.d.ts b/types/resize-observer-browser/index.d.ts index 83291fe4a0..5e585f81e5 100644 --- a/types/resize-observer-browser/index.d.ts +++ b/types/resize-observer-browser/index.d.ts @@ -4,6 +4,12 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.7 +declare global { + interface Window { + ResizeObserver: typeof ResizeObserver; + } +} + export class ResizeObserver { constructor(callback: ResizeObserverCallback); disconnect(): void; @@ -11,7 +17,7 @@ export class ResizeObserver { unobserve(target: Element): void; } -export type ResizeObserverCallback = (entries: ResizeObserverEntry[]) => void; +export type ResizeObserverCallback = (entries: ReadonlyArray) => void; export interface ResizeObserverEntry { readonly target: Element; diff --git a/types/resize-observer-browser/test/resize-observer-global.test.ts b/types/resize-observer-browser/test/resize-observer-global.test.ts new file mode 100644 index 0000000000..6398b979fe --- /dev/null +++ b/types/resize-observer-browser/test/resize-observer-global.test.ts @@ -0,0 +1,11 @@ +function resizeObserverCreatesViaWindow(): void { + const resizeObserver = new window.ResizeObserver((entries) => { + const div = document.getElementById('display-div')!; + const rect = entries[0].contentRect; + div.textContent = `${rect.left} ${rect.right}`; + }); + const div = document.getElementById('resized-div')!; + resizeObserver.observe(div); + resizeObserver.unobserve(div); + resizeObserver.disconnect(); +} diff --git a/types/resize-observer-browser/resize-observer-browser-tests.ts b/types/resize-observer-browser/test/resize-observer-module.test.ts similarity index 100% rename from types/resize-observer-browser/resize-observer-browser-tests.ts rename to types/resize-observer-browser/test/resize-observer-module.test.ts diff --git a/types/resize-observer-browser/tsconfig.json b/types/resize-observer-browser/tsconfig.json index 849758c836..fcba3665dc 100644 --- a/types/resize-observer-browser/tsconfig.json +++ b/types/resize-observer-browser/tsconfig.json @@ -19,6 +19,7 @@ }, "files": [ "index.d.ts", - "resize-observer-browser-tests.ts" + "test/resize-observer-global.test.ts", + "test/resize-observer-module.test.ts" ] } From 4c3c3fa206938166ab968aaeb6a5e465d5a37bac Mon Sep 17 00:00:00 2001 From: Chives Date: Tue, 19 Mar 2019 11:47:46 -0700 Subject: [PATCH 066/337] Rename test files to resize-observer-browser pattern --- ...global.test.ts => resize-observer-browser-global.tests.ts} | 0 ...module.test.ts => resize-observer-browser-module.tests.ts} | 0 types/resize-observer-browser/tsconfig.json | 4 ++-- 3 files changed, 2 insertions(+), 2 deletions(-) rename types/resize-observer-browser/test/{resize-observer-global.test.ts => resize-observer-browser-global.tests.ts} (100%) rename types/resize-observer-browser/test/{resize-observer-module.test.ts => resize-observer-browser-module.tests.ts} (100%) diff --git a/types/resize-observer-browser/test/resize-observer-global.test.ts b/types/resize-observer-browser/test/resize-observer-browser-global.tests.ts similarity index 100% rename from types/resize-observer-browser/test/resize-observer-global.test.ts rename to types/resize-observer-browser/test/resize-observer-browser-global.tests.ts diff --git a/types/resize-observer-browser/test/resize-observer-module.test.ts b/types/resize-observer-browser/test/resize-observer-browser-module.tests.ts similarity index 100% rename from types/resize-observer-browser/test/resize-observer-module.test.ts rename to types/resize-observer-browser/test/resize-observer-browser-module.tests.ts diff --git a/types/resize-observer-browser/tsconfig.json b/types/resize-observer-browser/tsconfig.json index fcba3665dc..69a030695e 100644 --- a/types/resize-observer-browser/tsconfig.json +++ b/types/resize-observer-browser/tsconfig.json @@ -19,7 +19,7 @@ }, "files": [ "index.d.ts", - "test/resize-observer-global.test.ts", - "test/resize-observer-module.test.ts" + "test/resize-observer-browser-global.tests.ts", + "test/resize-observer-browser-module.tests.ts" ] } From 7fff40c88e2f72b6028e74b9b566251cb7f0c682 Mon Sep 17 00:00:00 2001 From: Saxon Landers Date: Wed, 20 Mar 2019 14:25:49 +1100 Subject: [PATCH 067/337] Add MessageDescriptor support to @lingui/macro --- types/lingui__macro/index.d.ts | 21 ++++++++--------- types/lingui__macro/lingui__macro-tests.tsx | 25 +++++++++++---------- types/lingui__macro/select.d.ts | 20 +++++++++-------- types/lingui__macro/tsconfig.json | 3 +++ 4 files changed, 38 insertions(+), 31 deletions(-) diff --git a/types/lingui__macro/index.d.ts b/types/lingui__macro/index.d.ts index e433b43ec7..8a6679323d 100644 --- a/types/lingui__macro/index.d.ts +++ b/types/lingui__macro/index.d.ts @@ -4,30 +4,31 @@ // Definitions: https://github.com/huan086/lingui-typings // TypeScript Version: 2.8 +import { MessageDescriptor } from '@lingui/core'; import { ComponentClass } from 'react'; import { FormatPropsWithoutI18n } from './createFormat'; import { SelectProps, PluralProps } from "./select"; // JS -export function t(strings: TemplateStringsArray, ...values: any[]): string; +export function t(strings: TemplateStringsArray, ...values: any[]): MessageDescriptor; -export function t(id: string): (strings: TemplateStringsArray, ...values: any[]) => string; +export function t(id: string): (strings: TemplateStringsArray, ...values: any[]) => MessageDescriptor; -export function select(config: SelectProps): string; +export function select(config: SelectProps): MessageDescriptor; -export function select(id: string, config: SelectProps): string; +export function select(id: string, config: SelectProps): MessageDescriptor; -export function plural(config: PluralProps): string; +export function plural(config: PluralProps): MessageDescriptor; -export function plural(id: string, config: PluralProps): string; +export function plural(id: string, config: PluralProps): MessageDescriptor; -export function selectOrdinal(config: PluralProps): string; +export function selectOrdinal(config: PluralProps): MessageDescriptor; -export function selectOrdinal(id: string, config: PluralProps): string; +export function selectOrdinal(id: string, config: PluralProps): MessageDescriptor; -export function date(value: Date, format?: Intl.DateTimeFormatOptions): string; +export function date(value: Date, format?: Intl.DateTimeFormatOptions): MessageDescriptor; -export function number(value: number, format?: Intl.NumberFormatOptions): string; +export function number(value: number, format?: Intl.NumberFormatOptions): MessageDescriptor; // JSX export { default as Trans } from './Trans'; diff --git a/types/lingui__macro/lingui__macro-tests.tsx b/types/lingui__macro/lingui__macro-tests.tsx index a60c5fd2d7..583729e9bc 100644 --- a/types/lingui__macro/lingui__macro-tests.tsx +++ b/types/lingui__macro/lingui__macro-tests.tsx @@ -1,4 +1,5 @@ import * as React from 'react'; +import { MessageDescriptor } from '@lingui/core'; import { t, select, @@ -16,25 +17,25 @@ import { // JS const age = 12; -const templateResult: string = t`${age} years old`; -const templateIdResult: string = t('templateId')`${age} years old`; +const templateResult: MessageDescriptor = t`${age} years old`; +const templateIdResult: MessageDescriptor = t('templateId')`${age} years old`; const count = 42; -const pluralResult: string = plural({ +const pluralResult: MessageDescriptor = plural({ value: count, 0: 'no books', one: '# book', other: '# books' }); -const pluralIdResult: string = plural('pluralId', { +const pluralIdResult: MessageDescriptor = plural('pluralId', { value: count, 0: 'no books', one: '# book', other: '# books' }); -const selectOrdinalResult: string = selectOrdinal({ +const selectOrdinalResult: MessageDescriptor = selectOrdinal({ value: count, 0: 'Zeroth book', one: '#st book', @@ -42,7 +43,7 @@ const selectOrdinalResult: string = selectOrdinal({ few: '#rd book', other: '#th book' }); -const selectOrdinalIdResult: string = selectOrdinal('selectOrdinalId', { +const selectOrdinalIdResult: MessageDescriptor = selectOrdinal('selectOrdinalId', { value: count, 0: 'Zeroth book', one: '#st book', @@ -60,10 +61,10 @@ const selectResult = select({ female: plural({ value: numOfGuests, offset: 1, - 0: t`${host} does not give a party.`, - 1: t`${host} invites ${guest} to her party.`, - 2: t`${host} invites ${guest} and one other person to her party.`, - other: t`${host} invites ${guest} and # other people to her party.` + 0: `${host} does not give a party.`, + 1: `${host} invites ${guest} to her party.`, + 2: `${host} invites ${guest} and one other person to her party.`, + other: `${host} invites ${guest} and # other people to her party.` }), male: 'male', other: 'other' @@ -76,8 +77,8 @@ const selectIdResult = select('selectId', { other: 'other' }); -const formattedDate: string = date(new Date(), { timeZone: 'UTC' }); -const formattedNumber: string = number(1234.56, { style: 'currency', currency: 'EUR' }); +const formattedDate: MessageDescriptor = date(new Date(), { timeZone: 'UTC' }); +const formattedNumber: MessageDescriptor = number(1234.56, { style: 'currency', currency: 'EUR' }); // JSX const App = () => { diff --git a/types/lingui__macro/select.d.ts b/types/lingui__macro/select.d.ts index 6a2eb51db9..a182ace000 100644 --- a/types/lingui__macro/select.d.ts +++ b/types/lingui__macro/select.d.ts @@ -1,11 +1,13 @@ +import { MessageDescriptor } from "@lingui/core"; + export interface PluralForms { - zero?: string; - one?: string; - two?: string; - few?: string; - many?: string; - other: string; - [exact: number]: string; + zero?: string | MessageDescriptor; + one?: string | MessageDescriptor; + two?: string | MessageDescriptor; + few?: string | MessageDescriptor; + many?: string | MessageDescriptor; + other: string | MessageDescriptor; + [exact: number]: string | MessageDescriptor; } export interface PluralProps extends PluralForms { @@ -15,6 +17,6 @@ export interface PluralProps extends PluralForms { export interface SelectProps { value: string; - other: string; - [selectForm: string]: string; + other: string | MessageDescriptor; + [selectForm: string]: string | MessageDescriptor; } diff --git a/types/lingui__macro/tsconfig.json b/types/lingui__macro/tsconfig.json index 5d58b08dad..82f2639036 100644 --- a/types/lingui__macro/tsconfig.json +++ b/types/lingui__macro/tsconfig.json @@ -20,6 +20,9 @@ "paths": { "@lingui/macro": [ "lingui__macro" + ], + "@lingui/core": [ + "lingui__core" ] } }, From 56e1fb93baa78541795fba8d41e3e5bbe61b5778 Mon Sep 17 00:00:00 2001 From: Pine Wu Date: Tue, 19 Mar 2019 21:21:28 -0700 Subject: [PATCH 068/337] VS Code 1.18 Extension API --- types/vscode/index.d.ts | 218 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 209 insertions(+), 9 deletions(-) diff --git a/types/vscode/index.d.ts b/types/vscode/index.d.ts index e01e612919..7587bbfbf3 100644 --- a/types/vscode/index.d.ts +++ b/types/vscode/index.d.ts @@ -1,5 +1,5 @@ -// Type definitions for Visual Studio Code 1.17 -// Project: https://github.com/microsoft/vscode-extension-vscode +// Type definitions for Visual Studio Code 1.18 +// Project: https://github.com/microsoft/vscode // Definitions by: Visual Studio Code Team, Microsoft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,7 +10,7 @@ *--------------------------------------------------------------------------------------------*/ /** - * Type Definition for Visual Studio Code 1.17 Extension API + * Type Definition for Visual Studio Code 1.18 Extension API */ declare module 'vscode' { @@ -1514,6 +1514,22 @@ declare module 'vscode' { onDidSelectItem?(item: QuickPickItem | string): any; } + /** + * Options to configure the behaviour of the [workspace folder](#WorkspaceFolder) pick UI. + */ + export interface WorkspaceFolderPickOptions { + + /** + * An optional string to show as place holder in the input box to guide the user what to pick on. + */ + placeHolder?: string; + + /** + * Set to `true` to keep the picker open when focus moves to another part of the editor or to another window. + */ + ignoreFocusOut?: boolean; + } + /** * Options to configure the behaviour of a file open dialog. * @@ -1671,7 +1687,7 @@ declare module 'vscode' { * @return A human readable string which is presented as diagnostic message. * Return `undefined`, `null`, or the empty string when 'value' is valid. */ - validateInput?(value: string): string | undefined | null; + validateInput?(value: string): string | undefined | null | Thenable; } /** @@ -1679,7 +1695,7 @@ declare module 'vscode' { * relatively to a base path. The base path can either be an absolute file path * or a [workspace folder](#WorkspaceFolder). */ - class RelativePattern { + export class RelativePattern { /** * A base file path to which this pattern will be matched against relatively. @@ -1980,6 +1996,13 @@ declare module 'vscode' { * @param value Markdown string. */ appendMarkdown(value: string): MarkdownString; + + /** + * Appends the given string as codeblock using the provided language. + * @param value A code snippet. + * @param language An optional [language identifier](#languages.getLanguages). + */ + appendCodeblock(value: string, language?: string): MarkdownString; } /** @@ -2983,6 +3006,133 @@ declare module 'vscode' { resolveDocumentLink?(link: DocumentLink, token: CancellationToken): ProviderResult; } + /** + * Represents a color in RGBA space. + */ + export class Color { + + /** + * The red component of this color in the range [0-1]. + */ + readonly red: number; + + /** + * The green component of this color in the range [0-1]. + */ + readonly green: number; + + /** + * The blue component of this color in the range [0-1]. + */ + readonly blue: number; + + /** + * The alpha component of this color in the range [0-1]. + */ + readonly alpha: number; + + /** + * Creates a new color instance. + * + * @param red The red component. + * @param green The green component. + * @param blue The bluew component. + * @param alpha The alpha component. + */ + constructor(red: number, green: number, blue: number, alpha: number); + } + + /** + * Represents a color range from a document. + */ + export class ColorInformation { + + /** + * The range in the document where this color appers. + */ + range: Range; + + /** + * The actual color value for this color range. + */ + color: Color; + + /** + * Creates a new color range. + * + * @param range The range the color appears in. Must not be empty. + * @param color The value of the color. + * @param format The format in which this color is currently formatted. + */ + constructor(range: Range, color: Color); + } + + /** + * A color presentation object describes how a [`color`](#Color) should be represented as text and what + * edits are required to refer to it from source code. + * + * For some languages one color can have multiple presentations, e.g. css can represent the color red with + * the constant `Red`, the hex-value `#ff0000`, or in rgba and hsla forms. In csharp other representations + * apply, e.g `System.Drawing.Color.Red`. + */ + export class ColorPresentation { + + /** + * The label of this color presentation. It will be shown on the color + * picker header. By default this is also the text that is inserted when selecting + * this color presentation. + */ + label: string; + + /** + * An [edit](#TextEdit) which is applied to a document when selecting + * this presentation for the color. When `falsy` the [label](#ColorPresentation.label) + * is used. + */ + textEdit?: TextEdit; + + /** + * An optional array of additional [text edits](#TextEdit) that are applied when + * selecting this color presentation. Edits must not overlap with the main [edit](#ColorPresentation.textEdit) nor with themselves. + */ + additionalTextEdits?: TextEdit[]; + + /** + * Creates a new color presentation. + * + * @param label The label of this color presentation. + */ + constructor(label: string); + } + + /** + * The document color provider defines the contract between extensions and feature of + * picking and modifying colors in the editor. + */ + export interface DocumentColorProvider { + + /** + * Provide colors for the given document. + * + * @param document The document in which the command was invoked. + * @param token A cancellation token. + * @return An array of [color informations](#ColorInformation) or a thenable that resolves to such. The lack of a result + * can be signaled by returning `undefined`, `null`, or an empty array. + */ + provideDocumentColors(document: TextDocument, token: CancellationToken): ProviderResult; + + /** + * Provide [representations](#ColorPresentation) for a color. + * + * @param color The color to show and insert. + * @param context A context object with additional information + * @param token A cancellation token. + * @return An array of color presentations or a thenable that resolves to such. The lack of a result + * can be signaled by returning `undefined`, `null`, or an empty array. + */ + provideColorPresentations(color: Color, context: { document: TextDocument, range: Range }, token: CancellationToken): ProviderResult; + } + /** * A tuple of two characters, like a pair of * opening and closing brackets. @@ -4589,6 +4739,15 @@ declare module 'vscode' { */ export function showQuickPick(items: T[] | Thenable, options?: QuickPickOptions, token?: CancellationToken): Thenable; + /** + * Shows a selection list of [workspace folders](#workspace.workspaceFolders) to pick from. + * Returns `undefined` if no folder is open. + * + * @param options Configures the behavior of the workspace folder list. + * @return A promise that resolves to the workspace folder or `undefined`. + */ + export function showWorkspaceFolderPick(options?: WorkspaceFolderPickOptions): Thenable; + /** * Shows a file open dialog to the user which allows to select a file * for opening-purposes. @@ -4830,6 +4989,10 @@ declare module 'vscode' { * Args for the custom shell executable, this does not work on Windows (see #8429) */ shellArgs?: string[]; + /** + * Object with environment variables that will be added to the VS Code process. + */ + env?: { [key: string]: string | null }; } /** @@ -5044,6 +5207,14 @@ declare module 'vscode' { */ export let workspaceFolders: WorkspaceFolder[] | undefined; + /** + * The name of the workspace. `undefined` when no folder + * has been opened. + * + * @readonly + */ + export let name: string | undefined; + /** * An event that is emitted when a workspace folder is added or removed. */ @@ -5238,7 +5409,7 @@ declare module 'vscode' { /** * An event that is emitted when the [configuration](#WorkspaceConfiguration) changed. */ - export const onDidChangeConfiguration: Event; + export const onDidChangeConfiguration: Event; /** * Register a task provider. @@ -5250,6 +5421,21 @@ declare module 'vscode' { export function registerTaskProvider(type: string, provider: TaskProvider): Disposable; } + /** + * An event describing the change in Configuration + */ + export interface ConfigurationChangeEvent { + + /** + * Returns `true` if the given section for the given resource (if provided) is affected. + * + * @param section Configuration name, supports _dotted_ names. + * @param resource A resource Uri. + * @return `true` if the given section for the given resource (if provided) is affected. + */ + affectsConfiguration(section: string, resource?: Uri): boolean; + } + /** * Namespace for participating in language-specific editor [features](https://code.visualstudio.com/docs/editor/editingevolved), * like IntelliSense, code actions, diagnostics etc. @@ -5563,6 +5749,19 @@ declare module 'vscode' { */ export function registerDocumentLinkProvider(selector: DocumentSelector, provider: DocumentLinkProvider): Disposable; + /** + * Register a color provider. + * + * Multiple providers can be registered for a language. In that case providers are asked in + * parallel and the results are merged. A failing provider (rejected promise or exception) will + * not cause a failure of the whole operation. + * + * @param selector A selector that defines the documents this provider is applicable to. + * @param provider A color provider. + * @return A [disposable](#Disposable) that unregisters this provider when being disposed. + */ + export function registerColorProvider(selector: DocumentSelector, provider: DocumentColorProvider): Disposable; + /** * Set a [language configuration](#LanguageConfiguration) for a language. * @@ -5870,8 +6069,8 @@ declare module 'vscode' { /** * A debug configuration provider allows to add the initial debug configurations to a newly created launch.json - * and allows to resolve a launch configuration before it is used to start a new debug session. - * A debug configuration provider is registered via #workspace.registerDebugConfigurationProvider. + * and to resolve a launch configuration before it is used to start a new debug session. + * A debug configuration provider is registered via #debug.registerDebugConfigurationProvider. */ export interface DebugConfigurationProvider { /** @@ -5888,11 +6087,12 @@ declare module 'vscode' { * Resolves a [debug configuration](#DebugConfiguration) by filling in missing values or by adding/changing/removing attributes. * If more than one debug configuration provider is registered for the same type, the resolveDebugConfiguration calls are chained * in arbitrary order and the initial debug configuration is piped through the chain. + * Returning the value 'undefined' prevents the debug session from starting. * * @param folder The workspace folder from which the configuration originates from or undefined for a folderless setup. * @param debugConfiguration The [debug configuration](#DebugConfiguration) to resolve. * @param token A cancellation token. - * @return The resolved debug configuration. + * @return The resolved debug configuration or undefined. */ resolveDebugConfiguration?(folder: WorkspaceFolder | undefined, debugConfiguration: DebugConfiguration, token?: CancellationToken): ProviderResult; } From b88cb29d302fa0f549062c14258096e8ac210dee Mon Sep 17 00:00:00 2001 From: Pine Wu Date: Tue, 19 Mar 2019 22:23:31 -0700 Subject: [PATCH 069/337] VS Code 1.19 Extension API --- types/vscode/index.d.ts | 66 +++++++++++++++++++++++++++++++---------- 1 file changed, 51 insertions(+), 15 deletions(-) diff --git a/types/vscode/index.d.ts b/types/vscode/index.d.ts index 7587bbfbf3..6bfd97caf4 100644 --- a/types/vscode/index.d.ts +++ b/types/vscode/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Visual Studio Code 1.18 +// Type definitions for Visual Studio Code 1.19 // Project: https://github.com/microsoft/vscode // Definitions by: Visual Studio Code Team, Microsoft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,7 +10,7 @@ *--------------------------------------------------------------------------------------------*/ /** - * Type Definition for Visual Studio Code 1.18 Extension API + * Type Definition for Visual Studio Code 1.19 Extension API */ declare module 'vscode' { @@ -1724,7 +1724,15 @@ declare module 'vscode' { /** * A file glob pattern to match file paths against. This can either be a glob pattern string - * (like `**∕*.{ts,js}` or `*.{ts,js}`) or a [relative pattern](#RelativePattern). + * (like `**​/*.{ts,js}` or `*.{ts,js}`) or a [relative pattern](#RelativePattern). + * + * Glob patterns can have the following syntax: + * * `*` to match one or more characters in a path segment + * * `?` to match on one character in a path segment + * * `**` to match any number of path segments, including none + * * `{}` to group conditions (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files) + * * `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) + * * `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) */ export type GlobPattern = string | RelativePattern; @@ -1734,7 +1742,7 @@ declare module 'vscode' { * its resource, or a glob-pattern that is applied to the [path](#TextDocument.fileName). * * @sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }` - * @sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**∕package.json' }` + * @sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**​/package.json' }` */ export interface DocumentFilter { @@ -1760,7 +1768,7 @@ declare module 'vscode' { * and [language filters](#DocumentFilter). * * @sample `let sel:DocumentSelector = 'typescript'`; - * @sample `let sel:DocumentSelector = ['typescript', { language: 'json', pattern: '**∕tsconfig.json' }]`; + * @sample `let sel:DocumentSelector = ['typescript', { language: 'json', pattern: '**​/tsconfig.json' }]`; */ export type DocumentSelector = string | DocumentFilter | (string | DocumentFilter)[]; @@ -1801,7 +1809,6 @@ declare module 'vscode' { * a [code action](#CodeActionProvider.provideCodeActions) is run. */ export interface CodeActionContext { - /** * An array of diagnostics. */ @@ -2912,12 +2919,11 @@ declare module 'vscode' { * The completion item provider interface defines the contract between extensions and * [IntelliSense](https://code.visualstudio.com/docs/editor/intellisense). * - * When computing *complete* completion items is expensive, providers can optionally implement - * the `resolveCompletionItem`-function. In that case it is enough to return completion - * items with a [label](#CompletionItem.label) from the - * [provideCompletionItems](#CompletionItemProvider.provideCompletionItems)-function. Subsequently, - * when a completion item is shown in the UI and gains focus this provider is asked to resolve - * the item, like adding [doc-comment](#CompletionItem.documentation) or [details](#CompletionItem.detail). + * Providers can delay the computation of the [`detail`](#CompletionItem.detail) + * and [`documentation`](#CompletionItem.documentation) properties by implementing the + * [`resolveCompletionItem`](#CompletionItemProvider.resolveCompletionItem)-function. However, properties that + * are needed for the inital sorting and filtering, like `sortText`, `filterText`, `insertText`, and `range`, must + * not be changed during resolve. * * Providers are asked for completions either explicitly by a user gesture or -depending on the configuration- * implicitly when typing words or trigger characters. @@ -3456,7 +3462,7 @@ declare module 'vscode' { uri: Uri; /** - * The document range of this locations. + * The document range of this location. */ range: Range; @@ -4500,7 +4506,7 @@ declare module 'vscode' { * has changed. *Note* that the event also fires when the active editor changes * to `undefined`. */ - export const onDidChangeActiveTextEditor: Event; + export const onDidChangeActiveTextEditor: Event; /** * An [event](#Event) which fires when the array of [visible editors](#window.visibleTextEditors) @@ -5264,7 +5270,7 @@ declare module 'vscode' { /** * Find files across all [workspace folders](#workspace.workspaceFolders) in the workspace. * - * @sample `findFiles('**∕*.js', '**∕node_modules∕**', 10)` + * @sample `findFiles('**​/*.js', '**​/node_modules/**', 10)` * @param include A [glob pattern](#GlobPattern) that defines the files to search for. The glob pattern * will be matched against the file paths of resulting matches relative to their workspace. Use a [relative pattern](#RelativePattern) * to restrict the search results to a [workspace folder](#WorkspaceFolder). @@ -5781,6 +5787,11 @@ declare module 'vscode' { * Setter and getter for the contents of the input box. */ value: string; + + /** + * A string to show as place holder in the input box to guide the user. + */ + placeholder: string; } interface QuickDiffProvider { @@ -6097,6 +6108,26 @@ declare module 'vscode' { resolveDebugConfiguration?(folder: WorkspaceFolder | undefined, debugConfiguration: DebugConfiguration, token?: CancellationToken): ProviderResult; } + /** + * Represents the debug console. + */ + export interface DebugConsole { + /** + * Append the given value to the debug console. + * + * @param value A string, falsy values will not be printed. + */ + append(value: string): void; + + /** + * Append the given value and a line feed character + * to the debug console. + * + * @param value A string, falsy values will be printed. + */ + appendLine(value: string): void; + } + /** * Namespace for dealing with debug sessions. */ @@ -6121,6 +6152,11 @@ declare module 'vscode' { */ export let activeDebugSession: DebugSession | undefined; + /** + * The currently active [debug console](#DebugConsole). + */ + export let activeDebugConsole: DebugConsole; + /** * An [event](#Event) which fires when the [active debug session](#debug.activeDebugSession) * has changed. *Note* that the event also fires when the active debug session changes From f219b3a99acaa6cde232f10511c4b993e7e395bc Mon Sep 17 00:00:00 2001 From: Pine Wu Date: Tue, 19 Mar 2019 22:27:51 -0700 Subject: [PATCH 070/337] Add a link to vscode website --- types/vscode/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/vscode/index.d.ts b/types/vscode/index.d.ts index 6bfd97caf4..d326575601 100644 --- a/types/vscode/index.d.ts +++ b/types/vscode/index.d.ts @@ -11,6 +11,7 @@ /** * Type Definition for Visual Studio Code 1.19 Extension API + * See https://code.visualstudio.com/api for more information */ declare module 'vscode' { From 44797ba9e9f0eb57b4f87af7c70c1b62e38dc383 Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Wed, 20 Mar 2019 08:27:21 +0100 Subject: [PATCH 071/337] fix review findings --- types/node/test/util.ts | 2 +- types/node/ts3.2/node-tests.ts | 20 ++++++++++++++++++++ types/node/util.d.ts | 2 +- types/node/v10/node-tests.ts | 2 +- types/node/v10/ts3.2/node-tests.ts | 20 ++++++++++++++++++++ types/node/v10/util.d.ts | 2 +- 6 files changed, 44 insertions(+), 4 deletions(-) diff --git a/types/node/test/util.ts b/types/node/test/util.ts index 0dd1843b9c..f0208c4ada 100644 --- a/types/node/test/util.ts +++ b/types/node/test/util.ts @@ -159,7 +159,7 @@ import { readFile } from 'fs'; const teEncodeRes: Uint8Array = te.encode("TextEncoder"); // util.types - let b: Boolean; + let b: boolean; b = util.types.isBigInt64Array(15); b = util.types.isBigUint64Array(15); b = util.types.isModuleNamespaceObject(15); diff --git a/types/node/ts3.2/node-tests.ts b/types/node/ts3.2/node-tests.ts index 3f64e22e81..18de85a3a1 100644 --- a/types/node/ts3.2/node-tests.ts +++ b/types/node/ts3.2/node-tests.ts @@ -1,5 +1,6 @@ // tslint:disable-next-line:no-bad-reference import "../node-tests"; +import * as util from "util"; ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -9,3 +10,22 @@ import "../node-tests"; const hrtimeBigint: bigint = process.hrtime.bigint(); } } + +////////////////////////////////////////////////////////// +/// Util Tests /// +////////////////////////////////////////////////////////// +{ + { + const value: BigInt64Array | BigUint64Array | number = [] as any; + if (util.types.isBigInt64Array(value)) { + // $ExpectType BigInt64Array + const b = value; + } else if (util.types.isBigUint64Array(value)) { + // $ExpectType BigUint64Array + const b = value; + } else { + // $ExpectType number + const b = value; + } + } +} diff --git a/types/node/util.d.ts b/types/node/util.d.ts index 05edbfcf5b..14a1c2c495 100644 --- a/types/node/util.d.ts +++ b/types/node/util.d.ts @@ -114,7 +114,7 @@ declare module "util" { function isArrayBuffer(object: any): object is ArrayBuffer; function isAsyncFunction(object: any): boolean; function isBooleanObject(object: any): object is Boolean; - function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* BigInt */); + function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); function isDataView(object: any): object is DataView; function isDate(object: any): object is Date; function isExternal(object: any): boolean; diff --git a/types/node/v10/node-tests.ts b/types/node/v10/node-tests.ts index 1e40139731..e13f8b313a 100644 --- a/types/node/v10/node-tests.ts +++ b/types/node/v10/node-tests.ts @@ -952,7 +952,7 @@ function bufferTests() { const teEncodeRes: Uint8Array = te.encode("TextEncoder"); // util.types - let b: Boolean; + let b: boolean; b = util.types.isBigInt64Array(15); b = util.types.isBigUint64Array(15); b = util.types.isModuleNamespaceObject(15); diff --git a/types/node/v10/ts3.2/node-tests.ts b/types/node/v10/ts3.2/node-tests.ts index 3f64e22e81..18de85a3a1 100644 --- a/types/node/v10/ts3.2/node-tests.ts +++ b/types/node/v10/ts3.2/node-tests.ts @@ -1,5 +1,6 @@ // tslint:disable-next-line:no-bad-reference import "../node-tests"; +import * as util from "util"; ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -9,3 +10,22 @@ import "../node-tests"; const hrtimeBigint: bigint = process.hrtime.bigint(); } } + +////////////////////////////////////////////////////////// +/// Util Tests /// +////////////////////////////////////////////////////////// +{ + { + const value: BigInt64Array | BigUint64Array | number = [] as any; + if (util.types.isBigInt64Array(value)) { + // $ExpectType BigInt64Array + const b = value; + } else if (util.types.isBigUint64Array(value)) { + // $ExpectType BigUint64Array + const b = value; + } else { + // $ExpectType number + const b = value; + } + } +} diff --git a/types/node/v10/util.d.ts b/types/node/v10/util.d.ts index 07c21bf47e..05b6ab3df1 100644 --- a/types/node/v10/util.d.ts +++ b/types/node/v10/util.d.ts @@ -114,7 +114,7 @@ declare module "util" { function isArrayBuffer(object: any): object is ArrayBuffer; function isAsyncFunction(object: any): boolean; function isBooleanObject(object: any): object is Boolean; - function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* BigInt */); + function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); function isDataView(object: any): object is DataView; function isDate(object: any): object is Date; function isExternal(object: any): boolean; From 7b79531f48fb6a80eb811a458a3c4d42c8893da4 Mon Sep 17 00:00:00 2001 From: breeze9527 Date: Wed, 20 Mar 2019 17:58:41 +0800 Subject: [PATCH 072/337] [amap-js-api-indoor-map] reverse overloads order --- types/amap-js-api-indoor-map/index.d.ts | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/types/amap-js-api-indoor-map/index.d.ts b/types/amap-js-api-indoor-map/index.d.ts index b19082e926..03c2a6bb2f 100644 --- a/types/amap-js-api-indoor-map/index.d.ts +++ b/types/amap-js-api-indoor-map/index.d.ts @@ -73,29 +73,28 @@ declare namespace AMap { class IndoorMap extends Layer { constructor(options?: IndoorMap.Options); + showIndoorMap( + indoorId: string, + callback?: (error: null | Error, result: IndoorMap.SearchResult) => void + ): void; + showIndoorMap( + indoorId: string, + floor?: number, + callback?: (error: null | Error, result: IndoorMap.SearchResult) => void + ): void; showIndoorMap( indoorId: string, floor?: number, shopId?: string, - noMove?: boolean, callback?: (error: null | Error, result: IndoorMap.SearchResult) => void ): void; showIndoorMap( indoorId: string, floor?: number, shopId?: string, + noMove?: boolean, callback?: (error: null | Error, result: IndoorMap.SearchResult) => void ): void; - showIndoorMap( - indoorId: string, - floor?: number, - callback?: (error: null | Error, result: IndoorMap.SearchResult) => void - ): void; - showIndoorMap( - indoorId: string, - callback?: (error: null | Error, result: IndoorMap.SearchResult) => void - ): void; - showFloor(floor: number, noMove?: boolean): false | undefined; showFloorBar(): void; hideFloorBar(): void; From 2cef25af737a426a783942b91888eb168674d940 Mon Sep 17 00:00:00 2001 From: Karlis Melderis Date: Wed, 20 Mar 2019 14:45:18 +0100 Subject: [PATCH 073/337] add path prop to ArchiverError type --- types/archiver/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/archiver/index.d.ts b/types/archiver/index.d.ts index a9cafca24b..a25b018c11 100644 --- a/types/archiver/index.d.ts +++ b/types/archiver/index.d.ts @@ -41,6 +41,8 @@ declare namespace archiver { class ArchiverError extends Error { code: string; // Since archiver format support is modular, we cannot enumerate all possible error codes, as the modules can throw arbitrary ones. data: any; + path?: any; + constructor(code: string, data: any); } From 5d13cc220d4e8b3fed57eedbe0872028f9a0af41 Mon Sep 17 00:00:00 2001 From: Sander Siim Date: Wed, 20 Mar 2019 16:14:47 +0200 Subject: [PATCH 074/337] Add FullscreenControl component type definition added in react-map-gl 4.1 --- types/react-map-gl/index.d.ts | 10 +++++++++- types/react-map-gl/react-map-gl-tests.tsx | 2 ++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/types/react-map-gl/index.d.ts b/types/react-map-gl/index.d.ts index 04c4d9aed9..23b723a594 100644 --- a/types/react-map-gl/index.d.ts +++ b/types/react-map-gl/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for react-map-gl 4.0 +// Type definitions for react-map-gl 4.1 // Project: https://github.com/uber/react-map-gl#readme // Definitions by: Robert Imig // Fabio Berta +// Sander Siim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 @@ -309,6 +310,13 @@ export interface NavigationControlProps extends BaseControlProps { export class NavigationControl extends BaseControl {} +export interface FullscreenControlProps extends BaseControlProps { + className?: string; + container?: HTMLElement | null; +} + +export class FullscreenControl extends BaseControl {} + export interface DraggableControlProps extends BaseControlProps { draggable?: boolean; onDrag?: (event: DragEvent) => void; diff --git a/types/react-map-gl/react-map-gl-tests.tsx b/types/react-map-gl/react-map-gl-tests.tsx index c9024287c9..6740ad0eb4 100644 --- a/types/react-map-gl/react-map-gl-tests.tsx +++ b/types/react-map-gl/react-map-gl-tests.tsx @@ -5,6 +5,7 @@ import { CanvasOverlay, SVGOverlay, HTMLOverlay, + FullscreenControl, CanvasRedrawOptions, HTMLRedrawOptions, SVGRedrawOptions, @@ -37,6 +38,7 @@ class MyMap extends React.Component<{}, State> { width={400} ref={this.setRefInteractive} > + { const { From cfea3610cec286931f97f9b6c470d55dd75e88ad Mon Sep 17 00:00:00 2001 From: Kirill Kvashonin Date: Wed, 20 Mar 2019 17:56:34 +0300 Subject: [PATCH 075/337] types for scroll-to-element --- types/scroll-to-element/index.d.ts | 15 ++++++++++++ .../scroll-to-element-tests.ts | 19 +++++++++++++++ types/scroll-to-element/tsconfig.json | 24 +++++++++++++++++++ types/scroll-to-element/tslint.json | 1 + 4 files changed, 59 insertions(+) create mode 100644 types/scroll-to-element/index.d.ts create mode 100644 types/scroll-to-element/scroll-to-element-tests.ts create mode 100644 types/scroll-to-element/tsconfig.json create mode 100644 types/scroll-to-element/tslint.json diff --git a/types/scroll-to-element/index.d.ts b/types/scroll-to-element/index.d.ts new file mode 100644 index 0000000000..d2faf83658 --- /dev/null +++ b/types/scroll-to-element/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for scroll-to-element 2.0 +// Project: https://github.com/willhoag/scroll-to-element +// Definitions by: Kirill Kvashonin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Options { + offset?: number; + align?: 'top' | 'middle' | 'bottom'; + ease?: string; + duration?: number; +} + +declare function scrollToElement(selector: string | HTMLElement | Element, options?: Options): void; + +export default scrollToElement; diff --git a/types/scroll-to-element/scroll-to-element-tests.ts b/types/scroll-to-element/scroll-to-element-tests.ts new file mode 100644 index 0000000000..a9d3d33d81 --- /dev/null +++ b/types/scroll-to-element/scroll-to-element-tests.ts @@ -0,0 +1,19 @@ +import scrollToElement from 'scroll-to-element'; + +scrollToElement('#id'); + +// with options +scrollToElement('.className', { + offset: 0, + ease: 'out-bounce', + duration: 1500 +}); + +// or if you already have a reference to the element +const elem = document.querySelector('.className'); +scrollToElement(elem, { + offset: 0, + ease: 'out-bounce', + align: 'top', + duration: 1500 +}); diff --git a/types/scroll-to-element/tsconfig.json b/types/scroll-to-element/tsconfig.json new file mode 100644 index 0000000000..f11fef6ecb --- /dev/null +++ b/types/scroll-to-element/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "scroll-to-element-tests.ts" + ] +} diff --git a/types/scroll-to-element/tslint.json b/types/scroll-to-element/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/scroll-to-element/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file From c2b85164cc1ab17c95f9c8e1c72d63f5179828e7 Mon Sep 17 00:00:00 2001 From: Bradley Hill Date: Wed, 20 Mar 2019 09:58:36 -0500 Subject: [PATCH 076/337] Fabric Polyline pathOffset exposed (just like Path). It is always set in initializer. --- types/fabric/fabric-impl.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 5b2a7c13af..96034c0b5f 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -3642,6 +3642,9 @@ export class Polyline extends Object { * @param [skipOffset] Whether points offsetting should be skipped */ constructor(points: Array<{ x: number; y: number }>, options?: IPolylineOptions); + + pathOffset: Point; + /** * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) */ From a47d29e744dbb7cc696871118f4d77c85e9c9078 Mon Sep 17 00:00:00 2001 From: Jim Li Date: Wed, 20 Mar 2019 11:39:30 -0400 Subject: [PATCH 077/337] [react-dom] Add test for charCode in synthetic events --- types/react-dom/v15/react-dom-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-dom/v15/react-dom-tests.ts b/types/react-dom/v15/react-dom-tests.ts index 5f5b149594..8d10405a86 100644 --- a/types/react-dom/v15/react-dom-tests.ts +++ b/types/react-dom/v15/react-dom-tests.ts @@ -61,7 +61,7 @@ describe('React dom test utils', () => { node.value = 'giraffe'; ReactTestUtils.Simulate.change(node); - ReactTestUtils.Simulate.keyDown(node, { key: "Enter", keyCode: 13, which: 13 }); + ReactTestUtils.Simulate.keyDown(node, { key: "Enter", charCode: 13, keyCode: 13, which: 13 }); }); it('renderIntoDocument', () => { From 09dbb2e98ec20e898dc11dbb80c1ae6836e33faf Mon Sep 17 00:00:00 2001 From: Diamond Lewis Date: Wed, 20 Mar 2019 11:03:32 -0500 Subject: [PATCH 078/337] type fixes --- types/parse/index.d.ts | 56 ++++++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 26 deletions(-) diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index 6c3aa122f1..da3fde2dc6 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -24,6 +24,10 @@ declare namespace Parse { let liveQueryServerURL: string; let VERSION: string; + interface BatchSizeOption { + batchSize?: number; + } + interface SuccessOption { success?: Function; } @@ -267,25 +271,25 @@ declare namespace Parse { constructor(attributes?: string[], options?: any); static createWithoutData(id: string): T; - static destroyAll(list: T[], options?: Object.DestroyAllOptions): Promise; - static extend(className: string, protoProps?: any, classProps?: any): any; + static destroyAll(list: T[], options?: Object.DestroyAllOptions): Promise; + static extend(className: string | { className: string }, protoProps?: any, classProps?: any): any; static fetchAll(list: T[], options: Object.FetchAllOptions): Promise; static fetchAllIfNeeded(list: T[], options: Object.FetchAllOptions): Promise; - static fetchAllWithInclude(list: any, keys: any, options: any): any; + static fetchAllWithInclude(list: T[], keys: string | Array>, options: Object.RequestOptions): any; static fromJSON(json: any, override: boolean): any; static pinAll(objects: Object[]): Promise; static pinAllWithName(name: string, objects: Object[]): Promise; static registerSubclass(className: string, clazz: new (options?: any) => T): void; static saveAll(list: T[], options?: Object.SaveAllOptions): Promise; - static unPinAll(objects: any): Promise; + static unPinAll(objects: Object[]): Promise; static unPinAllObjects(): Promise; - static unPinAllObjectsWithName(name: string): Promise; - static unPinAllWithName(...args: any[]): Promise; + static unPinAllObjectsWithName(name: string): Promise; + static unPinAllWithName(name: string, objects: Object[]): Promise; - add(attr: string, item: any): this; - addAll(attr: string, items: any[]): this; - addAllUnique(attr: string, items: any[]): this; - addUnique(attr: string, item: any): this; + add(attr: string, item: any): this | boolean; + addAll(attr: string, items: any[]): this | boolean; + addAllUnique(attr: string, items: any[]): this | boolean; + addUnique(attr: string, item: any): this | boolean; change(options: any): this; changedAttributes(diff: any): boolean; clear(options: any): any; @@ -298,7 +302,7 @@ declare namespace Parse { existed(): boolean; fetch(options?: Object.FetchOptions): Promise; fetchFromLocalDatastore(): Promise | void; - fetchWithInclude(keys: string[], options?: any): Promise; + fetchWithInclude(keys: keys: string | Array>, options?: Object.RequestOptions): Promise; get(attr: string): any | undefined; getACL(): ACL | undefined; has(attr: string): boolean; @@ -306,16 +310,16 @@ declare namespace Parse { increment(attr: string, amount?: number): any; initialize(): void; isNew(): boolean; - isPinned(...args: any[]): Promise; + isPinned(): Promise; isValid(): boolean; op(attr: string): any; - pin(): Promise; - pinWithName(name: string): Promise; + pin(): Promise; + pinWithName(name: string): Promise; previous(attr: string): any; previousAttributes(): any; relation(attr: string): Relation; - remove(attr: string, item: any): any; - removeAll(attr: string, items: any): any; + remove(attr: string, item: any): this | boolean; + removeAll(attr: string, items: any): this | boolean; revert(): void; save(attrs?: { [key: string]: any } | null, options?: Object.SaveOptions): Promise; save(key: string, value: any, options?: Object.SaveOptions): Promise; @@ -324,8 +328,8 @@ declare namespace Parse { set(attrs: object, options?: Object.SetOptions): boolean; setACL(acl: ACL, options?: SuccessFailureOptions): boolean; toPointer(): Pointer; - unPin(): Promise; - unPinWithName(name: string): Promise; + unPin(): Promise; + unPinWithName(name: string): Promise; unset(attr: string, options?: any): any; validate(attrs: any, options?: SuccessFailureOptions): boolean; } @@ -333,7 +337,7 @@ declare namespace Parse { namespace Object { interface DestroyOptions extends SuccessFailureOptions, WaitOption, ScopeOptions { } - interface DestroyAllOptions extends SuccessFailureOptions, ScopeOptions { } + interface DestroyAllOptions extends BatchSizeOption, ScopeOptions { } interface FetchAllOptions extends SuccessFailureOptions, ScopeOptions { } @@ -341,14 +345,14 @@ declare namespace Parse { interface SaveOptions extends SuccessFailureOptions, SilentOption, ScopeOptions, WaitOption { } - interface SaveAllOptions extends SuccessFailureOptions, ScopeOptions { } + interface SaveAllOptions extends BatchSizeOption, ScopeOptions { } interface SetOptions extends ErrorOption, SilentOption { promise?: any; } } - class Polygon extends BaseObject { + class Polygon extends BaseObject { constructor(arg1: GeoPoint[] | number[][]); containsPoint(point: GeoPoint): boolean; equals(other: Polygon | any): boolean; @@ -438,7 +442,7 @@ declare namespace Parse { constructor(objectClass: new (...args: any[]) => T); static and(...args: Query[]): Query; - static fromJSON(className: any, json: any): Query; + static fromJSON(className: string, json: any): Query; static nor(...args: Query[]): Query; static or(...var_args: Query[]): Query; @@ -453,7 +457,7 @@ declare namespace Parse { containedIn(key: string, values: any[]): Query; contains(key: string, substring: string): Query; containsAll(key: string, values: any[]): Query; - containsAllStartingWith(key: string, values: any[]): Query; + containsAllStartingWith(key: string, values: string[]): Query; count(options?: Query.CountOptions): Promise; descending(key: string): Query; descending(key: string[]): Query; @@ -489,10 +493,10 @@ declare namespace Parse { polygonContains(key: string, point: GeoPoint): Query; select(...keys: string[]): Query; skip(n: number): Query; - sortByTextScore(): any; + sortByTextScore(): this; startsWith(key: string, prefix: string): Query; subscribe(): LiveQuerySubscription; - withJSON(json: any): any; + withJSON(json: any): this; withinGeoBox(key: string, southwest: GeoPoint, northeast: GeoPoint): Query; withinKilometers(key: string, point: GeoPoint, maxDistance: number): Query; withinMiles(key: string, point: GeoPoint, maxDistance: number): Query; @@ -659,7 +663,7 @@ subscription.on('close', () => {}); class User extends Object { static allowCustomUserClass(isAllowed: boolean): void; - static become(sessionToken: string, options?: SuccessFailureOptions): Promise; + static become(sessionToken: string, options?: UseMasterKeyOption): Promise; static current(): User | undefined; static currentAsync(): Promise; static signUp(username: string, password: string, attrs: any, options?: SignUpOptions): Promise; From 9679af37366557bd8c48cbcabfb99b00202a9f3d Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 20 Mar 2019 09:18:48 -0700 Subject: [PATCH 079/337] Switch incorrect 'export default' to 'export =' --- types/riot-route/index.d.ts | 2 +- types/riot-route/riot-route-tests.ts | 2 +- types/rollup-plugin-json/index.d.ts | 37 ++++++++++--------- .../rollup-plugin-json-tests.ts | 2 +- 4 files changed, 23 insertions(+), 20 deletions(-) diff --git a/types/riot-route/index.d.ts b/types/riot-route/index.d.ts index 453bb185fa..a771b3096d 100644 --- a/types/riot-route/index.d.ts +++ b/types/riot-route/index.d.ts @@ -6,4 +6,4 @@ import route from './lib/index'; -export default route; +export = route; diff --git a/types/riot-route/riot-route-tests.ts b/types/riot-route/riot-route-tests.ts index fab6a2b0df..496c8c7fb4 100644 --- a/types/riot-route/riot-route-tests.ts +++ b/types/riot-route/riot-route-tests.ts @@ -1,4 +1,4 @@ -import { default as route } from 'riot-route'; +import route = require('riot-route'); import routeFromTag from 'riot-route/lib/tag'; /* () */ diff --git a/types/rollup-plugin-json/index.d.ts b/types/rollup-plugin-json/index.d.ts index b6b61b25e5..c906d90e8a 100644 --- a/types/rollup-plugin-json/index.d.ts +++ b/types/rollup-plugin-json/index.d.ts @@ -8,22 +8,25 @@ /// import { Plugin } from 'rollup'; -export interface Options { - /** - * All JSON files will be parsed by default, but you can also specifically include/exclude files - */ - include?: string | string[]; - exclude?: string | string[]; - /** - * for tree-shaking, properties will be declared as variables, using either `var` or `const` - * @default false - */ - preferConst?: boolean; - /** - * specify indentation for the generated default export — defaults to '\t' - * @default '\t' - */ - indent?: string; +declare namespace json { + interface Options { + /** + * All JSON files will be parsed by default, but you can also specifically include/exclude files + */ + include?: string | string[]; + exclude?: string | string[]; + /** + * for tree-shaking, properties will be declared as variables, using either `var` or `const` + * @default false + */ + preferConst?: boolean; + /** + * specify indentation for the generated default export — defaults to '\t' + * @default '\t' + */ + indent?: string; + } } -export default function json(options?: Options): Plugin; +declare function json(options?: json.Options): Plugin; +export = json; diff --git a/types/rollup-plugin-json/rollup-plugin-json-tests.ts b/types/rollup-plugin-json/rollup-plugin-json-tests.ts index 32e7b26b7a..ed3ddc2b72 100644 --- a/types/rollup-plugin-json/rollup-plugin-json-tests.ts +++ b/types/rollup-plugin-json/rollup-plugin-json-tests.ts @@ -1,4 +1,4 @@ -import json from 'rollup-plugin-json'; +import json = require('rollup-plugin-json'); json(); // $ExpectType Plugin From fab55e0af1f9ccfb00dbc26281e87bfb60ad8e77 Mon Sep 17 00:00:00 2001 From: Diamond Lewis Date: Wed, 20 Mar 2019 11:38:30 -0500 Subject: [PATCH 080/337] fix tests --- types/parse/index.d.ts | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index da3fde2dc6..ba3d546ca5 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -36,6 +36,24 @@ declare namespace Parse { error?: Function; } + interface FullOptions { + success?: Function; + error?: Function; + useMasterKey?: boolean; + sessionToken?: string; + installationId?: string; + progress?: Function; + } + + interface RequestOptions { + useMasterKey?: boolean; + sessionToken?: string; + installationId?: string; + batchSize?: number; + include?: string | string[]; + progress?: Function; + } + interface SuccessFailureOptions extends SuccessOption, ErrorOption { } @@ -275,7 +293,7 @@ declare namespace Parse { static extend(className: string | { className: string }, protoProps?: any, classProps?: any): any; static fetchAll(list: T[], options: Object.FetchAllOptions): Promise; static fetchAllIfNeeded(list: T[], options: Object.FetchAllOptions): Promise; - static fetchAllWithInclude(list: T[], keys: string | Array>, options: Object.RequestOptions): any; + static fetchAllWithInclude(list: T[], keys: string | Array>, options: RequestOptions): Promise; static fromJSON(json: any, override: boolean): any; static pinAll(objects: Object[]): Promise; static pinAllWithName(name: string, objects: Object[]): Promise; @@ -302,7 +320,7 @@ declare namespace Parse { existed(): boolean; fetch(options?: Object.FetchOptions): Promise; fetchFromLocalDatastore(): Promise | void; - fetchWithInclude(keys: keys: string | Array>, options?: Object.RequestOptions): Promise; + fetchWithInclude(keys: string | Array>, options?: RequestOptions): Promise; get(attr: string): any | undefined; getACL(): ACL | undefined; has(attr: string): boolean; @@ -457,7 +475,7 @@ declare namespace Parse { containedIn(key: string, values: any[]): Query; contains(key: string, substring: string): Query; containsAll(key: string, values: any[]): Query; - containsAllStartingWith(key: string, values: string[]): Query; + containsAllStartingWith(key: string, values: any[]): Query; count(options?: Query.CountOptions): Promise; descending(key: string): Query; descending(key: string[]): Query; From e7d6af3d2cbb0383325896c5e56acdaabb8643ba Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 20 Mar 2019 10:15:17 -0700 Subject: [PATCH 081/337] Update react-table to 6.8 The change from #30638 was first introduced in 6.6, but @types/react-table was already at 6.7, so the correct change is to bump it to 6.8 for a breaking change like this. --- types/react-table/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-table/index.d.ts b/types/react-table/index.d.ts index 626e420cb6..6327eb6128 100644 --- a/types/react-table/index.d.ts +++ b/types/react-table/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-table 6.6 +// Type definitions for react-table 6.8 // Project: https://github.com/react-tools/react-table // Definitions by: Roy Xue , // Pavel Sakalo , From 70e0999d26f109ec0f2f007fa38ae743d7280d02 Mon Sep 17 00:00:00 2001 From: Konrad Klockgether <12186615+Nielio@users.noreply.github.com> Date: Wed, 20 Mar 2019 18:19:44 +0100 Subject: [PATCH 082/337] Added: Polygon and Vec2 typings (#33696) * Type definitions for Vec2 and Polygon Polygon requires Vec2 * [vec2] lint * [polygon] lint * [polygon] export default * [vec2] export default * [polygon] use global package reference * [polygon] remove package.json * [polygon] add member-access keywords; Remove doc tags without description * [vec2] add member-access keywords; Remove doc tags without description * [vec2] constructor test * [polygon] simple test * [polygon] correct parameter name * [vec2] comments in test * [vec2] remove member-access rule * [vec2] remove member-access rule * [polygon] remove member-access rule * [polygon] [vec2] change export type * [polygon] fix vec2 import * [polygon] use default export * [vec2] use default export * [vec2] try `export = Vec2;` * [polygon] try `export = Polygon;` * Revert "[polygon] try `export = Polygon;`" This reverts commit 62131e05 * Revert "[vec2] try `export = Vec2;`" This reverts commit 0fba20c7 * [vec2] [polygon] try `export = Vec2;` and `export = Polygon;` * [vec2] [polygon] try `export = Vec2;` and `export = Polygon;` --- types/polygon/index.d.ts | 190 ++++++++++++++++++++++++++++++++ types/polygon/polygon-tests.ts | 16 +++ types/polygon/tsconfig.json | 23 ++++ types/polygon/tslint.json | 3 + types/vec2/index.d.ts | 191 +++++++++++++++++++++++++++++++++ types/vec2/tsconfig.json | 23 ++++ types/vec2/tslint.json | 3 + types/vec2/vec2-tests.ts | 8 ++ 8 files changed, 457 insertions(+) create mode 100644 types/polygon/index.d.ts create mode 100644 types/polygon/polygon-tests.ts create mode 100644 types/polygon/tsconfig.json create mode 100644 types/polygon/tslint.json create mode 100644 types/vec2/index.d.ts create mode 100644 types/vec2/tsconfig.json create mode 100644 types/vec2/tslint.json create mode 100644 types/vec2/vec2-tests.ts diff --git a/types/polygon/index.d.ts b/types/polygon/index.d.ts new file mode 100644 index 0000000000..c5e7adb827 --- /dev/null +++ b/types/polygon/index.d.ts @@ -0,0 +1,190 @@ +// Type definitions for polygon 1.0 +// Project: https://github.com/tmpvar/polygon.js#readme +// Definitions by: Konrad Klockgether +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* tslint:disable:array-type */ // cause contradictory error messages + +import Vec2 = require('vec2'); + +/** + * Create a new polygon: + * + * ```javascript + * var p = new Polygon([ + * Vec2(0, 0), + * Vec2(10, 0), + * Vec2(0, 10) + * ]); + * + * ``` + * + * You can pass an array of `Vec2`s, arrays `[x, y]`, or objects `{ x: 10, y: 20 }` + * + * **Stuff to Note**: most of the Vec2's methods take a `returnNew` as the last parameter. + * If passed a truthy value, a new vector will be returned to you. + * Otherwise the operation will be applied to `this` and `this` will be returned. + */ +declare class Polygon { + readonly points: Vec2[]; + + /** + * Returns the number of points in this polygon + */ + readonly length: number; + + constructor(points: Vec2[] | number[][] | { x: number, y: number }[]); + + /** + * Something like Array.forEach on points + */ + each(fn: (prev: Vec2, current: Vec2, next: Vec2, idx: number) => any): Polygon; + + /** + * Returns the point at index `idx`. note: this will wrap in both directions + */ + point(idx: number): Vec2; + + /** + * Ensure all of the points are unique + */ + dedupe(returnNew?: boolean): Polygon; + + /** + * Insert `vec2` at the specified index + */ + insert(vec2: Vec2, index: number): void; + + /** + * Remove the specified `vec2` or numeric index from this polygon + */ + remove(vecOrIndex: Vec2 | number): Polygon; + + /** + * Removes contiguous points that are the same + */ + clean(returnNew?: boolean): Polygon; + + /** + * Returns the direction in which a polygon is wound (true === clockwise) + */ + winding(): boolean; + + /** + * Rewinds the polygon in the specified direction (true === clockwise) + */ + rewind(cw: boolean): Polygon; + + /** + * Computes the area of the polygon + */ + area(): number; + + /** + * Finds the closest point in this polygon to `vec2` + */ + closestPointTo(vec2: Vec2): Vec2; + + /** + * Returns a `Vec2` at the center of the AABB + */ + center(): Vec2; + + /** + * Scales this polygon around `origin` (default is `this.center()`) and will return a new polygon if requested with `returnNew` + */ + scale(amount: number, origin: Vec2, returnNew?: boolean): Polygon; + + /** + * Returns true if `vec2` is inside the polygon + */ + containsPoint(vec2: Vec2): boolean; + + /** + * Returns true if `poly` is completely contained in this polygon + */ + containsPolygon(poly: Polygon): boolean; + + /** + * Returns an object `{x:_, y:_, w:_, h:_}` representing the axis-aligned bounding box of this polygyon + */ + aabb(): { x: number, y: number, w: number, h: number }; + + /** + * Performs an offset/buffering operation on this polygon and returns a new one + */ + offset(amount: number): Polygon; + + /** + * Return an array `[startpoint, endpoint]` representing the line at the specified `index` + */ + line(index: number): [Vec2, Vec2]; + + /** + * Iterate over the lines in this polygon + */ + lines(fn: (start: Vec2, end: Vec2, index: number) => any): Polygon; + + /** + * Find self-intersections and return them as a new polygon + */ + selfIntersections(): Polygon; + + /** + * Remove self intersections from this polygon. returns an array of polygons + */ + pruneSelfIntersections(): Polygon[]; + + /** + * Return a new instance of this polygon + */ + clone(): Polygon; + + /** + * Rotate by origin `vec2` (default `this.center()`) by radians `rads` and return a clone if `returnNew` is specified + */ + rotate(rads: number, vec2: Vec2, returnNew?: boolean): Polygon; + + /** + * Translate by `vec2` and return a clone if `returnNew` is specified + */ + translate(vec2: Vec2, returnNew?: boolean): Polygon; + + /** + * Return true if this polygon has the same components and the incoming `poly` + */ + equal(poly: Polygon): boolean; + + /** + * Works with an array of vec2's, + * an object containing a `.position` and `.radius`, + * an object populated with x1,y1,x2,y2, + * an object populated with x,y,w,h, + * and an object populated with x,y,width,height. + * See the tests for more info + */ + contains( + thing: Vec2[] + | { position: Vec2, radius: number } + | { x1: number, y1: number, x2: number, y2: number } + | { x: number, y: number, w: number, h: number } + | { x: number, y: number, width: number, height: number } + ): boolean; + + /** + * Returns a new polygon representing the boolean union of `this` and the incoming `polygon` + */ + union(polygon: Polygon): Polygon; + + /** + * Returns a new polygon representing the boolean cut of `polygon` from `this` + */ + cut(polygon: Polygon): Polygon; + + /** + * Convert this polygon into an array of arrays (`[[x, y]]`) + */ + toArray(): number[][]; +} + +export = Polygon; diff --git a/types/polygon/polygon-tests.ts b/types/polygon/polygon-tests.ts new file mode 100644 index 0000000000..13ea7c08c1 --- /dev/null +++ b/types/polygon/polygon-tests.ts @@ -0,0 +1,16 @@ +// no tests yet +import Polygon = require('polygon'); + +const polygon1 = new Polygon([ + [0, 0], + [5, 0], + [5, 5], + [0, 5], + [0, 0], +]); +const shouldBeTrue = polygon1.contains({ + x: 3, + y: 3, + w: 4, + h: 3, +}); diff --git a/types/polygon/tsconfig.json b/types/polygon/tsconfig.json new file mode 100644 index 0000000000..516af96426 --- /dev/null +++ b/types/polygon/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "polygon-tests.ts" + ] +} diff --git a/types/polygon/tslint.json b/types/polygon/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/polygon/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/vec2/index.d.ts b/types/vec2/index.d.ts new file mode 100644 index 0000000000..e3b6623bb5 --- /dev/null +++ b/types/vec2/index.d.ts @@ -0,0 +1,191 @@ +// Type definitions for vec2 1.6 +// Project: https://github.com/tmpvar/vec2.js +// Definitions by: Konrad Klockgether +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * A generic library useful when you need to work with points/vectors in 2d space. + * **Stuff to Note**: most of the Vec2's methods take a `returnNew` as the last parameter. + * If passed a truthy value, a new vector will be returned to you. + * Otherwise the operation will be applied to `this` and `this` will be returned. + * Also, since `Infinity`and `NaN` are so insidious, this library will throw as soon as it detects either of these so you can take action to fix your data/algorithm. + */ +declare class Vec2 { + readonly x: number; + readonly y: number; + + constructor(xy: number[]); + constructor(x: number, y: number); + + /** + * Add an observer `fn` that will be called whenever this vector changes. Calling this method without a function causes it to notify observers. + * `fn` signature: `function(vec, prev) {}` - where `prev` is a clone of the vector before the last operation. + * this function returns the passed `fn` + */ + change(fn?: (vec: Vec2, prev: Vec2) => any): Vec2; + + /** + * Pass a `fn` to remove it from the observers list. Calling this function without a `fn` will remove all observers. + */ + ignore(fn?: (vec: Vec2, prev: Vec2) => any): Vec2; + + /** + * Sets the `x` and `y` coordinates of this vector. If `false` is passed for `notify`, none of the observers will be called. + */ + set(x: number, y: number, notify: boolean): Vec2; + + /** + * Sets the `x` and `y` of this vector to `0` + */ + zero(): Vec2; + + /** + * Returns a clone of this vector. + * _Note_: this does not clone observers + */ + zero(): Vec2; + + /** + * Negate the `x` and `y` coords of this vector. If `returnNew` is truthy, a new vector with the negated coordinates will be returned. + */ + negate(returnNew?: boolean): Vec2; + + /** + * Add the `x` and `y` to this vector's coordinates. + * If `returnNew` is truthy, return a new vector containing the resulting coordinates. Otherwise apply them to this vector and return it. + */ + add(x: number, y: number, returnNew?: boolean): Vec2; + add(vec2: number[] | Vec2, returnNew?: boolean): Vec2; + + subtract(x: number, y: number, returnNew?: boolean): Vec2; + subtract(vec2: Vec2 | number[], returnNew?: boolean): Vec2; + + /** + * Multiply this vectors components with the incoming, returning a clone if `returnNew` is truthy. + */ + multiply(x: number, y: number, returnNew?: boolean): Vec2; + multiply(scalarArrayVec2: number | number[] | Vec2, returnNew?: boolean): Vec2; + + /** + * Divide this vectors components by the incoming, returning a clone if `returnNew` is truthy. + * _note_: this method will throw if you attempt to divide by zero or pass values that cause NaNs + */ + divide(x: number, y: number, returnNew?: boolean): Vec2; + divide(scalarArrayVec2: number | number[] | Vec2, returnNew?: boolean): Vec2; + + /** + * Rotate this vector's cordinates around `(0,0)`. If `returnNew` is specified, a new `Vec2` will be created and populated with the result and returned. + * Otherwise the result is applied to this vector and `this` is returned. + * `inverse` - inverts the direction of the rotation + * `returnNew` - causes the result to be applied to a new `Vec2`, otherwise the result is applied to `this` + */ + rotate(radians: number, inverse?: number, returnNew?: boolean): Vec2; + + /** + * Returns the length of this vector from `(0,0)` + */ + length(): number; + + /** + * Returns the length of this vector prior to the `Math.sqrt` call. + * This is usefull when you don't need to know the actual distance, but need a normalized value to compare with another `Vec2#lengthSquared` or similar. + */ + lengthSquared(): number; + + /** + * _returns_: the distance between this vector and the incoming + */ + distance(vec2: Vec2): number; + + /** + * _returns_: closest vector in array to this vector. + */ + nearest(array: Vec2[]): Vec2; + + /** + * Normalizes this vector. If `returnNew` is truthy, a new vector populated with the normalized coordinates will be returned. + */ + normalize(returnNew?: boolean): Vec2; + + /** + * Returns true if the incoming coordinates are the same as this vector's + */ + equal(x: number, y: number): boolean; + equal(arrayVec2: number[] | Vec2): boolean; + + /** + * Return a `Vec2` that contains the absolute value of each of this vector's parts. + * If `returnNew` is truthy, create a new `Vec2` and return it. Otherwise apply the absolute values to to `this`. + */ + abs(returnNew?: boolean): Vec2; + + /** + * Return a `Vec2` consisting of the smallest values from this vector and the incoming + * When returnNew is truthy, a new `Vec2` will be returned otherwise the minimum values in either this or `vec` will be applied to this vector. + */ + min(vec: Vec2, returnNew?: boolean): Vec2; + + /** + * Return a `Vec2` consisting of the largest values from this vector and the incoming + * When returnNew is truthy, a new `Vec2` will be returned otherwise the maximum values in either `this` or `vec` will be applied to this vector. + */ + max(vec: Vec2, returnNew?: boolean): Vec2; + + /** + * Clamp the coordinates of this vector to the high/low of the incoming vec2s. If `returnNew` apply the result to the new vector and return. + * Otherwise apply to this vector. + */ + clamp(low: Vec2, high: Vec2, returnNew?: boolean): Vec2; + + /** + * + * Perform linear interpolation between this vector and the incoming. + * `amount` - the percentage along the path to place the vector + * `returnNew` - if `truthy`, apply the result to a new vector and return it, otherwise return `this` + */ + lerp(vec: Vec2, amount: number, returnNew?: boolean): Vec2; + + /** + * Returns a vector set with the `(-y,x)` coordinates of this vector. If `returnNew` a new vector is created and the operation is applied to the new vector. + */ + skew(returnNew?: boolean): Vec2; + + /** + * _returns_: `double` + */ + dot(): number; + + /** + * _returns_: `double` + */ + perpDot(): number; + + /** + * Returns the angle from this vector to the incoming. + */ + angleTo(vec: Vec2): number; + + /** + * Where `start` and `end` are vec2-like (e.g. `start.x` and `start.y`) + */ + isPointOnLine(start: Vec2, end: Vec2): boolean; + + /** + * _returns_: `[x, y]` + */ + toArray(): number[]; + + /** + * Applies the `[0]` to `this.x` and `[1]` to `this.y` + */ + fromArray(array: number[]): Vec2; + + toJSON(): { x: number, y: number }; + + /** + * _returns_: `'(x, y)'` + */ + toString(): string; +} + +export = Vec2; diff --git a/types/vec2/tsconfig.json b/types/vec2/tsconfig.json new file mode 100644 index 0000000000..ddd223e3be --- /dev/null +++ b/types/vec2/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "vec2-tests.ts" + ] +} diff --git a/types/vec2/tslint.json b/types/vec2/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/vec2/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/vec2/vec2-tests.ts b/types/vec2/vec2-tests.ts new file mode 100644 index 0000000000..384c364333 --- /dev/null +++ b/types/vec2/vec2-tests.ts @@ -0,0 +1,8 @@ +import Vec2 = require('vec2'); + +// some constructor tests +const instance = new Vec2([0, 1]); +const instanceFromArray = new Vec2(instance.toArray()); +const json = instanceFromArray.toJSON(); +const instanceFromJson = new Vec2(json.x, json.y); +const shouldBeTrue = instanceFromJson.equal(instance); From 4d87d9ce0ae63f1da34a761810fa6a17e3d46f63 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 20 Mar 2019 10:50:27 -0700 Subject: [PATCH 083/337] Remove test that fails on TS3.4 This is by design (TS #30215); previously Typescript incorrectly inferred `{}` but now gives an error. --- types/ramda/ramda-tests.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index fdac7648db..2d8b00ba6a 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -967,7 +967,8 @@ interface Obj { } const list: Book[] = [{id: "xyz", title: "A"}, {id: "abc", title: "B"}]; const a1 = R.indexBy(R.prop("id"), list); - const a2 = R.indexBy(R.prop("id"))(list); + // Typescript 3.3 incorrectly gives `a2: {}`, 3.4 gives an error instead. + // const a2 = R.indexBy(R.prop("id"))(list); const a3 = R.indexBy<{ id: string }>(R.prop("id"))(list); const a4 = R.indexBy(R.prop<"id", string>("id"))(list); const a5 = R.indexBy<{ id: string }>(R.prop<"id", string>("id"))(list); From 8179d9cb6d8c0d0d46afe6c403ea60c34fa7b238 Mon Sep 17 00:00:00 2001 From: Gordon Date: Wed, 20 Mar 2019 13:45:50 -0500 Subject: [PATCH 084/337] Fix incorrect connectHits exposed properties --- types/react-instantsearch-core/index.d.ts | 2 +- .../react-instantsearch-core-tests.tsx | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/types/react-instantsearch-core/index.d.ts b/types/react-instantsearch-core/index.d.ts index 0092feb370..ed0241ffad 100644 --- a/types/react-instantsearch-core/index.d.ts +++ b/types/react-instantsearch-core/index.d.ts @@ -333,7 +333,7 @@ interface HitsProvided { * https://community.algolia.com/react-instantsearch/connectors/connectHits.html */ // tslint:disable-next-line:no-unnecessary-generics -export function connectHits(stateless: React.StatelessComponent>): React.ComponentClass; +export function connectHits(stateless: React.StatelessComponent>): React.ComponentClass; export function connectHits, THit>(ctor: React.ComponentType): ConnectedComponentClass>; export function connectHitsPerPage(Composed: React.ComponentType): React.ComponentClass; diff --git a/types/react-instantsearch-core/react-instantsearch-core-tests.tsx b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx index 76cc26f2a4..3d0208707e 100644 --- a/types/react-instantsearch-core/react-instantsearch-core-tests.tsx +++ b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx @@ -408,12 +408,14 @@ import { } const ConnectedCustomHighlight2 = connectHighlight(CustomHighlight2); - connectHits(({ hits }) => ( + const ConnectedStatelessHits = connectHits(({ hits }) => (

)); + + ; }; // https://github.com/algolia/react-instantsearch/blob/master/examples/autocomplete/src/App-Mentions.js From 0f7add13ba328dabad5af4f841417fce64a96213 Mon Sep 17 00:00:00 2001 From: arunksan Date: Wed, 20 Mar 2019 13:23:59 -0700 Subject: [PATCH 085/337] @types/highcharts: dataLabels support Highcharts.ganttChart() --- types/highcharts/index.d.ts | 47 ++++++++++++++++++++++------------ types/highcharts/test/index.ts | 43 +++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 16 deletions(-) diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index b3900154cd..8001ab7884 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -5,6 +5,7 @@ // Albert Ozimek // Juliën Hanssens // Johns Gresham +// ArunkeshavaReddy Sankaramaddi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -4458,7 +4459,10 @@ declare namespace Highcharts { * @default 'Solid' */ dashStyle?: string; - dataLabels?: DataLabels; + /** + * Gantt charts use one or more data labels for each series, for showing multiple date periods. + */ + dataLabels?: DataLabels | DataLabels[]; /** * Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on * graphs and points. For large datasets it improves performance. @@ -5984,6 +5988,7 @@ declare namespace Highcharts { interface ColumnRangeChartSeriesOptions extends IndividualSeriesOptions, ColumnRangeChart { } interface ErrorBarChartSeriesOptions extends IndividualSeriesOptions, ErrorBarChart { } interface FunnelChartSeriesOptions extends IndividualSeriesOptions, FunnelChart { } + interface GanttChartSeriesOptions extends IndividualSeriesOptions, SeriesChart { } interface GaugeChartSeriesOptions extends IndividualSeriesOptions, GaugeChart { } interface HeatMapSeriesOptions extends IndividualSeriesOptions, HeatMapChart { } interface LineChartSeriesOptions extends IndividualSeriesOptions, LineChart { } @@ -6023,11 +6028,11 @@ declare namespace Highcharts { * The id of a series in the drilldown.series array to use for a drilldown for this point. * @since 3.0.8 */ - drilldown?: string; - /** - * The end value of the point. For gantt datetime axes, the end value is the timestamp in milliseconds since 1970. - */ - end?: number; + drilldown?: string; + /** + * The end value of the point. For gantt datetime axes, the end value is the timestamp in milliseconds since 1970. + */ + end?: number; /** * Individual point events */ @@ -6106,11 +6111,11 @@ declare namespace Highcharts { * Whether to display a slice offset from the center. * @default false */ - sliced?: boolean; - /** - * The start value of the point. For gantt datetime axes, the start value is the timestamp in milliseconds since 1970. - */ - start?: number; + sliced?: boolean; + /** + * The start value of the point. For gantt datetime axes, the start value is the timestamp in milliseconds since 1970. + */ + start?: number; /** * The value of the point, resulting in a relative area of the point in the treemap. */ @@ -6686,6 +6691,16 @@ declare namespace Highcharts { yAxis?: AxisOptions[] | AxisOptions; } + /** + * The Gantt chart uses different plot options than the base Highcharts chart Options. + */ + interface GanttOptions extends Options { + /** + * The specific Gantt Series to append the GanttChart. + */ + series?: GanttChartSeriesOptions[]; + } + interface GlobalOptions extends Options { /** * Global options that don't apply to each chart. These options, like the lang options, must be set using the @@ -7269,11 +7284,11 @@ declare namespace Highcharts { * As Highcharts.Chart, but without need for the new keyword. * @since 4.2.0 */ - chart(renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; - /** - * Highcharts ganttChart which doesn't require the new keyword. Required Highcharts Gantt module. - */ - ganttChart(renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; + chart(renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; + /** + * Highcharts ganttChart which doesn't require the new keyword. Required Highcharts Gantt module. + */ + ganttChart(renderTo: string | HTMLElement, options: GanttOptions, callback?: (chart: ChartObject) => void): ChartObject; /** * An array containing the current chart objects in the page. A chart's position in the array is preserved * throughout the page's lifetime. When a chart is destroyed, the array item becomes undefined. diff --git a/types/highcharts/test/index.ts b/types/highcharts/test/index.ts index 9ac03d1f81..358064b877 100644 --- a/types/highcharts/test/index.ts +++ b/types/highcharts/test/index.ts @@ -2886,3 +2886,46 @@ function test_GanttChart() { }], }); } + +// Tests DataLabels types for Highcharts.ganttChart, which uses the Gantt module +function test_GanttChartDataLabels() { + Highcharts.ganttChart('ganttChartContainer', { + xAxis: { + min: Date.UTC(2014, 9, 18), + max: Date.UTC(2014, 12, 20) + }, + series: [{ + name: 'Project 1', + data: [ + { + name: 'Lemon Tea', + start: Date.UTC(2014, 10, 18), + end: Date.UTC(2014, 11, 20) + }, + { + name: 'Stapler', + start: Date.UTC(2014, 11, 18), + end: Date.UTC(2014, 12, 20) + }, + { + name: 'Sierra', + start: Date.UTC(2014, 12, 18), + end: Date.UTC(2014, 12, 20) + }, + ], + dataLabels: [{ + enabled: true, + format: 'Data Label Left', + useHTML: true, + align: 'left', + allowOverlap: true, + }, { + enabled: true, + format: 'Data Label Right', + useHTML: true, + align: 'right', + allowOverlap: true, + }] + }], + }); +} From 4d0f36a90408ea95b88d3e1ef5e782d495ddd3c2 Mon Sep 17 00:00:00 2001 From: Grant Timmerman Date: Wed, 20 Mar 2019 13:38:05 -0700 Subject: [PATCH 086/337] Revert "[@types/google-apps-script] Remove the unnecessary console declaration" --- types/google-apps-script/google-apps-script.base.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/google-apps-script/google-apps-script.base.d.ts b/types/google-apps-script/google-apps-script.base.d.ts index 5c2a8d9155..be1bad95d5 100644 --- a/types/google-apps-script/google-apps-script.base.d.ts +++ b/types/google-apps-script/google-apps-script.base.d.ts @@ -326,3 +326,4 @@ declare var Logger: GoogleAppsScript.Base.Logger; // conflicts with MimeType in lib.d.ts // declare var MimeType: GoogleAppsScript.Base.MimeType; declare var Session: GoogleAppsScript.Base.Session; +declare var console: GoogleAppsScript.Base.console; From 10cdba22e19514b23035d929af1a17afd97313b6 Mon Sep 17 00:00:00 2001 From: Damien Sorel Date: Wed, 20 Mar 2019 22:38:06 +0100 Subject: [PATCH 087/337] Update tsconfig.json --- types/wordpress__jest-console/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/wordpress__jest-console/tsconfig.json b/types/wordpress__jest-console/tsconfig.json index f21c4b6ce7..429b3c1488 100644 --- a/types/wordpress__jest-console/tsconfig.json +++ b/types/wordpress__jest-console/tsconfig.json @@ -19,6 +19,6 @@ }, "files": [ "index.d.ts", - "jest-console-tests.ts" + "wordpress__jest-console-tests.ts" ] } From 3780fcc54da727c710f1e027b3fc98a29ce68072 Mon Sep 17 00:00:00 2001 From: Ben James Date: Wed, 20 Mar 2019 22:43:41 +0000 Subject: [PATCH 088/337] Add @google-cloud/text-to-speech definitions --- .../google-cloud__text-to-speech-tests.ts | 56 ++++++++ types/google-cloud__text-to-speech/index.d.ts | 123 ++++++++++++++++++ .../tsconfig.json | 19 +++ .../google-cloud__text-to-speech/tslint.json | 1 + 4 files changed, 199 insertions(+) create mode 100644 types/google-cloud__text-to-speech/google-cloud__text-to-speech-tests.ts create mode 100644 types/google-cloud__text-to-speech/index.d.ts create mode 100644 types/google-cloud__text-to-speech/tsconfig.json create mode 100644 types/google-cloud__text-to-speech/tslint.json diff --git a/types/google-cloud__text-to-speech/google-cloud__text-to-speech-tests.ts b/types/google-cloud__text-to-speech/google-cloud__text-to-speech-tests.ts new file mode 100644 index 0000000000..79c368c8e3 --- /dev/null +++ b/types/google-cloud__text-to-speech/google-cloud__text-to-speech-tests.ts @@ -0,0 +1,56 @@ +import textToSpeech from "@google-cloud/text-to-speech"; + +const client = new textToSpeech.TextToSpeechClient({}); + +/* listVoices */ + +client.listVoices({}); + +client.listVoices({}, (err, res) => { + if (res) { + res.map(voice => + console.log( + voice.language_codes, + voice.name, + voice.naturalSampleRateHertz, + voice.ssmlGender + ) + ); + } +}); + +client.listVoices({ languageCode: "en-GB" }).then(res => { + res[0].map(voice => + console.log( + voice.language_codes, + voice.name, + voice.naturalSampleRateHertz, + voice.ssmlGender + ) + ); +}); + +/* synthesizeSpeech */ + +client.synthesizeSpeech( + { + input: { text: "Hello world." }, + audioConfig: { audioEncoding: "MP3" }, + voice: { name: "Alice" } + }, + (err, res) => { + if (res) { + console.log(res.audioContent); + } + } +); + +client + .synthesizeSpeech({ + input: { ssml: "Hello world." }, + audioConfig: { audioEncoding: "OGG_OPUS" }, + voice: { name: "Bob", languageCode: "en-GB" } + }) + .then(res => { + console.log(res[0].audioContent); + }); diff --git a/types/google-cloud__text-to-speech/index.d.ts b/types/google-cloud__text-to-speech/index.d.ts new file mode 100644 index 0000000000..9e0c80cac2 --- /dev/null +++ b/types/google-cloud__text-to-speech/index.d.ts @@ -0,0 +1,123 @@ +// Type definitions for google-cloud__text-to-speech 0.5 +// Project: https://github.com/googleapis/nodejs-text-to-speech +// Definitions by: Ben James +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.8 + +/// + +export type GoogleError = any; + +export type APICallback = ( + err: GoogleError | null, + response?: T +) => void; + +export interface PromiseLike extends Promise { + /** + * Cancel the ongoing promise + */ + cancel(): void; +} + +export interface MethodOverload { + (data: T, options?: CallOptions): PromiseLike<[R]>; + (data: T, options: CallOptions, callback: APICallback): void; + (data: T, callback: APICallback): void; +} + +export interface CallOptions { + timeout?: number; + retry?: any; + autoPaginate?: boolean; + pageToken?: any; + isBundling: boolean; + longrunning?: any; + promise?: any; +} + +export interface ClientOptionsCredentials { + client_email: string; + private_key: string; +} + +export interface ClientOptions { + credentials?: ClientOptionsCredentials; + email?: string; + keyFilename?: string; + port?: number; + projectId?: string; + promise?: any; + servicePath?: string; +} + +export interface ListVoicesRequest { + languageCode?: string; +} + +export type ListVoicesOptions = CallOptions; + +export type SsmlVoiceGender = + | "SSML_VOICE_GENDER_UNSPECIFIED" + | "MALE" + | "FEMALE" + | "NEUTRAL"; + +export interface Voice { + language_codes: string[]; + name: string; + ssmlGender: SsmlVoiceGender; + naturalSampleRateHertz: number; +} + +export type ListVoicesResponse = Voice[]; + +export type SynthesisInput = { text: string } | { ssml: string }; + +export interface VoiceSelectionParams { + languageCode?: string; + name?: string; + ssmlGender?: SsmlVoiceGender; +} + +export type AudioEncoding = + | "AUDIO_ENCODING_UNSPECIFIED" + | "LINEAR16" + | "MP3" + | "OGG_OPUS"; + +export interface AudioConfig { + audioEncoding: AudioEncoding; + effectsProfileId?: string[]; + pitch?: number; + sampleRateHertz?: number; + speakingRate?: number; + volumeGainDb?: number; +} + +export interface SynthesizeSpeechRequest { + input: SynthesisInput; + voice: VoiceSelectionParams; + audioConfig: AudioConfig; +} + +export type SynthesizeSpeechOptions = CallOptions; + +export interface SynthesizeSpeechResponse { + audioContent: Buffer; +} + +declare class TextToSpeechClient { + constructor(options?: ClientOptions); + + listVoices: MethodOverload; + synthesizeSpeech: MethodOverload< + SynthesizeSpeechRequest, + SynthesizeSpeechResponse + >; +} + +declare const TextToSpeech: { TextToSpeechClient: typeof TextToSpeechClient }; + +export default TextToSpeech; diff --git a/types/google-cloud__text-to-speech/tsconfig.json b/types/google-cloud__text-to-speech/tsconfig.json new file mode 100644 index 0000000000..a682d930a1 --- /dev/null +++ b/types/google-cloud__text-to-speech/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@google-cloud/text-to-speech": ["google-cloud__text-to-speech"] + } + }, + "files": ["index.d.ts", "google-cloud__text-to-speech-tests.ts"] +} diff --git a/types/google-cloud__text-to-speech/tslint.json b/types/google-cloud__text-to-speech/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/google-cloud__text-to-speech/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From e9b97bdc546aafd6069a68a87897686d1d342b35 Mon Sep 17 00:00:00 2001 From: James Garbutt <43081j@users.noreply.github.com> Date: Wed, 20 Mar 2019 22:44:28 +0000 Subject: [PATCH 089/337] stylelint: correct several interfaces (#33666) * stylelint: correct several interfaces * stylelint: add rule tester * stylelint: introduce plugin type * stylelint: remove rule option * stylelint: bump major version * stylelint: compromise and match latest SL version --- types/stylelint/index.d.ts | 125 ++++++++++++++++++++++------- types/stylelint/package.json | 6 ++ types/stylelint/stylelint-tests.ts | 43 ++++++++-- 3 files changed, 141 insertions(+), 33 deletions(-) create mode 100644 types/stylelint/package.json diff --git a/types/stylelint/index.d.ts b/types/stylelint/index.d.ts index 7d1f0fccc4..adf5057a07 100644 --- a/types/stylelint/index.d.ts +++ b/types/stylelint/index.d.ts @@ -1,37 +1,56 @@ -// Type definitions for stylelint 9.4 +// Type definitions for stylelint 9.10 // Project: https://github.com/stylelint/stylelint, https://stylelint.io // Definitions by: Alan Agius // Filips Alpe +// James Garbutt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -export type FormatterType = "json" | "string" | "verbose" | "compact"; +import * as postcss from 'postcss'; -export type SyntaxType = "scss" | "sass" | "less" | "sugarss"; +export type FormatterType = "json" | "string" | "verbose" | "compact" | "unix"; + +export type SyntaxType = "css-in-js" + | "html" + | "less" + | "markdown" + | "sass" + | "scss" + | "sugarss"; + +export interface Configuration { + rules: Record; + extends: string | string[]; + plugins: string[]; + processors: string[]; + ignoreFiles: string|string[]; + defaultSeverity: "warning"|"error"; +} export interface LinterOptions { - code?: string; - codeFilename?: string; - config?: JSON; - configBasedir?: string; - configFile?: string; - configOverrides?: JSON; - cache?: boolean; - cacheLocation?: string; - files?: string | string[]; - fix?: boolean; - formatter?: FormatterType; - ignoreDisables?: boolean; - reportNeedlessDisables?: boolean; - ignorePath?: boolean; - syntax?: SyntaxType; - customSyntax?: string; + cache: boolean; + cacheLocation: string; + code: string; + codeFilename: string; + config: Partial; + configBasedir: string; + configFile: string; + configOverrides: Partial; + customSyntax: string; + disableDefaultIgnores: boolean; + files: string | string[]; + fix: boolean; + formatter: FormatterType; + ignoreDisables: boolean; + ignorePath: string; + maxWarnings: number; + reportNeedlessDisables: boolean; + syntax: SyntaxType; } export interface LinterResult { errored: boolean; output: string; - postcssResults: any[]; results: LintResult[]; } @@ -49,11 +68,12 @@ export namespace formatters { function string(results: LintResult[]): string; function compact(results: LintResult[]): string; function verbose(results: LintResult[]): string; + function unix(results: LintResult[]): string; } -export function lint(options?: LinterOptions): Promise; +export function lint(options?: Partial): Promise; -export type RuleOption = { +export type ValidateOptionsAssertion = { actual: any; possible?: any; optional?: false; @@ -63,25 +83,74 @@ export type RuleOption = { optional: true; }; +export type RuleMessageValue = string | ((...args: any[]) => string); + export namespace utils { function report(violation: { ruleName: string; - result: LintResult; + result: postcss.Result; message: string; - node: any; + node: postcss.Node; index?: number; word?: string; line?: number; }): void; - function ruleMessages(ruleName: string, messages: { [key: string]: any; }): typeof messages; + function ruleMessages( + ruleName: string, + messages: T): T; - function validateOptions(result: LintResult, ruleName: string, ...options: RuleOption[]): boolean; + function validateOptions(result: postcss.Result, ruleName: string, + ...options: ValidateOptionsAssertion[]): boolean; - function checkAgainstRule(options: { ruleName: string; ruleSettings: any; root: any; }, callback: (warning: string) => void): void; + function checkAgainstRule(options: { + ruleName: string; + ruleSettings: any; + root: any; + }, callback: (warning: string) => void): void; } +export type Plugin = (primaryOption: any, secondaryOptions?: object) => + (root: postcss.Root, result: postcss.Result) => void|PromiseLike; + export function createPlugin( ruleName: string, - plugin: (options: RuleOption[]) => (root: any, result: LintResult) => void, + plugin: Plugin ): any; + +export interface RuleTesterResult { + expected: number; + actual: number; + description: string; +} + +export interface RuleTesterTest { + code: string; + description?: string; +} + +export interface RuleTesterTestRejected extends RuleTesterTest { + line?: number; + column?: number; + only?: boolean; + message?: string; +} + +export interface RuleTesterSchema { + ruleName: string; + syntax?: SyntaxType; + config?: any; + accept?: RuleTesterTest[]; + reject?: RuleTesterTestRejected[]; +} + +export interface RuleTesterContext { + comparisonCount: number; + completeAssertionDescription: string; + caseDescription: string; + only?: boolean; +} + +export function createRuleTester( + fn: (result: Promise, context: RuleTesterContext) => void +): (rule: Plugin, schema: RuleTesterSchema) => void; diff --git a/types/stylelint/package.json b/types/stylelint/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/stylelint/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/stylelint/stylelint-tests.ts b/types/stylelint/stylelint-tests.ts index e51d2eb643..fc3dc0e5fd 100644 --- a/types/stylelint/stylelint-tests.ts +++ b/types/stylelint/stylelint-tests.ts @@ -1,6 +1,19 @@ -import { LinterOptions, FormatterType, SyntaxType, lint, LintResult, LinterResult, createPlugin, utils } from "stylelint"; +import { + LinterOptions, + FormatterType, + SyntaxType, + lint, + LintResult, + LinterResult, + createPlugin, + utils, + createRuleTester, + RuleTesterContext, + RuleTesterResult, + Plugin +} from "stylelint"; -const options: LinterOptions = { +const options: Partial = { code: "div { color: red }", files: ["**/**.scss"], formatter: "json", @@ -8,14 +21,13 @@ const options: LinterOptions = { cacheLocation: "./stylelint.cache.json", ignoreDisables: true, reportNeedlessDisables: true, - ignorePath: true, + ignorePath: 'foo', syntax: "scss" }; lint(options).then((x: LinterResult) => { const err: boolean = x.errored; const output: string = x.output; - const postcssResults: any[] = x.postcssResults; const results: LintResult[] = x.results; }); @@ -29,7 +41,7 @@ const messages = utils.ruleMessages(ruleName, { warning: (reason: string) => `This is not allowed because ${reason}`, }); -createPlugin(ruleName, options => { +const testPlugin: Plugin = (options) => { return (root, result) => { const validOptions = utils.validateOptions(result, ruleName, { actual: options }); if (!validOptions) { @@ -52,4 +64,25 @@ createPlugin(ruleName, options => { }); }); }; +}; + +createPlugin(ruleName, testPlugin); + +const tester = createRuleTester( + (result: Promise, context: RuleTesterContext) => { + return; + } +); + +tester(testPlugin, { + ruleName: 'foo', + config: [true, 1], + accept: [ + { code: 'test' }, + { code: 'test2', description: 'testing' } + ], + reject: [ + { code: 'testreject', line: 1, column: 1 }, + { code: 'test2reject', message: 'x', line: 1, column: 1 } + ] }); From 574bd2a385fa44d98fb3bd8904f64154dd145afe Mon Sep 17 00:00:00 2001 From: Muhammet Ozturk Date: Thu, 21 Mar 2019 03:59:02 +0300 Subject: [PATCH 090/337] pako type definition fixing --- types/pako/index.d.ts | 224 +++++++++++++++++++++++++-------------- types/pako/pako-tests.ts | 19 ++-- types/pako/tslint.json | 75 +------------ 3 files changed, 153 insertions(+), 165 deletions(-) diff --git a/types/pako/index.d.ts b/types/pako/index.d.ts index 7f9b31f2b9..e6299ac88c 100644 --- a/types/pako/index.d.ts +++ b/types/pako/index.d.ts @@ -1,84 +1,148 @@ -// Type definitions for pako 1.0.4 +// Type definitions for pako 1.0 // Project: https://github.com/nodeca/pako -// Definitions by: Denis Cappellin , Caleb Eggensperger +// Definitions by: Denis Cappellin , +// Caleb Eggensperger , +// Muhammet Öztürk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = Pako; -export as namespace pako; - -declare namespace Pako { - export interface DeflateOptions { - level?: number; - windowBits?: number; - memLevel?: number; - strategy?: number; - dictionary?: any; - raw?: boolean; - to?: 'string'; - } - - export interface InflateOptions { - windowBits?: number; - raw?: boolean; - to?: 'string'; - } - - export type Data = Uint8Array | Array | string; - - /** - * Compress data with deflate algorithm and options. - */ - export function deflate( data: Data, options: DeflateOptions & {to: 'string'} ): string; - export function deflate( data: Data, options?: DeflateOptions ): Uint8Array; - - /** - * The same as deflate, but creates raw data, without wrapper (header and adler32 crc). - */ - export function deflateRaw( data: Data, options: DeflateOptions & {to: 'string'} ): string; - export function deflateRaw( data: Data, options?: DeflateOptions ): Uint8Array; - - /** - * The same as deflate, but create gzip wrapper instead of deflate one. - */ - export function gzip( data: Data, options: DeflateOptions & {to: 'string'} ): string; - export function gzip( data: Data, options?: DeflateOptions ): Uint8Array; - - /** - * Decompress data with inflate/ungzip and options. Autodetect format via wrapper header - * by default. That's why we don't provide separate ungzip method. - */ - export function inflate( data: Data, options: InflateOptions & {to: 'string'} ): string; - export function inflate( data: Data, options?: InflateOptions ): Uint8Array; - - /** - * The same as inflate, but creates raw data, without wrapper (header and adler32 crc). - */ - export function inflateRaw( data: Data, options: InflateOptions & {to: 'string'} ): string; - export function inflateRaw( data: Data, options?: InflateOptions ): Uint8Array; - - /** - * Just shortcut to inflate, because it autodetects format by header.content. Done for convenience. - */ - export function ungzip( data: Data, options: InflateOptions & {to: 'string'} ): string; - export function ungzip( data: Data, options?: InflateOptions ): Uint8Array; - - export class Deflate { - constructor( options?: DeflateOptions ); - err: number; - msg: string; - result: Uint8Array | Array; - onData( chunk: Data ): void; - onEnd( status: number ): void; - push( data: Data | ArrayBuffer, mode?: number | boolean ): boolean; - } - - export class Inflate { - constructor( options?: InflateOptions ); - err: number; - msg: string; - result: Data; - onData( chunk: Data ): void; - onEnd( status: number ): void; - push( data: Data | ArrayBuffer, mode?: number | boolean ): boolean; - } +export enum FlushValues { + Z_NO_FLUSH = 0, + Z_PARTIAL_FLUSH = 1, + Z_SYNC_FLUSH = 2, + Z_FULL_FLUSH = 3, + Z_FINISH = 4, + Z_BLOCK = 5, + Z_TREES = 6, +} + +export enum StrategyValues { + Z_FILTERED = 1, + Z_HUFFMAN_ONLY = 2, + Z_RLE = 3, + Z_FIXED = 4, + Z_DEFAULT_STRATEGY = 0, +} + +export enum ReturnCodes { + Z_OK = 0, + Z_STREAM_END = 1, + Z_NEED_DICT = 2, + Z_ERRNO = -1, + Z_STREAM_ERROR = -2, + Z_DATA_ERROR = -3, + Z_BUF_ERROR = -5, +} + +export interface DeflateOptions { + level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + windowBits?: number; + memLevel?: number; + strategy?: StrategyValues; + dictionary?: any; + raw?: boolean; + to?: 'string'; + chunkSize?: number; + gzip?: boolean; + header?: Header; +} + +export interface DeflateFunctionOptions { + level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + windowBits?: number; + memLevel?: number; + strategy?: StrategyValues; + dictionary?: any; + raw?: boolean; + to?: 'string'; +} + +export interface InflateOptions { + windowBits?: number; + dictionary?: any; + raw?: boolean; + to?: 'string'; + chunkSize?: number; +} + +export interface InflateFunctionOptions { + windowBits?: number; + raw?: boolean; + to?: 'string'; +} + +export interface Header { + text?: boolean; + time?: number; + os?: number; + extra?: number[]; + name?: string; + comment?: string; + hcrc?: boolean; +} + +export type Data = Uint8Array | number[] | string; + +/** + * Compress data with deflate algorithm and options. + */ +export function deflate(data: Data, options: DeflateFunctionOptions & { to: 'string' }): string; +export function deflate(data: Data, options?: DeflateFunctionOptions): Uint8Array; + +/** + * The same as deflate, but creates raw data, without wrapper (header and adler32 crc). + */ +export function deflateRaw(data: Data, options: DeflateFunctionOptions & { to: 'string' }): string; +export function deflateRaw(data: Data, options?: DeflateFunctionOptions): Uint8Array; + +/** + * The same as deflate, but create gzip wrapper instead of deflate one. + */ +export function gzip(data: Data, options: DeflateFunctionOptions & { to: 'string' }): string; +export function gzip(data: Data, options?: DeflateFunctionOptions): Uint8Array; + +/** + * Decompress data with inflate/ungzip and options. Autodetect format via wrapper header + * by default. That's why we don't provide separate ungzip method. + */ +export function inflate(data: Data, options: InflateFunctionOptions & { to: 'string' }): string; +export function inflate(data: Data, options?: InflateFunctionOptions): Uint8Array; + +/** + * The same as inflate, but creates raw data, without wrapper (header and adler32 crc). + */ +export function inflateRaw(data: Data, options: InflateFunctionOptions & { to: 'string' }): string; +export function inflateRaw(data: Data, options?: InflateFunctionOptions): Uint8Array; + +/** + * Just shortcut to inflate, because it autodetects format by header.content. Done for convenience. + */ +export function ungzip(data: Data, options: InflateFunctionOptions & { to: 'string' }): string; +export function ungzip(data: Data, options?: InflateFunctionOptions): Uint8Array; + +export class Deflate { + constructor(options?: DeflateOptions); + + err: ReturnCodes; + msg: string; + result: Uint8Array | number[]; + + onData(chunk: Data): void; + + onEnd(status: number): void; + + push(data: Data | ArrayBuffer, mode?: FlushValues | boolean): boolean; +} + +export class Inflate { + constructor(options?: InflateOptions); + + err: ReturnCodes; + msg: string; + result: Data; + + onData(chunk: Data): void; + + onEnd(status: number): void; + + push(data: Data | ArrayBuffer, mode?: FlushValues | boolean): boolean; } diff --git a/types/pako/pako-tests.ts b/types/pako/pako-tests.ts index 5e5a6c3eef..9caa562e53 100644 --- a/types/pako/pako-tests.ts +++ b/types/pako/pako-tests.ts @@ -1,24 +1,21 @@ - - import pako = require("pako"); -var chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9]) -var chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]); +const chunk1 = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]); +const chunk2 = new Uint8Array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); -var deflate = new pako.Deflate({ level: 3 }); +const deflate = new pako.Deflate({level: 3}); deflate.push(chunk1, false); deflate.push(chunk2, true); // true -> last chunk if (deflate.err) { - throw new Error( deflate.err.toString() ); + throw new Error(deflate.err.toString()); } console.log(deflate.result); -let str: string = pako.deflate('1234', {to: 'string'}); -let arr: Uint8Array = pako.deflate('1234'); - -let str2: string = pako.inflate('1234', {to: 'string'}); -let arr2: Uint8Array = pako.inflate('1234'); +const str: string = pako.deflate('1234', {to: 'string'}); +const arr: Uint8Array = pako.deflate('1234'); +const str2: string = pako.inflate('1234', {to: 'string'}); +const arr2: Uint8Array = pako.inflate('1234'); diff --git a/types/pako/tslint.json b/types/pako/tslint.json index a41bf5d19a..2ff396e742 100644 --- a/types/pako/tslint.json +++ b/types/pako/tslint.json @@ -1,79 +1,6 @@ { "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 + } } From 9170ffffe50b903d593d8c9ac9c0c55e34dab212 Mon Sep 17 00:00:00 2001 From: Muhammet Ozturk Date: Thu, 21 Mar 2019 04:03:28 +0300 Subject: [PATCH 091/337] delete spaces --- types/pako/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/pako/index.d.ts b/types/pako/index.d.ts index e6299ac88c..26cc24a25c 100644 --- a/types/pako/index.d.ts +++ b/types/pako/index.d.ts @@ -1,7 +1,7 @@ // Type definitions for pako 1.0 // Project: https://github.com/nodeca/pako -// Definitions by: Denis Cappellin , -// Caleb Eggensperger , +// Definitions by: Denis Cappellin +// Caleb Eggensperger // Muhammet Öztürk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 317302647c25f772f61770c060c3941e3bcec04e Mon Sep 17 00:00:00 2001 From: Scott Beca Date: Thu, 21 Mar 2019 12:36:46 +1100 Subject: [PATCH 092/337] Update type definitions for react-inlinesvg to match v0.8.4 --- types/react-inlinesvg/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react-inlinesvg/index.d.ts b/types/react-inlinesvg/index.d.ts index e8e1f4095b..2dde329572 100644 --- a/types/react-inlinesvg/index.d.ts +++ b/types/react-inlinesvg/index.d.ts @@ -31,6 +31,7 @@ export interface Props { uniquifyIDs?: boolean; onError?(error: RequestError | InlineSVGError): void; onLoad?(src: URL | string, isCached: boolean): void; + processSVG?(svgText: string): string; supportTest?(): void; wrapper?(): ReactNode; } From 1e38dbd503c11d4d0ceba7da1a3812dc7cdb449e Mon Sep 17 00:00:00 2001 From: breeze9527 Date: Thu, 21 Mar 2019 10:16:51 +0800 Subject: [PATCH 093/337] [amap-js-api] Add comments --- types/amap-js-api/array-bounds.d.ts | 5 + types/amap-js-api/bounds.d.ts | 27 ++ types/amap-js-api/browser.d.ts | 141 ++++++++ types/amap-js-api/common.d.ts | 9 + types/amap-js-api/convert-from.d.ts | 12 + types/amap-js-api/dom-util.d.ts | 69 +++- types/amap-js-api/event.d.ts | 57 ++- types/amap-js-api/geometry-util.d.ts | 118 ++++-- types/amap-js-api/layer/building.d.ts | 24 ++ types/amap-js-api/layer/flexible.d.ts | 18 + types/amap-js-api/layer/layer.d.ts | 36 ++ types/amap-js-api/layer/layerGroup.d.ts | 37 +- types/amap-js-api/layer/massMarks.d.ts | 52 +++ types/amap-js-api/layer/mediaLayer.d.ts | 59 +++ types/amap-js-api/layer/tileLayer.d.ts | 54 +++ types/amap-js-api/layer/wms.d.ts | 27 ++ types/amap-js-api/layer/wmts.d.ts | 27 ++ types/amap-js-api/lngLat.d.ts | 28 ++ types/amap-js-api/map.d.ts | 381 ++++++++++++++++++++ types/amap-js-api/overlay/bezierCurve.d.ts | 15 +- types/amap-js-api/overlay/circle.d.ts | 35 ++ types/amap-js-api/overlay/circleMarker.d.ts | 3 + types/amap-js-api/overlay/contextMenu.d.ts | 29 +- types/amap-js-api/overlay/ellipse.d.ts | 22 ++ types/amap-js-api/overlay/geoJSON.d.ts | 29 ++ types/amap-js-api/overlay/icon.d.ts | 23 ++ types/amap-js-api/overlay/infoWindow.d.ts | 61 ++++ types/amap-js-api/overlay/marker.d.ts | 194 +++++++++- types/amap-js-api/overlay/markerShape.d.ts | 4 + types/amap-js-api/overlay/overlay.d.ts | 38 ++ types/amap-js-api/overlay/overlayGroup.d.ts | 54 ++- types/amap-js-api/overlay/pathOverlay.d.ts | 30 ++ types/amap-js-api/overlay/polygon.d.ts | 46 +++ types/amap-js-api/overlay/polyline.d.ts | 73 ++++ types/amap-js-api/overlay/rectangle.d.ts | 22 ++ types/amap-js-api/overlay/shapeOverlay.d.ts | 50 +++ types/amap-js-api/overlay/text.d.ts | 22 ++ types/amap-js-api/pixel.d.ts | 19 + types/amap-js-api/size.d.ts | 15 + types/amap-js-api/util.d.ts | 59 ++- types/amap-js-api/view2D.d.ts | 16 + 41 files changed, 1982 insertions(+), 58 deletions(-) diff --git a/types/amap-js-api/array-bounds.d.ts b/types/amap-js-api/array-bounds.d.ts index 419d8e4b1d..3e0145e049 100644 --- a/types/amap-js-api/array-bounds.d.ts +++ b/types/amap-js-api/array-bounds.d.ts @@ -2,7 +2,12 @@ declare namespace AMap { class ArrayBounds { constructor(bounds: LocationValue[]); bounds: LngLat[]; + /** + * 判断传入的点是否在ArrayBounds内 + * @param point 目标点 + */ contains(point: LocationValue): boolean; + // internal toBounds(): Bounds; getCenter(): LngLat; diff --git a/types/amap-js-api/bounds.d.ts b/types/amap-js-api/bounds.d.ts index 63e880fe65..f594969292 100644 --- a/types/amap-js-api/bounds.d.ts +++ b/types/amap-js-api/bounds.d.ts @@ -1,12 +1,39 @@ declare namespace AMap { class Bounds { + /** + * 地物对象的经纬度矩形范围。 + * @param southWest 西南角经纬度 + * @param northEast 东北角经纬度 + */ constructor(southWest: LngLat, northEast: LngLat); + /** + * 指定点坐标是否在矩形范围内 + * @param point 制定坐标 + */ contains(point: LocationValue): boolean; + /** + * 获取当前Bounds的中心点经纬度坐标 + */ getCenter(): LngLat; + /** + * 获取西南角坐标 + */ getSouthWest(): LngLat; + /** + * 获取东南角坐标 + */ getSouthEast(): LngLat; + /** + * 获取东北角坐标 + */ getNorthEast(): LngLat; + /** + * 获取西北角坐标 + */ getNorthWest(): LngLat; + /** + * 以字符串形式返回地物对象的矩形范围 + */ toString(): string; } } diff --git a/types/amap-js-api/browser.d.ts b/types/amap-js-api/browser.d.ts index 71bfaa8fea..26b3956aa1 100644 --- a/types/amap-js-api/browser.d.ts +++ b/types/amap-js-api/browser.d.ts @@ -1,51 +1,192 @@ declare namespace AMap { namespace Browser { + /** + * 当前浏览器userAgent + */ const ua: string; + /** + * 是否移动设备 + */ const mobile: boolean; + /** + * 平台类型,如:'windows'、'mac'、'ios'、'android'、'other' + */ const plat: 'android' | 'ios' | 'windows' | 'mac' | 'other'; + /** + * 是否mac设备 + */ const mac: boolean; + /** + * 是否windows设备 + */ const windows: boolean; + /** + * 是否iOS设备 + */ const ios: boolean; + /** + * 是否iPad + */ const iPad: boolean; + /** + * 是否iPhone + */ const iPhone: boolean; + /** + * 是否安卓设备 + */ const android: boolean; + /** + * 是否安卓4以下系统 + */ const android23: boolean; + /** + * 是否Chrome浏览器 + */ const chrome: boolean; + /** + * 是否火狐浏览器 + */ const firefox: boolean; + /** + * 是否Safari浏览器 + */ const safari: boolean; + /** + * 是否微信 + */ const wechat: boolean; + /** + * 是否UC浏览器 + */ const uc: boolean; + /** + * 是否QQ或者QQ浏览器 + */ const qq: boolean; + /** + * 是否IE + */ const ie: boolean; + /** + * 是否IE6 + */ const ie6: boolean; + /** + * 是否IE7 + */ const ie7: boolean; + /** + * 是否IE8 + */ const ie8: boolean; + /** + * 是否IE9 + */ const ie9: boolean; + /** + * 是否IE10 + */ const ie10: boolean; + /** + * 是否IE11 + */ const ie11: boolean; + /** + * 是否Edge浏览器 + */ const edge: boolean; + /** + * 是否IE9以下 + */ const ielt9: boolean; + /** + * 是否百度浏览器 + */ const baidu: boolean; + /** + * 是否支持LocaStorage + */ const isLocalStorage: boolean; + /** + * 是否支持Geolocation + */ const isGeolocation: boolean; + /** + * 是否Webkit移动浏览器 + */ const mobileWebkit: boolean; + /** + * 是否支持Css3D的Webkit移动端浏览器 + */ const mobileWebkit3d: boolean; + /** + * 是否Opera移动浏览器 + */ const mobileOpera: boolean; + /** + * 是否高清屏幕,devicePixelRatio>1 + */ const retina: boolean; + /** + * 是否触屏 + */ const touch: boolean; + /** + * 是否msPointer设备 + */ const msPointer: boolean; + /** + * 是否pointer设备 + */ const pointer: boolean; + /** + * 是否webkit浏览器 + */ const webkit: boolean; + /** + * 是否支持Css3D的ie浏览器 + */ const ie3d: boolean; + /** + * 是否支持Css3D的Webkit浏览器 + */ const webkit3d: boolean; + /** + * 是否支持Css3D的gecko浏览器 + */ const gecko3d: boolean; + /** + * 是否支持Css3D的opera浏览器 + */ const opera3d: boolean; + /** + * 是否支持Css3D的浏览器 + */ const any3d: boolean; + /** + * 是否支持canvas + */ const isCanvas: boolean; + /** + * 是否支持svg + */ const isSvg: boolean; + /** + * 是否支持vml + */ const isVML: boolean; + /** + * 是否支持WebWorker + */ const isWorker: boolean; + /** + * 是否支持WebSocket + */ const isWebsocket: boolean; + /** + * 判断是否支持webgl + */ function isWebGL(): boolean; } } diff --git a/types/amap-js-api/common.d.ts b/types/amap-js-api/common.d.ts index 3d51dc719e..8b442ad0a3 100644 --- a/types/amap-js-api/common.d.ts +++ b/types/amap-js-api/common.d.ts @@ -9,8 +9,17 @@ declare namespace AMap { : V extends undefined ? {} : { value: V }); type MapsEvent = Event; diff --git a/types/amap-js-api/convert-from.d.ts b/types/amap-js-api/convert-from.d.ts index 9fe1f1e76d..61f83f9b94 100644 --- a/types/amap-js-api/convert-from.d.ts +++ b/types/amap-js-api/convert-from.d.ts @@ -1,12 +1,24 @@ declare namespace AMap { namespace convertFrom { interface Result { + /** + * 成功状态文字描述 + */ info: string; // 'ok' + /** + * 高德坐标集合 + */ locations: LngLat[]; } type Type = 'gps' | 'baidu' | 'mapbar'; type SearchStatus = 'complete' | 'error'; } + /** + * 为坐标转换类,支持将其他坐标系的坐标点转换为高德坐标系。 + * @param lnglat 待转换坐标 + * @param type 用于说明是哪个服务商的坐标 + * @param callback 转换完成后的回调函数 + */ function convertFrom( lnglat: LocationValue | LocationValue[], type: convertFrom.Type | null, diff --git a/types/amap-js-api/dom-util.d.ts b/types/amap-js-api/dom-util.d.ts index d83a2ca69a..e39793f006 100644 --- a/types/amap-js-api/dom-util.d.ts +++ b/types/amap-js-api/dom-util.d.ts @@ -1,31 +1,78 @@ declare namespace AMap { namespace DomUtil { + /** + * 获取DOM元素的大小 + * @param dom DOM元素 + */ function getViewport(dom: HTMLElement): Size; - + /** + * 获取DOM元素距离窗口左上角的距离 + * @param dom DOM元素 + */ function getViewportOffset(dom: HTMLElement): Pixel; - + /** + * 在parentNode内部创建一个className类名的tagName元素 + * @param tagName 标签名称 + * @param parent 父节点 + * @param className 类名 + */ function create( tagName: K, parent?: HTMLElement, className?: string ): HTMLElementTagNameMap[K]; - + /** + * 给DOM元素设置为className样式 + * @param dom DOM元素 + * @param className 类名 + */ function setClass(dom: HTMLElement, className?: string): void; - + /** + * DOM元素是否包含className + * @param dom DOM元素 + * @param className 类名 + */ function hasClass(dom: HTMLElement, className: string): boolean; - + /** + * 给DOM元素添加一个className + * @param dom DOM元素 + * @param className 类名 + */ function addClass(dom: HTMLElement, className: string): void; - + /** + * 给DOM元素删除一个className + * @param dom DOM元素 + * @param className 类名 + */ function removeClass(dom: HTMLElement, className: string): void; - + /** + * 给DOM元素设定一个透明度 + * @param dom DOM元素 + * @param opacity 透明度(0-1) + */ function setOpacity(dom: HTMLElement, opacity: number): void; - + /** + * 给DOM元素旋转一个角度,以center为中心,center以元素左上角为坐标原点 + * @param dom DOM元素 + * @param deg 旋转角度 + * @param origin 旋转中心 + */ function rotate(dom: HTMLElement, deg: number, origin?: { x: number, y: number }): void; - + /** + * 给DOM元素删除一组样式,Object同样式表 + * @param dom DOM元素 + * @param style 样式 + */ function setCss(dom: HTMLElement | HTMLElement[], style: Partial): typeof DomUtil; // this - + /** + * 清空DOM元素 + * @param dom DOM元素 + */ function empty(dom: HTMLElement): void; - + /** + * 将DOM元素从父节点删除 + * @param dom DOM元素 + */ function remove(dom: HTMLElement): void; } } diff --git a/types/amap-js-api/event.d.ts b/types/amap-js-api/event.d.ts index d8ff5753c9..d90ee4c720 100644 --- a/types/amap-js-api/event.d.ts +++ b/types/amap-js-api/event.d.ts @@ -1,5 +1,13 @@ declare namespace AMap { abstract class EventEmitter { + /** + * 注册事件 + * @param eventName 事件名称 + * @param handler 事件回调函数 + * @param context 事件回调中的上下文 + * @param once 触发一次 + * @param unshift 更改事件顺序 + */ on( eventName: string, // tslint:disable-next-line:no-unnecessary-generics @@ -8,14 +16,23 @@ declare namespace AMap { once?: boolean, unshift?: boolean ): this; - + /** + * 移除事件绑定 + * @param eventName 事件名称 + * @param handler 事件功能函数 + * @param context 事件上下文 + */ off( eventName: string, // tslint:disable-next-line handler: ((this: C, event: E) => void) | 'mv', context?: C ): this; - + /** + * 触发事件 + * @param eventName 事件名称 + * @param data 事件数据 + */ emit(eventName: string, data?: any): this; } @@ -23,7 +40,13 @@ declare namespace AMap { interface EventListener { type: T; } - + /** + * 注册DOM对象事件 + * @param instance 需注册事件的DOM对象 + * @param eventName 事件名称 + * @param handler 事件功能函数 + * @param context 事件上下文 + */ function addDomListener( // tslint:disable-next-line: no-unnecessary-generics instance: HTMLElementTagNameMap[N], @@ -31,7 +54,13 @@ declare namespace AMap { handler: (this: C, event: HTMLElementEventMap[E]) => void, context?: C ): EventListener<0>; - + /** + * 给对象注册事件 + * @param instance 需注册事件的对象 + * @param eventName 事件名称 + * @param handler 事件功能函数 + * @param context 事件上下文 + */ function addListener( // tslint:disable-next-line: no-unnecessary-generics instance: I, @@ -41,7 +70,13 @@ declare namespace AMap { // tslint:disable-next-line: no-unnecessary-generics context?: C ): EventListener<1>; - + /** + * 给对象注册一次性事件 + * @param instance 需注册事件的对象 + * @param eventName 事件名称 + * @param handler 事件功能函数 + * @param context 事件上下文 + */ function addListenerOnce( // tslint:disable-next-line: no-unnecessary-generics instance: I, @@ -51,9 +86,17 @@ declare namespace AMap { // tslint:disable-next-line: no-unnecessary-generics context?: C ): EventListener<1>; - + /** + * 删除事件 + * @param listener 侦听器 + */ function removeListener(listener: EventListener<0 | 1>): void; - + /** + * 触发非DOM事件 + * @param instance 触发对象 + * @param eventName 事件名称 + * @param data 事件数据 + */ function trigger(instance: EventEmitter, eventName: string, data?: any): void; } } diff --git a/types/amap-js-api/geometry-util.d.ts b/types/amap-js-api/geometry-util.d.ts index 03f6800088..c8a5eae2e9 100644 --- a/types/amap-js-api/geometry-util.d.ts +++ b/types/amap-js-api/geometry-util.d.ts @@ -1,106 +1,176 @@ declare namespace AMap { namespace GeometryUtil { + /** + * 计算两个经纬度点之间的实际距离 + */ function distance( point1: LocationValue, point2: LocationValue | LocationValue[] ): number; - + /** + * 计算一个经纬度路径围成区域的实际面积 + */ function ringArea(ring: LocationValue[]): number; - + /** + * 判断一个经纬度路径是否为顺时针 + */ function isClockwise(path: LocationValue[]): boolean; - + /** + * 计算一个经纬度路径的实际长度 + */ function distanceOfLine(line: LocationValue[]): number; - + /** + * 计算两个经纬度面的交叉区域 + */ function ringRingClip( ring1: LocationValue[], ring2: LocationValue[] ): Array<[number, number]>; - + /** + * 判断两个经纬度面是否交叉 + */ function doesRingRingIntersect( ring1: LocationValue[], ring2: LocationValue[] ): boolean; - + /** + * 判断经纬度路径和经纬度面是否交叉 + */ function doesLineRingIntersect( line: LocationValue[], ring: LocationValue[] ): boolean; - + /** + * 判断两个经纬度路径是否相交 + */ function doesLineLineIntersect( line1: LocationValue[], line2: LocationValue[] ): boolean; - + /** + * 判断线段和多个环是否相交 + */ function doesSegmentPolygonIntersect( point1: LocationValue, point2: LocationValue, polygon: LocationValue[][] ): boolean; - + /** + * 判断线段和一个环是否相交 + */ function doesSegmentRingIntersect( point1: LocationValue, point2: LocationValue, ring: LocationValue[] ): boolean; - + /** + * 判断线段和一个路径是否相交 + */ function doesSegmentLineIntersect( point1: LocationValue, point2: LocationValue, line: LocationValue[] ): boolean; - + /** + * 判断两个线段是否相交 + */ function doesSegmentsIntersect( point1: LocationValue, point2: LocationValue, point3: LocationValue, point4: LocationValue ): boolean; - + /** + * 判断点是否在环内 + */ function isPointInRing(point: LocationValue, ring: LocationValue[]): boolean; - + /** + * 判断环是否在另一个环内 + */ function isRingInRing(ring1: LocationValue[], ring2: LocationValue[]): boolean; - + /** + * 判断点是否在多个环组成区域内 + */ function isPointInPolygon(point: LocationValue, polygon: LocationValue[][]): boolean; - + /** + * 判断点是否在多个环组成区域内 + */ function makesureClockwise(path: Array<[number, number]>): Array<[number, number]>; - + /** + * 将一个路径变为逆时针 + */ function makesureAntiClockwise(path: Array<[number, number]>): Array<[number, number]>; - + /** + * 计算P2P3上距离P1最近的点 + * @param point1 P1 + * @param point2 P2 + * @param point3 P3 + */ function closestOnSegment( point1: LocationValue, point2: LocationValue, point3: LocationValue ): [number, number]; - + /** + * 计算line上距离P最近的点 + */ function closestOnLine(point: LocationValue, line: LocationValue[]): [number, number]; - + /** + * 计算P2P3到P1的距离 + * @param point1 P1 + * @param point2 P2 + * @param point3 P3 + */ function distanceToSegment( point1: LocationValue, point2: LocationValue, point3: LocationValue ): number; - + /** + * 计算P到line的距离 + */ function distanceToLine(point: LocationValue, line: LocationValue[]): number; - + /** + * 判断P1是否在P2P3上 + * @param point1 P1 + * @param point2 P2 + * @param point3 P3 + * @param tolerance 误差范围 + */ function isPointOnSegment( point1: LocationValue, point2: LocationValue, point3: LocationValue, tolerance?: number ): boolean; - + /** + * 判断P是否在line上 + * @param point 点P + * @param line 线 + * @param tolerance 误差范围 + */ function isPointOnLine( point: LocationValue, line: LocationValue[], tolerance?: number ): boolean; - + /** + * 判断P是否在ring的边上 + * @param point 点P + * @param ring 环 + * @param tolerance 误差范围 + */ function isPointOnRing( point: LocationValue, ring: LocationValue[], tolerance?: number ): boolean; - + /** + * 判断P是否在多个ring的边上 + * @param point 点P + * @param polygon 多边形 + * @param tolerance 误差范围 + */ function isPointOnPolygon( point: LocationValue, polygon: LocationValue[][], diff --git a/types/amap-js-api/layer/building.d.ts b/types/amap-js-api/layer/building.d.ts index 30dd7c4092..1b7426e28d 100644 --- a/types/amap-js-api/layer/building.d.ts +++ b/types/amap-js-api/layer/building.d.ts @@ -1,11 +1,27 @@ declare namespace AMap { namespace Buildings { interface Options extends Layer.Options { + /** + * 可见级别范围 + */ zooms?: [number, number]; + /** + * 不透明度 + */ opacity?: number; + /** + * 高度比例系数,可控制3D视图下的楼块高度 + */ heightFactor?: number; + /** + * 是否可见 + */ visible?: boolean; + /** + * 层级 + */ zIndex?: number; + // inner merge?: boolean; sort?: boolean; @@ -24,7 +40,15 @@ declare namespace AMap { } class Buildings extends Layer { + /** + * 楼块图层,单独展示矢量化的楼块图层 + * @param opts 图层选项 + */ constructor(opts?: Buildings.Options); + /** + * 按区域设置楼块的颜色 + * @param style 颜色设置 + */ setStyle(style: Buildings.Style): void; } } diff --git a/types/amap-js-api/layer/flexible.d.ts b/types/amap-js-api/layer/flexible.d.ts index bdb4001a7c..d91970dc31 100644 --- a/types/amap-js-api/layer/flexible.d.ts +++ b/types/amap-js-api/layer/flexible.d.ts @@ -2,6 +2,14 @@ declare namespace AMap { namespace TileLayer { namespace Flexible { interface Options extends TileLayer.Options { + /** + * 创建切片回调 + * @param x 横坐标 + * @param y 纵坐标 + * @param z 层级 + * @param success 成功回调 + * @param fail 失败回调 + */ createTile?( x: number, y: number, @@ -9,11 +17,21 @@ declare namespace AMap { success: (tile: HTMLImageElement | HTMLCanvasElement) => void, fail: () => void ): void; + /** + * 内存中缓存的切片的数量上限 + */ cacheSize?: number; + /** + * 是否显示 + */ visible?: boolean; } } class Flexible extends TileLayer { + /** + * 灵活切片图层 + * @param options 图层选项 + */ constructor(options?: Flexible.Options); } } diff --git a/types/amap-js-api/layer/layer.d.ts b/types/amap-js-api/layer/layer.d.ts index 8f35d949fd..64714bc68f 100644 --- a/types/amap-js-api/layer/layer.d.ts +++ b/types/amap-js-api/layer/layer.d.ts @@ -1,20 +1,56 @@ declare namespace AMap { namespace Layer { interface Options { + /** + * 所属的地图对象 + */ map?: Map; } } abstract class Layer extends EventEmitter { + /** + * 图层获取DOM节点 + */ getContainer(): HTMLDivElement | undefined; + /** + * 获取图层缩放范围 + */ getZooms(): [number, number]; + /** + * 设置透明度 + * @param alpha 透明度 + */ setOpacity(alpha: number): void; + /** + * 设置透明度 + */ getOpacity(): number; + /** + * 显示图层 + */ show(): void; + /** + * 隐藏图层 + */ hide(): void; + /** + * 设置图层所属地图 + * @param map map对象 + */ setMap(map?: Map | null): void; + /** + * 获取图层所属地图 + */ getMap(): Map | null | undefined; + /** + * 设置图层的层级 + * @param index 层级 + */ setzIndex(index: number): void; + /** + * 获取图层的层级 + */ getzIndex(): number; } } diff --git a/types/amap-js-api/layer/layerGroup.d.ts b/types/amap-js-api/layer/layerGroup.d.ts index 4cc463eef7..6a07c8fc72 100644 --- a/types/amap-js-api/layer/layerGroup.d.ts +++ b/types/amap-js-api/layer/layerGroup.d.ts @@ -1,14 +1,49 @@ declare namespace AMap { class LayerGroup extends Layer { + /** + * 图层集合 + * @param layers 集合中的图层 + */ constructor(layers: L | L[]); + /** + * 添加单个图层到集合中,不支持添加重复的图层 + * @param layer 图层 + */ addLayer(layer: L | L[]): this; + /** + * 添加图层数组到集合中,不支持添加重复的图层 + * @param layers 图层数组 + */ addLayers(layers: L | L[]): this; + /** + * 返回当前集合中所有的图层 + */ getLayers(): L[]; getLayer(finder: (this: null, item: L, index: number, list: L[]) => boolean): L | null; + /** + * 判断传入的图层实例是否在集合中 + * @param layer 目标图层 + */ hasLayer(layer: L | ((this: null, item: L, index: number, list: L[]) => boolean)): boolean; + /** + * 从集合中删除传入的图层实例 + * @param layer 图层 + */ removeLayer(layer: L | L[]): this; - removeLayers(layer: L | L[]): this; + /** + * 从集合中删除传入的图层实例数组 + * @param layers 图层数组 + */ + removeLayers(layers: L | L[]): this; + /** + * 清空集合 + */ clearLayers(): this; + /** + * 对集合中的图层做迭代操作 + * @param iterator 迭代回调 + * @param context 执行上下文 + */ eachLayer(iterator: (this: C, layer: L, index: number, list: L[]) => void, context?: C): void; // overwrite diff --git a/types/amap-js-api/layer/massMarks.d.ts b/types/amap-js-api/layer/massMarks.d.ts index 1ab5464a5b..963f7e2ec6 100644 --- a/types/amap-js-api/layer/massMarks.d.ts +++ b/types/amap-js-api/layer/massMarks.d.ts @@ -12,21 +12,51 @@ declare namespace AMap { } interface Style { + /** + * 图标显示位置偏移量,以图标的左上角为基准点(0,0)点 + */ anchor: Pixel; + /** + * 图标的地址 + */ url: string; + /** + * 图标的尺寸 + */ size: Size; + /** + * 旋转角度 + */ rotation?: number; } type UIEvent = Event ? D : Data; }>; interface Options extends Layer.Options { + /** + * 显示层级 + */ zIndex?: number; + /** + * 指针样式 + */ cursor?: string; + /** + * 是否在拖拽缩放过程中实时重绘 + */ alwayRender?: boolean; + /** + * 设置点的样式 + */ style: Style | Style[]; // rejectMapMask } @@ -37,11 +67,33 @@ declare namespace AMap { } class MassMarks extends Layer { + /** + * 海量点类,利用该类可同时在地图上展示万级别的点 + * @param data 点对象数组或url + * @param opts 选项 + */ constructor(data: D[] | string, opts: MassMarks.Options); + /** + * 设置显示样式 + * @param style 样式设置 + */ setStyle(style: MassMarks.Style | MassMarks.Style[]): void; + /** + * 获取显示样式 + */ getStyle(): MassMarks.Style | MassMarks.Style[]; + /** + * 设置数据集 + * @param data 数据集 + */ setData(data: D[] | string): void; + /** + * 获取数据集 + */ getData(): Array> & { lnglat: LngLat }>; + /** + * 清除海量点 + */ clear(): void; } } diff --git a/types/amap-js-api/layer/mediaLayer.d.ts b/types/amap-js-api/layer/mediaLayer.d.ts index a38f5ba025..43fee214bb 100644 --- a/types/amap-js-api/layer/mediaLayer.d.ts +++ b/types/amap-js-api/layer/mediaLayer.d.ts @@ -1,35 +1,94 @@ declare namespace AMap { namespace MediaLayer { interface Options extends Layer.Options { + /** + * 显示范围 + */ bounds?: Bounds; + /** + * 是否可见 + */ visible?: boolean; + /** + * 缩放范围 + */ zooms?: [number, number]; + /** + * 透明度 + */ opacity?: number; } } abstract class MediaLayer extends Layer { + /** + * @param options 图层选项 + */ constructor(options?: MediaLayer.Options); + /** + * 设置显示范围 + * @param bounds 显示范围 + */ setBounds(bounds: Bounds): void; + /** + * 获取显示的范围 + */ getBounds(): Bounds; + /** + * 设置图层选项 + * @param options 图层选项 + */ setOptions(options: Partial): void; + /** + * 获取图层选项 + */ getOptions(): Partial; + /** + * 获取元素 + */ getElement(): E | null; } + /** + * 图片图层 + */ class ImageLayer extends MediaLayer { + /** + * 修改Image的Url + * @param url url + */ setImageUrl(url: string): void; + /** + * 返回Image的Url + */ getImageUrl(): string | undefined; } class VideoLayer extends MediaLayer { + /** + * 修改Video的Url + * @param source url + */ setVideoUrl(source: string | string[]): void; + /** + * 返回Video的Url + */ getVideoUrl(): string | string[] | undefined; } class CanvasLayer extends MediaLayer { + /** + * 修改显示的Canvas + * @param canvas Canvas对象 + */ setCanvas(canvas: HTMLCanvasElement): void; + /** + * 返回Canvas对象 + */ getCanvas(): HTMLCanvasElement | undefined; + /** + * 当canvas的内容发生改变是用于刷新图层 + */ reFresh(): void; } } diff --git a/types/amap-js-api/layer/tileLayer.d.ts b/types/amap-js-api/layer/tileLayer.d.ts index 7576a70664..1a146b964c 100644 --- a/types/amap-js-api/layer/tileLayer.d.ts +++ b/types/amap-js-api/layer/tileLayer.d.ts @@ -5,33 +5,87 @@ declare namespace AMap { } interface Options extends Layer.Options { + /** + * 切片大小 + */ tileSize?: number; + /** + * 切片取图地址(自1.3版本起,该属性与getTileUrl属性合并) + */ tileUrl?: string; + /** + * 取图错误时的代替地址 + */ errorUrl?: string; + /** + * 获取图块取图地址 + */ getTileUrl?: string | ((x: number, y: number, level: number) => string); + /** + * 图层叠加的顺序值 + */ zIndex?: number; + /** + * 图层的透明度 + */ opacity?: number; + /** + * 支持的缩放级别范围 + */ zooms?: [number, number]; + /** + * 是否在高清屏下进行清晰度适配 + */ detectRetina?: boolean; } + /** + * 卫星图层 + */ class Satellite extends TileLayer { } + /** + * 路网图层 + */ class RoadNet extends TileLayer { } namespace Traffic { interface Options extends TileLayer.Options { + /** + * 是否设置可以自动刷新实时路况信息 + */ autoRefresh?: boolean; + /** + * 设置刷新间隔时长 + */ interval?: number; } } class Traffic extends TileLayer { + /** + * 实时交通图层 + * @param options 图层选项 + */ constructor(options?: Traffic.Options); } } class TileLayer extends Layer { + /** + * 切片图层 + * @param options 图层选项 + */ constructor(options?: TileLayer.Options); + /** + * 获取当前图层所有切片号 + */ getTiles(): string[]; + /** + * 重新加载此图层 + */ reload(): void; + /** + * 设置图层的取图地址 + * @param url 取图地址 + */ setTileUrl(url: string | ((x: number, y: number, level: number) => string)): void; } } diff --git a/types/amap-js-api/layer/wms.d.ts b/types/amap-js-api/layer/wms.d.ts index c4561ddf14..043975d856 100644 --- a/types/amap-js-api/layer/wms.d.ts +++ b/types/amap-js-api/layer/wms.d.ts @@ -13,16 +13,43 @@ declare namespace AMap { ELEVATION?: string; } interface Options extends Flexible.Options { + /** + * wms服务的url地址 + */ url: string; + /** + * OGC标准的WMS地图服务的GetMap接口的参数 + */ params: Params; + /** + * 地图级别切换时,不同级别的图片是否进行混合 + */ blend?: boolean; } } class WMS extends Flexible { + /** + * WMS图层 + * @param options 图层选项 + */ constructor(options: WMS.Options); + /** + * 设置wms服务地址 + * @param url 服务地址 + */ setUrl(url: string): void; + /** + * 返回wms服务地址 + */ getUrl(): string; + /** + * 设置OGC标准的WMS getMap接口的参数 + * @param params 接口参数 + */ setParams(params: WMS.Params): void; + /** + * 返回OGC标准的WMS getMap接口的参数 + */ getParams(): WMS.Params; } } diff --git a/types/amap-js-api/layer/wmts.d.ts b/types/amap-js-api/layer/wmts.d.ts index 5d85e5df48..7a122dd6b9 100644 --- a/types/amap-js-api/layer/wmts.d.ts +++ b/types/amap-js-api/layer/wmts.d.ts @@ -8,17 +8,44 @@ declare namespace AMap { Format?: string; } interface Options extends Flexible.Options { + /** + * wmts服务的url地址 + */ url: string; + /** + * OGC标准的WMTS地图服务的GetTile接口的参数 + */ params: Params; + /** + * 地图级别切换时,不同级别的图片是否进行混合 + */ blend?: boolean; } } class WMTS extends Flexible { + /** + * WMTS图层 + * @param options 图层选项 + */ constructor(options: WMTS.Options); + /** + * 设置wmts服务地址 + * @param url 服务地址 + */ setUrl(url: string): void; + /** + * 返回wmts服务地址 + */ getUrl(): string; + /** + * 设置OGC标准的WMTS getTile接口的参数 + * @param params 接口参数 + */ setParams(params: WMTS.Params): void; + /** + * 返回OGC标准的WMTS getTile接口的参数 + */ getParams(): WMTS.Params; } } diff --git a/types/amap-js-api/lngLat.d.ts b/types/amap-js-api/lngLat.d.ts index 4247002b2b..f649a78de8 100644 --- a/types/amap-js-api/lngLat.d.ts +++ b/types/amap-js-api/lngLat.d.ts @@ -1,11 +1,39 @@ declare namespace AMap { class LngLat { + /** + * 构造一个地理坐标对象 + * @param lng 经度 + * @param lat 纬度 + * @param noAutofix 是否自动修正 + */ constructor(lng: number, lat: number, noAutofix?: boolean); + /** + * 移动当前经纬度坐标得到新的坐标 + * @param east 移动经度,向右为正值 + * @param north 移动维度,向上为正值 + */ offset(east: number, north: number): LngLat; + /** + * 当前经纬度和传入经纬度或者经纬度数组连线之间的地面距离,单位为米 + * @param lnglat 对比目标 + */ distance(lnglat: LngLat | LngLat[]): number; + /** + * 获取经度值 + */ getLng(): number; + /** + * 获取纬度值 + */ getLat(): number; + /** + * 判断当前坐标对象与传入坐标对象是否相等 + * @param lnglat 判断目标 + */ equals(lnglat: LngLat): boolean; + /** + * 以字符串的形式返回 + */ toString(): string; // internal diff --git a/types/amap-js-api/map.d.ts b/types/amap-js-api/map.d.ts index 46edc68577..e7937966b1 100644 --- a/types/amap-js-api/map.d.ts +++ b/types/amap-js-api/map.d.ts @@ -3,39 +3,145 @@ declare namespace AMap { type Feature = 'bg' | 'point' | 'road' | 'building'; type ViewMode = '2D' | '3D'; interface Options { + /** + * 地图视口,用于控制影响地图静态显示的属性 + */ view?: View2D; + /** + * 地图图层数组,数组可以是图层 中的一个或多个,默认为普通二维地图 + */ layers?: Layer[]; + /** + * 地图显示的缩放级别 + */ zoom?: number; + /** + * 地图中心点坐标值 + */ center?: LocationValue; + /** + * 地图标注显示顺序 + */ labelzIndex?: number; + /** + * 地图显示的缩放级别范围 + */ zooms?: [number, number]; + /** + * 地图语言类型 + */ lang?: Lang; + /** + * 地图默认鼠标样式 + */ defaultCursor?: string; + /** + * 地图显示的参考坐标系 + */ crs?: 'EPSG3857' | 'EPSG3395' | 'EPSG4326'; + /** + * 地图平移过程中是否使用动画 + */ animateEnable?: boolean; + /** + * 是否开启地图热点和标注的hover效果 + */ isHotspot?: boolean; + /** + * 当前地图中默认显示的图层 + */ defaultLayer?: TileLayer; + /** + * 地图是否可旋转 + */ rotateEnable?: boolean; + /** + * 是否监控地图容器尺寸变化 + */ resizeEnable?: boolean; + /** + * 是否在有矢量底图的时候自动展示室内地图 + */ showIndoorMap?: boolean; + /** + * 在展示矢量图的时候自动展示室内地图图层 + */ + // indoorMap?: IndorMap + /** + * 是否支持可以扩展最大缩放级别 + */ expandZoomRange?: boolean; + /** + * 地图是否可通过鼠标拖拽平移 + */ dragEnable?: boolean; + /** + * 地图是否可缩放 + */ zoomEnable?: boolean; + /** + * 地图是否可通过双击鼠标放大地图 + */ doubleClickZoom?: boolean; + /** + * 地图是否可通过键盘控制 + */ keyboardEnable?: boolean; + /** + * 地图是否使用缓动效果 + */ jogEnable?: boolean; + /** + * 地图是否可通过鼠标滚轮缩放浏览 + */ scrollWheel?: boolean; + /** + * 地图在移动终端上是否可通过多点触控缩放浏览地图 + */ touchZoom?: boolean; + /** + * 当touchZoomCenter=1的时候,手机端双指缩放的以地图中心为中心,否则默认以双指中间点为中心 + */ touchZoomCenter?: number; + /** + * 设置地图的显示样式 + */ mapStyle?: string; + /** + * 设置地图上显示的元素种类 + */ features?: Feature[] | 'all' | Feature; + /** + * 设置地图显示3D楼块效果 + */ showBuildingBlock?: boolean; + /** + * 视图模式 + */ viewMode?: ViewMode; + /** + * 俯仰角度 + */ pitch?: number; + /** + * 是否允许设置俯仰角度 + */ pitchEnable?: boolean; + /** + * 楼块出现和消失的时候是否显示动画过程 + */ buildingAnimation?: boolean; + /** + * 调整天空颜色 + */ skyColor?: string; + /** + * 设置地图的预加载模式 + */ preloadMode?: boolean; + /** + * 为 Map 实例指定掩模的路径,各图层将只显示路径范围内图像 + */ mask?: Array<[number, number]> | Array> | Array>>; maxPitch?: number; rotation?: number; @@ -58,24 +164,67 @@ declare namespace AMap { // detectRetina: number; } interface Status { + /** + * 是否开启动画 + */ animateEnable: boolean; + /** + * 是否双击缩放 + */ doubleClickZoom: boolean; + /** + * 是否支持拖拽 + */ dragEnable: boolean; isHotspot: boolean; + /** + * 是否开启缓动效果 + */ jogEnable: boolean; + /** + * 是否支持键盘 + */ keyboardEnable: boolean; + /** + * 是否支持调整俯仰角 + */ pitchEnable: boolean; resizeEnable: boolean; + /** + * 是否支持旋转 + */ rotateEnable: boolean; + /** + * 是否支持滚轮缩放 + */ scrollWheel: boolean; + /** + * 是否支持触摸缩放 + */ touchZoom: boolean; + /** + * 是否支持缩放 + */ zoomEnable: boolean; } type HotspotEvent = Event; interface EventMap { @@ -113,73 +262,305 @@ declare namespace AMap { } class Map extends EventEmitter { + /** + * 构造一个地图对象 + * @param container 地图容器的id或者是DOM元素 + * @param opts 选项 + */ constructor(container: string | HTMLElement, opts?: Map.Options); + /** + * 唤起高德地图客户端marker页 + * @param obj 唤起参数 + */ poiOnAMAP(obj: { id: string; location?: LocationValue; name?: string }): void; + /** + * 唤起高德地图客户端marker详情页 + * @param obj 唤起参数 + */ detailOnAMAP(obj: { id: string; location?: LocationValue; name?: string }): void; + /** + * 获取当前地图缩放级别 + */ getZoom(): number; + /** + * 获取地图图层数组 + */ getLayers(): Layer[]; + /** + * 获取地图中心点经纬度坐标值 + */ getCenter(): LngLat; + /** + * 返回地图对象的容器 + */ getContainer(): HTMLElement | null; + /** + * 获取地图中心点所在区域 + */ getCity(callback: (cityData: { + /** + * 市名称 + */ city: string; + /** + * 市代码 + */ citycode: string; + /** + * 区名称 + */ district: string; + /** + * 省 + */ province: string | never[]; // province is empty array when getCity fail }) => void): void; + /** + * 获取当前地图视图范围,获取当前可视区域 + */ getBounds(): Bounds; + /** + * 获取当前地图标注的显示顺序 + */ getLabelzIndex(): number; + /** + * 获取Map的限制区域 + */ getLimitBounds(): Bounds; + /** + * 获取地图语言类型 + */ getLang(): Lang; + /** + * 获取地图容器像素大小 + */ getSize(): Size; + /** + * 获取地图顺时针旋转角度 + */ getRotation(): number; + /** + * 获取当前地图状态信息 + */ getStatus(): Map.Status; + /** + * 获取地图默认鼠标指针样式 + */ getDefaultCursor(): string; + /** + * 获取指定位置的地图分辨率 + * @param point 指定经纬度 + */ getResolution(point?: LocationValue): number; + /** + * 获取当前地图比例尺 + * @param dpi dpi + */ getScale(dpi?: number): number; + /** + * 设置地图显示的缩放级别 + * @param level 缩放级别 + */ setZoom(level: number): void; + /** + * 设置地图标注显示的顺序 + * @param index 显示顺序 + */ setLabelzIndex(index: number): void; + /** + * 设置地图图层数组 + * @param layers 图层数组 + */ setLayers(layers: Layer[]): void; + /** + * 添加覆盖物/图层 + * @param overlay 覆盖物/图层 + */ add(overlay: Overlay | Overlay[]): void; + /** + * 删除覆盖物/图层 + * @param overlay 覆盖物/图层 + */ remove(overlay: Overlay | Overlay[]): void; + /** + * 返回添加的覆盖物对象 + * @param type 覆盖物类型 + */ getAllOverlays(type?: 'marker' | 'circle' | 'polyline' | 'polygon'): Overlay[]; + /** + * 设置地图显示的中心点 + * @param center 中心点经纬度 + */ setCenter(center: LocationValue): void; + /** + * 地图缩放至指定级别并以指定点为地图显示中心点 + * @param zoomLevel 缩放等级 + * @param center 缩放中心 + */ setZoomAndCenter(zoomLevel: number, center: LocationValue): void; + /** + * 按照行政区名称或adcode来设置地图显示的中心点。 + * @param city 城市名称或城市编码 + * @param callback 回调 + */ setCity(city: string, callback: (this: this, coord: [string, string], zoom: number) => void): void; + /** + * 指定当前地图显示范围 + * @param bound 显示范围 + */ setBounds(bound: Bounds): Bounds; + /** + * 设置Map的限制区域 + * @param bound 限制区域 + */ setLimitBounds(bound: Bounds): void; + /** + * 清除限制区域 + */ clearLimitBounds(): void; + /** + * 设置地图语言类型 + * @param lang 语言类型 + */ setLang(lang: Lang): void; + /** + * 设置地图顺时针旋转角度,旋转原点为地图容器中心点 + * @param rotation 旋转角度 + */ setRotation(rotation: number): void; + /** + * 设置当前地图显示状态 + * @param status 状态 + */ setStatus(status: Partial): void; + /** + * 设置鼠标指针默认样式 + * @param cursor 指针样式 + */ setDefaultCursor(cursor: string): void; + /** + * 地图放大一级显示 + */ zoomIn(): void; + /** + * 地图缩小一级显示 + */ zoomOut(): void; + /** + * 地图中心点平移至指定点位置 + * @param position 目标位置经纬度 + */ panTo(position: LocationValue): void; + /** + * 以像素为单位,沿x方向和y方向移动地图 + * @param x 横向移动像素,向右为正 + * @param y 纵向移动像素,向下为正 + */ panBy(x: number, y: number): void; + /** + * 根据地图上添加的覆盖物分布情况,自动缩放地图到合适的视野级别 + * @param overlayList 覆盖物数组 + * @param immediately 是否需要动画过程 + * @param avoid 上下左右的像素避让宽度 + * @param maxZoom 最大缩放级别 + */ setFitView( overlayList?: Overlay | Overlay[], immediately?: boolean, avoid?: [number, number, number, number], maxZoom?: number ): Bounds | false | undefined; + /** + * 删除地图上所有的覆盖物 + */ clearMap(): void; + /** + * 注销地图对象,并清空地图容器 + */ destroy(): void; + /** + * 加载插件, + * tips: 插件的类型定义不在本类型定义中给出,需要另行安装例如 + * 3d地图:@types/amap-js-api-map3d + * 地区搜索:@types/amap-js-api-place-search + * @param name 插件名称 + * @param callback 插件加载完成后的回调函数 + */ plugin(name: string | string[], callback: () => void): this; + /** + * 添加控件 + * @param control 控件 + */ addControl(control: {}): void; // TODO + /** + * 移除控件 + * @param control 控件 + */ removeControl(control: {}): void; // TODO + /** + * 清除地图上的信息窗体。 + */ clearInfoWindow(): void; + /** + * 平面地图像素坐标转换为地图经纬度坐标 + * @param pixel 像素坐标 + * @param level 缩放等级 + */ pixelToLngLat(pixel: Pixel, level?: number): LngLat; + /** + * 地图经纬度坐标转换为平面地图像素坐标 + * @param lnglat 经纬度坐标 + * @param level 缩放等级 + */ lnglatToPixel(lnglat: LocationValue, level?: number): Pixel; + /** + * 地图容器像素坐标转为地图经纬度坐标 + * @param pixel 地图像素坐标 + */ containerToLngLat(pixel: Pixel): LngLat; + /** + * 地图经纬度坐标转为地图容器像素坐标 + * @param lnglat 经纬度坐标 + */ lngLatToContainer(lnglat: LocationValue): Pixel; + /** + * 地图经纬度坐标转为地图容器像素坐标 + * @param lnglat 经纬度坐标 + */ lnglatTocontainer(lnglat: LocationValue): Pixel; + /** + * 设置地图的显示样式 + * @param style 地图样式 + */ setMapStyle(style: string): void; + /** + * 获取地图显示样式 + */ getMapStyle(): string; + /** + * 设置地图上显示的元素种类 + * @param feature 元素 + */ setFeatures(feature: Map.Feature | Map.Feature[] | 'all'): void; + /** + * 获取地图显示元素种类 + */ getFeatures(): Map.Feature | Map.Feature[] | 'all'; + /** + * 修改底图图层 + * @param layer 图层 + */ setDefaultLayer(layer: TileLayer): void; + /** + * 设置俯仰角 + * @param pitch 俯仰角 + */ setPitch(pitch: number): void; + /** + * 获取俯仰角 + */ getPitch(): number; + getViewMode_(): Map.ViewMode; lngLatToGeodeticCoord(lnglat: LocationValue): Pixel; geodeticCoordToLngLat(pixel: Pixel): LngLat; diff --git a/types/amap-js-api/overlay/bezierCurve.d.ts b/types/amap-js-api/overlay/bezierCurve.d.ts index 5778cb72a6..b861440a92 100644 --- a/types/amap-js-api/overlay/bezierCurve.d.ts +++ b/types/amap-js-api/overlay/bezierCurve.d.ts @@ -2,18 +2,31 @@ declare namespace AMap { namespace BezierCurve { interface EventMap extends Polyline.EventMap { } type Options = Merge, { - // internal + /** + * 贝瑟尔曲线的路径 + */ path: Array>>; + // internal tolerance?: number; interpolateNumLimit?: [number | number]; }>; interface GetOptionsResult extends Polyline.GetOptionsResult { + /** + * 贝瑟尔曲线的路径 + */ path: Array; } } class BezierCurve extends Polyline { + /** + * 贝瑟尔曲线 + * @param options 覆盖物选项 + */ constructor(options: BezierCurve.Options); + /** + * 获取覆盖物选项 + */ getOptions(): Partial>; // internal getInterpolateLngLats(): LngLat[]; diff --git a/types/amap-js-api/overlay/circle.d.ts b/types/amap-js-api/overlay/circle.d.ts index 2a1cbd9020..c718119e5a 100644 --- a/types/amap-js-api/overlay/circle.d.ts +++ b/types/amap-js-api/overlay/circle.d.ts @@ -34,15 +34,50 @@ declare namespace AMap { } class Circle extends ShapeOverlay { + /** + * 圆形覆盖物 + * @param options 覆盖物选项 + */ constructor(options?: Circle.Options); + /** + * 设置圆中心点 + * @param center 中心点经纬度 + * @param preventEvent 阻止触发事件 + */ setCenter(center: LocationValue, preventEvent?: boolean): void; + /** + * 获取圆中心点 + */ getCenter(): LngLat | undefined; + /** + * 获取圆外切矩形范围 + */ getBounds(): Bounds | null; + /** + * 设置圆形的半径 + * @param radius 半径 + * @param preventEvent 阻止触发事件 + */ setRadius(radius: number, preventEvent?: boolean): void; + /** + * 获取圆形的半径 + */ getRadius(): number; + /** + * 修改选项 + * @param options 选项 + */ setOptions(options?: Circle.Options): void; + /** + * 获取选项 + */ getOptions(): Partial>; + /** + * 判断指定点坐标是否在圆内 + * @param point 坐标 + */ contains(point: LocationValue): boolean; + // internal getPath(count?: number): LngLat[]; } diff --git a/types/amap-js-api/overlay/circleMarker.d.ts b/types/amap-js-api/overlay/circleMarker.d.ts index 13e4162f46..0b67d7f13e 100644 --- a/types/amap-js-api/overlay/circleMarker.d.ts +++ b/types/amap-js-api/overlay/circleMarker.d.ts @@ -1,4 +1,7 @@ declare namespace AMap { // tslint:disable-next-line; + /** + * 圆点标记 + */ class CircleMarker extends Circle {} } diff --git a/types/amap-js-api/overlay/contextMenu.d.ts b/types/amap-js-api/overlay/contextMenu.d.ts index 72c7fc2852..eacb6673c8 100644 --- a/types/amap-js-api/overlay/contextMenu.d.ts +++ b/types/amap-js-api/overlay/contextMenu.d.ts @@ -1,7 +1,11 @@ declare namespace AMap { namespace ContextMenu { interface Options { + /** + * 右键菜单内容 + */ content?: string | HTMLElement; + // internal visible?: boolean; } @@ -14,10 +18,33 @@ declare namespace AMap { } class ContextMenu extends Overlay { + /** + * 地图右键菜单 + * @param options 选项 + */ constructor(options?: ContextMenu.Options); + /** + * 右键菜单中添加菜单项 + * @param text 菜单显示内容 + * @param fn 该菜单下需进行的操作 + * @param num 当前菜单项在右键菜单中的排序位置,以0开始 + */ addItem(text: string, fn: (this: HTMLLIElement) => void, num?: number): void; - removeItem(test: string, fn: (this: HTMLLIElement) => void): void; + /** + * 删除一个菜单项 + * @param text 菜单显示内容 + * @param fn 该菜单下需进行的操作 + */ + removeItem(text: string, fn: (this: HTMLLIElement) => void): void; + /** + * 在地图的指定位置打开右键菜单。 + * @param map 目标地图 + * @param position 打开位置经纬度 + */ open(map: Map, position: LocationValue): void; + /** + * 关闭右键菜单 + */ close(): void; } } diff --git a/types/amap-js-api/overlay/ellipse.d.ts b/types/amap-js-api/overlay/ellipse.d.ts index 55feaf3112..de9da22e0c 100644 --- a/types/amap-js-api/overlay/ellipse.d.ts +++ b/types/amap-js-api/overlay/ellipse.d.ts @@ -6,7 +6,13 @@ declare namespace AMap { } interface Options extends Polygon.Options { + /** + * 椭圆的中心 + */ center?: LocationValue; + /** + * 椭圆半径 + */ radius?: [number, number]; } type GetOptionsResult = Merge, { @@ -15,9 +21,25 @@ declare namespace AMap { } class Ellipse extends Polygon { + /** + * 椭圆 + * @param options 选项 + */ constructor(options?: Ellipse.Options); + /** + * 获取椭圆的中心点 + */ getCenter(): LngLat | undefined; + /** + * 设置椭圆的中心点 + * @param center 中心点 + * @param preventEvent 阻止触发事件 + */ setCenter(center: LocationValue, preventEvent?: boolean): void; + /** + * 修改椭圆属性 + * @param options 属性 + */ setOptions(options: Ellipse.Options): void; // internal diff --git a/types/amap-js-api/overlay/geoJSON.d.ts b/types/amap-js-api/overlay/geoJSON.d.ts index 75098a59f0..aa3554cb04 100644 --- a/types/amap-js-api/overlay/geoJSON.d.ts +++ b/types/amap-js-api/overlay/geoJSON.d.ts @@ -24,9 +24,27 @@ declare namespace AMap { features: GeoJSONObject[]; }; interface Options { + /** + * 要加载的标准GeoJSON对象 + */ geoJSON?: GeoJSONObject | GeoJSONObject[]; + /** + * 指定点要素的绘制方式 + * @param obj GeoJSON对象 + * @param lnglat 点的位置 + */ getMarker?(obj: GeoJSONObject, lnglat: LngLat): Marker; + /** + * 指定线要素的绘制方式 + * @param obj GeoJSON对象 + * @param lnglats 线的路径 + */ getPolyline?(obj: GeoJSONObject, lnglats: LngLat[]): Polyline; + /** + * 指定面要素的绘制方式 + * @param obj GeoJSON对象 + * @param lnglats 面的路径 + */ getPolygon?(obj: GeoJSONObject, lnglats: LngLat[]): Polygon; coordsToLatLng?(lnglat: LngLat): LngLat; @@ -36,8 +54,19 @@ declare namespace AMap { } class GeoJSON extends OverlayGroup { + /** + * GeoJSON + * @param options 选项 + */ constructor(options?: GeoJSON.Options); + /** + * 加载新的GeoJSON对象,转化为覆盖物,旧的覆盖物将移除 + * @param obj GeoJSON对象 + */ importData(obj: GeoJSON.GeoJSONObject | GeoJSON.GeoJSONObject[]): void; + /** + * 将当前对象包含的覆盖物转换为GeoJSON对象 + */ toGeoJSON(): GeoJSON.GeoJSONObject[]; } } diff --git a/types/amap-js-api/overlay/icon.d.ts b/types/amap-js-api/overlay/icon.d.ts index be300feef3..18d75921bf 100644 --- a/types/amap-js-api/overlay/icon.d.ts +++ b/types/amap-js-api/overlay/icon.d.ts @@ -1,16 +1,39 @@ declare namespace AMap { namespace Icon { interface Options { + /** + * 图标尺寸 + */ size?: SizeValue; + /** + * 图标取图偏移量 + */ imageOffset?: Pixel; + /** + * 图标的取图地址 + */ image?: string; + /** + * 图标所用图片大小 + */ imageSize?: SizeValue; } } class Icon extends EventEmitter { + /** + * 点标记的图标 + * @param options 选项 + */ constructor(options?: Icon.Options); + /** + * 设置图标图片大小 + * @param size 大小 + */ setImageSize(size: SizeValue): void; + /** + * 获取图标图片大小 + */ getImageSize(): Size; } } diff --git a/types/amap-js-api/overlay/infoWindow.d.ts b/types/amap-js-api/overlay/infoWindow.d.ts index 54bedd95a8..1c9b69a9a3 100644 --- a/types/amap-js-api/overlay/infoWindow.d.ts +++ b/types/amap-js-api/overlay/infoWindow.d.ts @@ -7,13 +7,37 @@ declare namespace AMap { } interface Options extends Overlay.Options { + /** + * 是否自定义窗体 + */ isCustom?: boolean; + /** + * 是否自动调整窗体到视野内 + */ autoMove?: boolean; + /** + * 控制是否在鼠标点击地图后关闭信息窗体 + */ closeWhenClickMap?: boolean; + /** + * 显示内容 + */ content?: string | HTMLElement; + /** + * 信息窗体尺寸 + */ size?: SizeValue; + /** + * 信息窗体显示位置偏移量 + */ offset?: Pixel; + /** + * 信息窗体显示基点位置 + */ position?: LocationValue; + /** + * 是否显示信息窗体阴影 + */ showShadow?: boolean; // internal height?: number; @@ -21,16 +45,53 @@ declare namespace AMap { } class InfoWindow extends Overlay { + /** + * 信息展示窗体 + * @param options 选项 + */ constructor(options?: InfoWindow.Options); + /** + * 在地图的指定位置打开信息窗体 + * @param map 地图 + * @param position 打开的位置 + */ open(map: Map, position?: LocationValue): void; + /** + * 关闭信息窗体 + */ close(): void; + /** + * 获取信息窗体是否打开 + */ getIsOpen(): boolean; + /** + * 设置信息窗体内容 + * @param content 窗体内容 + */ setContent(content: string | HTMLElement): void; + /** + * 获取信息窗体内容 + */ getContent(): string | HTMLElement | undefined; + /** + * 设置信息窗体显示基点位置 + * @param lnglat 位置经纬度 + */ setPosition(lnglat: LocationValue): void; + /** + * 获取信息窗体显示基点位置 + */ getPosition(): LngLat | undefined; + /** + * 设置信息窗体大小 + * @param size 大小 + */ setSize(size: SizeValue): void; + /** + * 获取信息窗体大小 + */ getSize(): Size | undefined; + // internal setOffset(offset: Pixel): void; } diff --git a/types/amap-js-api/overlay/marker.d.ts b/types/amap-js-api/overlay/marker.d.ts index e24ce7be8f..42dddf394a 100644 --- a/types/amap-js-api/overlay/marker.d.ts +++ b/types/amap-js-api/overlay/marker.d.ts @@ -26,78 +26,268 @@ declare namespace AMap { } interface Options extends Overlay.Options { + /** + * 点标记在地图上显示的位置 + */ position?: LocationValue; + /** + * 点标记显示位置偏移量 + */ offset?: Pixel; + /** + * 需在点标记中显示的图标 + */ icon?: string | Icon; + /** + * 点标记显示内容 + */ content?: string | HTMLElement; + /** + * 鼠标点击时marker是否置顶 + */ topWhenClick?: boolean; + /** + * 是否将覆盖物的鼠标或touch等事件冒泡到地图上 + */ bubble?: boolean; + /** + * 点标记是否可拖拽移动 + */ draggable?: boolean; + /** + * 拖拽点标记时是否开启点标记离开地图的效果 + */ raiseOnDrag?: boolean; + /** + * 鼠标悬停时的鼠标样式 + */ cursor?: string; + /** + * 点标记是否可见 + */ visible?: boolean; + /** + * 点标记的叠加顺序 + */ zIndex?: number; + /** + * 点标记的旋转角度 + */ angle?: number; + /** + * 是否自动旋转 + */ autoRotation?: boolean; + /** + * 点标记的动画效果 + */ animation?: AnimationName; + /** + * 点标记阴影 + */ shadow?: Icon | string; + /** + * 鼠标滑过点标记时的文字提示 + */ title?: string; + /** + * 可点击区域 + */ shape?: MarkerShape; + /** + * 文本标注 + */ label?: Label; - zooms?: [number, number]; // internal + zooms?: [number, number]; topWhenMouseOver?: boolean; height?: number; } } class Marker extends Overlay { + /** + * 点标记 + * @param options 选项 + */ constructor(options?: Marker.Options); + /** + * 唤起高德地图客户端标注页 + * @param obj 唤起参数 + */ markOnAMAP(obj?: { name?: string, position?: LocationValue }): void; + /** + * 获取偏移量 + */ getOffset(): Pixel; + /** + * 设置偏移量 + * @param offset 偏移量 + */ setOffset(offset: Pixel): void; + /** + * 设置点标记的动画效果 + * @param animate 动画效果类型 + */ setAnimation(animate: AnimationName, prevent?: boolean): void; + /** + * 获取点标记的动画效果类型 + */ getAnimation(): AnimationName; + /** + * 设置点标记是支持鼠标单击事件 + * @param cilckable 是否支持点击 + */ setClickable(cilckable: boolean): void; + /** + * 获取点标记是否支持鼠标单击事件 + */ getClickable(): boolean; + /** + * 获取点标记的位置 + */ getPosition(): LngLat | undefined; + /** + * 设置点标记位置 + * @param position 位置经纬度 + */ setPosition(position: LocationValue): void; + /** + * 设置点标记的旋转角度 + * @param angle 旋转角度 + */ setAngle(angle: number): void; + /** + * 设置点标记文本标签内容 + * @param label 标签内容 + */ setLabel(label?: Marker.Label): void; + /** + * 获取点标记文本标签内容 + */ getLabel(): Marker.Label | undefined; + /** + * 获取点标记的旋转角度 + */ getAngle(): number; + /** + * 设置点标记的叠加顺序 + * @param index 层级 + */ setzIndex(index: number): void; + /** + * 获取点标记的叠加顺序 + */ getzIndex(): number; + /** + * 设置点标记的显示图标 + * @param content 图标 + */ setIcon(content: string | Icon): void; + /** + * 获取Icon内容 + */ getIcon(): string | Icon | undefined; + /** + * 设置点标记对象是否可拖拽移动 + * @param draggable 是否可拖拽移动 + */ setDraggable(draggable: boolean): void; + /** + * 获取点标记对象是否可拖拽移动 + */ getDraggable(): boolean; + /** + * 设置鼠标悬停时的光标 + * @param cursor 光标 + */ setCursor(cursor: string): void; + /** + * 设置点标记显示内容,可以是HTML要素字符串或者HTML DOM对象 + * @param content 显示内容 + */ setContent(content: string | HTMLElement): void; + /** + * 获取点标记内容 + */ getContent(): string | HTMLElement; + /** + * 以指定的速度,点标记沿指定的路径移动 + * @param path 移动轨迹 + * @param speed 速度 + * @param timingFunction 缓动函数 + * @param circleable 是否循环 + */ moveAlong( path: LngLat[], speed: number, timingFunction?: (t: number) => number, circleable?: boolean ): void; + /** + * 以给定速度移动点标记到指定位置 + * @param lnglat 目标位置 + * @param speed 速度 + * @param timingFunction 缓动函数 + */ moveTo( - path: LocationValue, + lnglat: LocationValue, speed: number, timingFunction?: (t: number) => number ): void; + /** + * 点标记停止动画 + */ stopMove(): void; + /** + * 暂定点标记的动画效果 + */ pauseMove(): boolean; + /** + * 重新开始点标记的动画效果 + */ resumeMove(): boolean; + /** + * 指定目标显示地图 + * @param map 地图 + */ setMap(map: null | Map): void; + /** + * 鼠标滑过点标时的文字提示 + * @param title 提示文字 + */ setTitle(title: string): void; + /** + * 获取点标记的文字提示 + */ getTitle(): string | undefined; + /** + * 设置是否展示在最顶层 + * @param isTop 是否展示在最顶层 + */ setTop(isTop: boolean): void; + /** + * 获取是否展示在最顶层 + */ getTop(): boolean; + /** + * 设置阴影效果 + * @param icon 阴影效果 + */ setShadow(icon?: Icon | string): void; + /** + * 获取阴影图标 + */ getShadow(): Icon | undefined | string; + /** + * 设置可点击区域 + * @param shape 可点击区域 + */ setShape(shape?: MarkerShape): void; + /** + * 获取可点击区域 + */ getShape(): MarkerShape | undefined; } } diff --git a/types/amap-js-api/overlay/markerShape.d.ts b/types/amap-js-api/overlay/markerShape.d.ts index f0d6c39bac..19264f26cf 100644 --- a/types/amap-js-api/overlay/markerShape.d.ts +++ b/types/amap-js-api/overlay/markerShape.d.ts @@ -16,6 +16,10 @@ declare namespace AMap { } class MarkerShape extends EventEmitter { + /** + * Marker点击范围 + * @param options 选项 + */ constructor(options: MarkerShape.Options); } } diff --git a/types/amap-js-api/overlay/overlay.d.ts b/types/amap-js-api/overlay/overlay.d.ts index 1726b39c3e..f90bdb57ed 100644 --- a/types/amap-js-api/overlay/overlay.d.ts +++ b/types/amap-js-api/overlay/overlay.d.ts @@ -13,21 +13,59 @@ declare namespace AMap { mouseup: MapsEvent<'mouseup', I>; } interface Options { + /** + * 所属地图 + */ map?: Map; + /** + * 鼠标悬停时的鼠标样式 + */ cursor?: string; + /** + * 自定义数据 + */ extData?: ExtraData; + /** + * 事件是否穿透到地图 + */ bubble?: boolean; + /** + * 是否支持点击 + */ clickable?: boolean; + /** + * 是否支持拖拽 + */ draggable?: boolean; } } abstract class Overlay extends EventEmitter { constructor(options?: Overlay.Options); + /** + * 显示覆盖物 + */ show(): void; + /** + * 隐藏覆盖物 + */ hide(): void; + /** + * 获取所属地图 + */ getMap(): Map | null | undefined; + /** + * 设置所属地图 + * @param map 地图 + */ setMap(map: Map | null): void; + /** + * 设置自定义数据 + * @param extData 自定义数据 + */ setExtData(extData: ExtraData): void; + /** + * 获取自定义数据 + */ getExtData(): ExtraData | {}; // internal diff --git a/types/amap-js-api/overlay/overlayGroup.d.ts b/types/amap-js-api/overlay/overlayGroup.d.ts index d397505b04..a219e38fcd 100644 --- a/types/amap-js-api/overlay/overlayGroup.d.ts +++ b/types/amap-js-api/overlay/overlayGroup.d.ts @@ -11,20 +11,72 @@ type ReferOverlayOptions = declare namespace AMap { class OverlayGroup extends Overlay { + /** + * 覆盖物集合 + * @param overlays 覆盖物 + */ constructor(overlays?: O | O[]); + /** + * 添加单个覆盖物到集合中,不支持添加重复的覆盖物 + * @param overlay 覆盖物 + */ addOverlay(overlay: O | O[]): this; + /** + * 添加覆盖物数组到集合中,不支持添加重复的覆盖物 + * @param overlay 覆盖物数组 + */ addOverlays(overlay: O | O[]): this; + /** + * 返回当前集合中所有的覆盖物 + */ getOverlays(): O[]; + /** + * 判断传入的覆盖物实例是否在集合中 + * @param overlay 覆盖物 + */ hasOverlay(overlay: O | ((this: null, item: O, index: number, list: O[]) => boolean)): boolean; + /** + * 从集合中删除传入的覆盖物实例 + * @param overlay 覆盖物 + */ removeOverlay(overlay: O | O[]): this; + /** + * 从集合中删除传入的覆盖物实例数组 + * @param overlay 覆盖物数组 + */ removeOverlays(overlay: O | O[]): this; + /** + * 清空集合 + */ clearOverlays(): this; + /** + * 对集合中的覆盖物做迭代操作 + * @param iterator 迭代回调 + * @param context 执行上下文 + */ eachOverlay(iterator: (this: C, overlay: O, index: number, overlays: O[]) => void, context?: C): this; + /** + * 指定集合中里覆盖物的显示地图 + * @param map 地图 + */ setMap(map: null | Map): this; + /** + * 修改覆盖物属性 + * @param options 属性 + */ setOptions(options: ReferOverlayOptions): this; + /** + * 在地图上显示集合中覆盖物 + */ show(): this; + /** + * 在地图上隐藏集合中覆盖物 + */ hide(): this; - + /** + * 查找集合中的覆盖物 + * @param finder 查找回调 + */ getOverlay(finder: ((this: null, item: O, index: number, list: O[]) => boolean) | O): O | null; } } diff --git a/types/amap-js-api/overlay/pathOverlay.d.ts b/types/amap-js-api/overlay/pathOverlay.d.ts index de21aa35a7..d46b23a1c3 100644 --- a/types/amap-js-api/overlay/pathOverlay.d.ts +++ b/types/amap-js-api/overlay/pathOverlay.d.ts @@ -2,19 +2,49 @@ declare namespace AMap { namespace PathOverlay { interface EventMap extends ShapeOverlay.EventMap { } interface Options extends Overlay.Options { + /** + * 是否可见 + */ visible?: boolean; + /** + * 覆盖物层级 + */ zIndex?: number; + /** + * 描边线条颜色 + */ strokeColor?: string; + /** + * 描边线条透明度 + */ strokeOpacity?: number; + /** + * 描边宽度 + */ strokeWeight?: number; + /** + * 描边样式 + */ strokeStyle?: StrokeStyle; + /** + * 虚线间隔 + */ strokeDasharray?: number[]; + /** + * 折线拐点的绘制样式 + */ lineJoin?: StrokeLineJoin; + /** + * 折线两端线帽的绘制样式 + */ lineCap?: StrokeLineCap; } } abstract class PathOverlay extends ShapeOverlay { constructor(options?: PathOverlay.Options); + /** + * 获取范围 + */ getBounds(): Bounds | (this extends Rectangle ? undefined : null); } } diff --git a/types/amap-js-api/overlay/polygon.d.ts b/types/amap-js-api/overlay/polygon.d.ts index 8792e0e135..20a9c3595e 100644 --- a/types/amap-js-api/overlay/polygon.d.ts +++ b/types/amap-js-api/overlay/polygon.d.ts @@ -2,31 +2,77 @@ declare namespace AMap { namespace Polygon { interface EventMap extends PathOverlay.EventMap { } interface Options extends PathOverlay.Options { + /** + * 多边形轮廓线的节点坐标数组 + */ path?: LocationValue[] | LocationValue[][]; + /** + * 多边形填充颜色 + */ fillColor?: string; + /** + * 边形填充透明度 + */ fillOpacity?: number; } interface GetOptionsResult extends ShapeOverlay.GetOptionsResult { + /** + * 多边形填充颜色 + */ fillColor: string; + /** + * 边形填充透明度 + */ fillOpacity: number; + /** + * 多边形轮廓线的节点坐标数组 + */ path: LngLat[] | LngLat[][]; + /** + * 折线拐点的绘制样式 + */ lineJoin: StrokeLineJoin; texture: string; } } class Polygon extends PathOverlay { + /** + * 多边形 + * @param options 选项 + */ constructor(options?: Polygon.Options); + /** + * 设置多边形轮廓线节点数组 + * @param path 轮廓线节点 + */ setPath(path: LocationValue[] | LocationValue[][]): void; + /** + * 获取多边形轮廓线节点数组 + */ getPath(): LngLat[] | LngLat[][]; + /** + * 修改多边形属性 + * @param options 属性 + */ setOptions(options: Polygon.Options): void; + /** + * 获取多边形的属性 + */ getOptions(): Partial< this extends Omit ? Ellipse.GetOptionsResult : this extends Omit ? Rectangle.GetOptionsResult : Polygon.GetOptionsResult >; + /** + * 获取多边形的面积 + */ getArea(): number; + /** + * 判断指定点坐标是否在多边形范围内 + * @param point 坐标 + */ contains(point: LocationValue): boolean; } } diff --git a/types/amap-js-api/overlay/polyline.d.ts b/types/amap-js-api/overlay/polyline.d.ts index 207279b208..c7abfa6331 100644 --- a/types/amap-js-api/overlay/polyline.d.ts +++ b/types/amap-js-api/overlay/polyline.d.ts @@ -2,45 +2,118 @@ declare namespace AMap { namespace Polyline { interface EventMap extends PathOverlay.EventMap { } interface GetOptionsResult extends ShapeOverlay.GetOptionsResult { + /** + * 线条是否带描边 + */ isOutline: boolean; + /** + * 线条描边颜色 + */ outlineColor: string; + /** + * 是否绘制成大地线 + */ geodesic: boolean; + /** + * 折线的节点数组 + */ path: LngLat[]; + /** + * 折线拐点的绘制样式 + */ lineJoin: StrokeLineJoin; + /** + * 折线两端线帽的绘制样式 + */ lineCap: StrokeLineCap; + /** + * 描边的宽度 + */ borderWeight: number; + /** + * 是否延路径显示方向箭头 + */ showDir: boolean; + /** + * 方向箭头颜色 + */ dirColor: string; + /** + * 方向箭头图片 + */ dirImg: string; } interface Options extends PathOverlay.Options { + /** + * 线条是否带描边 + */ isOutline?: boolean; + /** + * 线条描边颜色 + */ outlineColor?: string; + /** + * 是否绘制成大地线 + */ geodesic?: boolean; + /** + * 方向箭头颜色 + */ dirColor?: string; + /** + * 描边的宽度 + */ borderWeight?: number; + /** + * 是否延路径显示方向箭头 + */ showDir?: boolean; + // internal + /** + * 折线的节点数组 + */ path?: LocationValue[]; } } class Polyline extends PathOverlay { + /** + * 折线 + * @param options 选项 + */ constructor(options?: BezierCurve.Options | Polyline.Options); + /** + * 设置组成该折线的节点数组 + * @param path 节点数组 + */ setPath( path: this extends Omit ? Array>> : LocationValue[] ): void; + /** + * 获取折线路径的节点数组 + */ getPath(): this extends Omit ? Array : LngLat[]; + /** + * 获取折线的总长度(单位:米) + */ getLength(): number; + /** + * 设置线的属性 + * @param options 属性 + */ setOptions(options: this extends Omit ? Partial> : Polyline.Options ): void; + /** + * 获取线的属性 + */ getOptions(): Partial>; } } diff --git a/types/amap-js-api/overlay/rectangle.d.ts b/types/amap-js-api/overlay/rectangle.d.ts index 259e2072de..833a46d3dc 100644 --- a/types/amap-js-api/overlay/rectangle.d.ts +++ b/types/amap-js-api/overlay/rectangle.d.ts @@ -5,17 +5,39 @@ declare namespace AMap { } interface Options extends Polygon.Options { + /** + * 矩形的范围 + */ bounds?: Bounds; } type GetOptionsResult = Merge, { + /** + * 路径节点数组 + */ path: LngLat[]; + /** + * 矩形的范围 + */ bounds: Bounds; texture: string; }>; } class Rectangle extends Polygon { + /** + * 矩形 + * @param options 选项 + */ constructor(options?: Rectangle.Options); + /** + * 获取矩形范围 + * @param bounds 矩形的范围 + * @param preventEvent 阻止触发事件 + */ setBounds(bounds: Bounds, preventEvent?: boolean): void; + /** + * 修改矩形属性 + * @param options 属性 + */ setOptions(options: Partial): void; } } diff --git a/types/amap-js-api/overlay/shapeOverlay.d.ts b/types/amap-js-api/overlay/shapeOverlay.d.ts index b8f239aac1..ab07fa3d88 100644 --- a/types/amap-js-api/overlay/shapeOverlay.d.ts +++ b/types/amap-js-api/overlay/shapeOverlay.d.ts @@ -7,24 +7,74 @@ declare namespace AMap { change: Event<'change', { target: I }>; } interface GetOptionsResult { + /** + * 所属地图 + */ map: Map; + /** + * 层级 + */ zIndex: number; + /** + * 线条颜色 + */ strokeColor: string; + /** + * 线条透明度 + */ strokeOpacity: number; + /** + * 线条宽度 + */ strokeWeight: number; + /** + * 线条样式,虚线或者实线 + */ strokeStyle: StrokeStyle; + /** + * 虚线的分段 + */ strokeDasharray: number[]; + /** + * 自定义属性 + */ extData: ExtraData | {}; + /** + * 事件是否穿透到地图 + */ bubble: boolean; + /** + * 是否支持点击 + */ clickable: boolean; } } abstract class ShapeOverlay extends Overlay { + /** + * 设置覆盖物属性 + * @param options 属性 + */ abstract setOptions(options: {}): void; + /** + * 获得属性 + */ abstract getOptions(): {}; + /** + * 获得层级 + */ getzIndex(): number; + /** + * 设置层级 + * @param zIndex 层级 + */ setzIndex(zIndex: number): void; + /** + * 返回可见 + */ getVisible(): boolean; + /** + * 设置是否可以拖拽 + */ setDraggable(draggable: boolean): void; } } diff --git a/types/amap-js-api/overlay/text.d.ts b/types/amap-js-api/overlay/text.d.ts index db15ae08ce..50f9249ad9 100644 --- a/types/amap-js-api/overlay/text.d.ts +++ b/types/amap-js-api/overlay/text.d.ts @@ -4,16 +4,38 @@ declare namespace AMap { type VerticalAlign = 'top' | 'middle' | 'bottom'; interface EventMap extends Marker.EventMap { } interface Options extends Marker.Options { + /** + * 文本内容 + */ text?: string; + /** + * 对齐方式 + */ textAlign?: TextAlign; + verticalAlign?: VerticalAlign; } } class Text extends Marker { + /** + * 纯文本标记 + * @param options 选项 + */ constructor(options?: Text.Options); + /** + * 标记显示的文本内容 + */ getText(): string; + /** + * 修改文本内容 + * @param text 文本内容 + */ setText(text: string): void; + /** + * 设置文本样式 + * @param style 文本样式 + */ setStyle(style: object): void; } } diff --git a/types/amap-js-api/pixel.d.ts b/types/amap-js-api/pixel.d.ts index fab4605b7a..b211e1d88a 100644 --- a/types/amap-js-api/pixel.d.ts +++ b/types/amap-js-api/pixel.d.ts @@ -1,9 +1,28 @@ declare namespace AMap { class Pixel { + /** + * 像素坐标,确定地图上的一个像素点 + * @param x 横轴坐标 + * @param y 纵轴坐标 + * @param round 是否四舍五入 + */ constructor(x: number, y: number, round?: boolean); + /** + * 获得X方向像素坐标 + */ getX(): number; + /** + * 获得Y方向像素坐标 + */ getY(): number; + /** + * 当前像素坐标与传入像素坐标是否相等 + * @param point 目标像素坐标 + */ equals(point: Pixel): boolean; + /** + * 以字符串形式返回像素坐标对象 + */ toString(): string; // internal diff --git a/types/amap-js-api/size.d.ts b/types/amap-js-api/size.d.ts index 12a1e25423..f13c2fff0b 100644 --- a/types/amap-js-api/size.d.ts +++ b/types/amap-js-api/size.d.ts @@ -1,9 +1,24 @@ declare namespace AMap { class Size { + /** + * 地物对象的像素尺寸 + * @param width 宽度像素 + * @param height 长度像素 + */ constructor(width: number, height: number); + /** + * 获得宽度 + */ getWidth(): number; + /** + * 获得高度 + */ getHeight(): number; + /** + * 以字符串形式返回尺寸大小对象 + */ toString(): string; + // internal contains(size: { x: number; y: number }): boolean; } diff --git a/types/amap-js-api/util.d.ts b/types/amap-js-api/util.d.ts index 70b48c31d1..ee275d66b5 100644 --- a/types/amap-js-api/util.d.ts +++ b/types/amap-js-api/util.d.ts @@ -1,25 +1,64 @@ declare namespace AMap { namespace Util { + /** + * 将颜色名转换为16进制RGB颜色值 + * @param colorName 颜色名 + */ function colorNameToHex(colorName: string): string; - + /** + * 将16进制RGB转为rgba(R,G,B,A) + * @param hex 16进制RGB + */ function rgbHex2Rgba(hex: string): string; - + /** + * 将16进制RGBA转为rgba(R,G,B,A) + * @param hex 16进制RGBA + */ function argbHex2Rgba(hex: string): string; - + /** + * 判断一个对象是都为空 + * @param obj 目标对象 + */ function isEmpty(obj: object): boolean; - + /** + * 从数组删除元素 + * @param array 数组 + * @param item 元素 + */ function deleteItemFromArray(array: T[], item: T): T[]; - + /** + * 按索引删除数组元素 + * @param array 数组 + * @param index 索引 + */ function deleteItemFromArrayByIndex(array: T[], index: number): T[]; - + /** + * 返回元素索引 + * @param array 数组 + * @param item 元素 + */ function indexOf(array: T[], item: T): number; - + /** + * 保留小数点后指定位 + * @param floatNumber 数值 + * @param digits 小数点位数 + */ function format(floatNumber: number, digits?: number): number; - + /** + * 判断是否数组 + * @param data 判断对象 + */ function isArray(data: any): data is any[]; - + /** + * 判断参数是否为DOM元素 + * @param data 判断对象 + */ function isDOM(data: any): data is HTMLElement; - + /** + * 判断数组是否包含某个元素 + * @param array 数组 + * @param item 元素 + */ function includes(array: T[], item: T): boolean; function requestIdleCallback(callback: (...args: any[]) => any, options?: { timeout?: number }): number; diff --git a/types/amap-js-api/view2D.d.ts b/types/amap-js-api/view2D.d.ts index d662b4c50e..f246c5c67f 100644 --- a/types/amap-js-api/view2D.d.ts +++ b/types/amap-js-api/view2D.d.ts @@ -1,13 +1,29 @@ declare namespace AMap { namespace View2D { interface Options { + /** + * 地图中心点坐标值 + */ center?: LocationValue; + /** + * 地图顺时针旋转角度 + */ rotation?: number; + /** + * 地图显示的缩放级别 + */ zoom?: number; + /** + * 地图显示的参考坐标系 + */ crs?: 'EPGS3857' | 'EPGS3395' | 'EPGS4326'; } } class View2D extends EventEmitter { + /** + * 二维地图显示视口,用于定义二维地图静态显示属性 + * @param options 选项 + */ constructor(options?: View2D.Options); } } From 397871698113a469ed9fb016b1b5fd1075dc128e Mon Sep 17 00:00:00 2001 From: SardineFish Date: Thu, 21 Mar 2019 00:13:26 +0800 Subject: [PATCH 094/337] Fix module exports in openpgp. --- types/openpgp/index.d.ts | 9436 ++++++++++++------------- types/openpgp/openpgp-tests.ts | 2 +- types/openpgp/ts3.2/index.d.ts | 9583 +++++++++++++------------- types/openpgp/ts3.2/openpgp-tests.ts | 2 +- 4 files changed, 9511 insertions(+), 9512 deletions(-) diff --git a/types/openpgp/index.d.ts b/types/openpgp/index.d.ts index 5d8c4a2cb6..c9a95e8c6a 100644 --- a/types/openpgp/index.d.ts +++ b/types/openpgp/index.d.ts @@ -19,1514 +19,1488 @@ type Integer = number; type Infinity = any; type ReadableStream = any; -export namespace openpgp { - namespace cleartext { +export as namespace openpgp; + +export namespace cleartext { + /** + * Class that represents an OpenPGP cleartext signed message. + * See {@link https://tools.ietf.org/html/rfc4880#section-7} + */ + class CleartextMessage { /** - * Class that represents an OpenPGP cleartext signed message. - * See {@link https://tools.ietf.org/html/rfc4880#section-7} + * @param text The cleartext of the signed message + * @param signature The detached signature or an empty signature for unsigned messages */ - class CleartextMessage { - /** - * @param text The cleartext of the signed message - * @param signature The detached signature or an empty signature for unsigned messages - */ - constructor(text: string, signature: signature.Signature); - - /** - * Returns the key IDs of the keys that signed the cleartext message - * @returns array of keyid objects - */ - getSigningKeyIds(): any[]; - - /** - * Sign the cleartext message - * @param privateKeys private keys with decrypted secret key data for signing - * @param signature (optional) any existing detached signature - * @param date (optional) The creation time of the signature that should be created - * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - * @returns new cleartext message with signed content - */ - sign(privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; - - /** - * Sign the cleartext message - * @param privateKeys private keys with decrypted secret key data for signing - * @param signature (optional) any existing detached signature - * @param date (optional) The creation time of the signature that should be created - * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - * @returns new detached signature of message content - */ - signDetached(privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; - - /** - * Verify signatures of cleartext signed message - * @param keys array of keys to verify signatures - * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @returns list of signer's keyid and validity of signature - */ - verify(keys: any[], date: Date): Promise>; - - /** - * Verify signatures of cleartext signed message - * @param keys array of keys to verify signatures - * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @returns list of signer's keyid and validity of signature - */ - verifyDetached(keys: any[], date: Date): Promise>; - - /** - * Get cleartext - * @returns cleartext of message - */ - getText(): string; - - /** - * Returns ASCII armored text of cleartext signed message - * @returns ASCII armor - */ - armor(): string | ReadableStream; - } + constructor(text: string, signature: signature.Signature); /** - * reads an OpenPGP cleartext signed message and returns a CleartextMessage object - * @param armoredText text to be parsed - * @returns new cleartext message object + * Returns the key IDs of the keys that signed the cleartext message + * @returns array of keyid objects */ - function readArmored(armoredText: string | ReadableStream): CleartextMessage; + getSigningKeyIds(): any[]; /** - * Creates a new CleartextMessage object from text - * @param text + * Sign the cleartext message + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature + * @param date (optional) The creation time of the signature that should be created + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new cleartext message with signed content */ - function fromText(text: string): void; + sign(privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; + + /** + * Sign the cleartext message + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature + * @param date (optional) The creation time of the signature that should be created + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new detached signature of message content + */ + signDetached(privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; + + /** + * Verify signatures of cleartext signed message + * @param keys array of keys to verify signatures + * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + verify(keys: any[], date: Date): Promise>; + + /** + * Verify signatures of cleartext signed message + * @param keys array of keys to verify signatures + * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + verifyDetached(keys: any[], date: Date): Promise>; + + /** + * Get cleartext + * @returns cleartext of message + */ + getText(): string; + + /** + * Returns ASCII armored text of cleartext signed message + * @returns ASCII armor + */ + armor(): string | ReadableStream; } /** - * @see module:config/config + * reads an OpenPGP cleartext signed message and returns a CleartextMessage object + * @param armoredText text to be parsed + * @returns new cleartext message object */ - namespace config { - var prefer_hash_algorithm: any; - - var encryption_cipher: any; - - var compression: any; - - var deflate_level: any; - - /** - * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. - * **NOT INTEROPERABLE WITH OTHER OPENPGP IMPLEMENTATIONS** - * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** - */ - var aead_protect: any; - - /** - * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. - * 0 means we implement a variant of {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00|this IETF draft}. - * 4 means we implement {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04|RFC4880bis-04}. - * Note that this determines how AEAD packets are parsed even when aead_protect is set to false - */ - var aead_protect_version: any; - - /** - * Default Authenticated Encryption with Additional Data (AEAD) encryption mode - * Only has an effect when aead_protect is set to true. - */ - var aead_mode: any; - - /** - * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode - * Only has an effect when aead_protect is set to true. - * Must be an integer value from 0 to 56. - */ - var aead_chunk_size_byte: any; - - /** - * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: - * Iteration Count Byte for S2K (String to Key) - */ - var s2k_iteration_count_byte: any; - - /** - * Use integrity protection for symmetric encryption - */ - var integrity_protect: any; - - var ignore_mdc_error: any; - - var allow_unauthenticated_stream: any; - - var checksum_required: any; - - var rsa_blinding: any; - - /** - * Work-around for rare GPG decryption bug when encrypting with multiple passwords. - * **Slower and slightly less secure** - */ - var password_collision_check: any; - - var revocations_expire: any; - - var use_native: any; - - var min_bytes_for_web_crypto: any; - - var zero_copy: any; - - var debug: any; - - var tolerant: any; - - var show_version: any; - - var show_comment: any; - - var versionstring: any; - - var commentstring: any; - - var keyserver: any; - - var node_store: any; - - /** - * Max userid string length (used for parsing) - */ - var max_userid_length: any; - - namespace localStorage { - class LocalStorage { - /** - * This object is used for storing and retrieving configuration from HTML5 local storage. - */ - constructor(); - - /** - * Reads the config out of the HTML5 local storage - * and initializes the object config. - * if config is null the default config will be used - */ - read(): void; - - /** - * Writes the config to HTML5 local storage - */ - write(): void; - } - } - } - - class LocalStorage { - /** - * This object is used for storing and retrieving configuration from HTML5 local storage. - */ - constructor(); - - /** - * Reads the config out of the HTML5 local storage - * and initializes the object config. - * if config is null the default config will be used - */ - read(): void; - - /** - * Writes the config to HTML5 local storage - */ - write(): void; - } - - + function readArmored(armoredText: string | ReadableStream): CleartextMessage; /** - * @see module:crypto/crypto - * @see module:crypto/signature - * @see module:crypto/public_key - * @see module:crypto/cipher - * @see module:crypto/random - * @see module:crypto/hash + * Creates a new CleartextMessage object from text + * @param text */ + function fromText(text: string): void; +} + +/** + * @see module:config/config + */ +export namespace config { + var prefer_hash_algorithm: any; + + var encryption_cipher: any; + + var compression: any; + + var deflate_level: any; + + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * **NOT INTEROPERABLE WITH OTHER OPENPGP IMPLEMENTATIONS** + * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** + */ + var aead_protect: any; + + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * 0 means we implement a variant of {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00|this IETF draft}. + * 4 means we implement {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04|RFC4880bis-04}. + * Note that this determines how AEAD packets are parsed even when aead_protect is set to false + */ + var aead_protect_version: any; + + /** + * Default Authenticated Encryption with Additional Data (AEAD) encryption mode + * Only has an effect when aead_protect is set to true. + */ + var aead_mode: any; + + /** + * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode + * Only has an effect when aead_protect is set to true. + * Must be an integer value from 0 to 56. + */ + var aead_chunk_size_byte: any; + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: + * Iteration Count Byte for S2K (String to Key) + */ + var s2k_iteration_count_byte: any; + + /** + * Use integrity protection for symmetric encryption + */ + var integrity_protect: any; + + var ignore_mdc_error: any; + + var allow_unauthenticated_stream: any; + + var checksum_required: any; + + var rsa_blinding: any; + + /** + * Work-around for rare GPG decryption bug when encrypting with multiple passwords. + * **Slower and slightly less secure** + */ + var password_collision_check: any; + + var revocations_expire: any; + + var use_native: any; + + var min_bytes_for_web_crypto: any; + + var zero_copy: any; + + var debug: any; + + var tolerant: any; + + var show_version: any; + + var show_comment: any; + + var versionstring: any; + + var commentstring: any; + + var keyserver: any; + + var node_store: any; + + /** + * Max userid string length (used for parsing) + */ + var max_userid_length: any; + + namespace localStorage { + class LocalStorage { + /** + * This object is used for storing and retrieving configuration from HTML5 local storage. + */ + constructor(); + + /** + * Reads the config out of the HTML5 local storage + * and initializes the object config. + * if config is null the default config will be used + */ + read(): void; + + /** + * Writes the config to HTML5 local storage + */ + write(): void; + } + } +} + +export class LocalStorage { + /** + * This object is used for storing and retrieving configuration from HTML5 local storage. + */ + constructor(); + + /** + * Reads the config out of the HTML5 local storage + * and initializes the object config. + * if config is null the default config will be used + */ + read(): void; + + /** + * Writes the config to HTML5 local storage + */ + write(): void; +} + + + +/** + * @see module:crypto/crypto + * @see module:crypto/signature + * @see module:crypto/public_key + * @see module:crypto/cipher + * @see module:crypto/random + * @see module:crypto/hash + */ +export namespace crypto { + /** + * @see module:crypto/public_key/elliptic/ecdh + */ + namespace aes_kw { + /** + * AES key wrap + * @param key + * @param data + * @returns + */ + function wrap(key: string, data: string): Uint8Array; + + /** + * AES key unwrap + * @param key + * @param data + * @returns + * @throws + */ + function unwrap(key: string, data: string): Uint8Array; + } + + namespace cfb { + function encrypt(algo: any, key: any, plaintext: any, iv: any): any + function decrypt(algo: any, key: any, ciphertext: any, iv: any): Promise + } + + namespace cipher { + /** + * AES-128 encryption and decryption (ID 7) + * @param key 128-bit key + * @see + * @see + * @returns + */ + function aes128(key: string): object; + + /** + * AES-128 Block Cipher (ID 8) + * @param key 192-bit key + * @see + * @see + * @returns + */ + function aes192(key: string): object; + + /** + * AES-128 Block Cipher (ID 9) + * @param key 256-bit key + * @see + * @see + * @returns + */ + function aes256(key: string): object; + + /** + * Triple DES Block Cipher (ID 2) + * @param key 192-bit key + * @see + * @returns + */ + function tripledes(key: string): object; + + /** + * CAST-128 Block Cipher (ID 3) + * @param key 128-bit key + * @see + * @returns + */ + function cast5(key: string): object; + + /** + * Twofish Block Cipher (ID 10) + * @param key 256-bit key + * @see + * @returns + */ + function twofish(key: string): object; + + /** + * Blowfish Block Cipher (ID 4) + * @param key 128-bit key + * @see + * @returns + */ + function blowfish(key: string): object; + + /** + * Not implemented + * @throws + */ + function idea(): void; + } + + namespace cmac { + /** + * This implementation of CMAC is based on the description of OMAC in + * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that + * document: + * We have made a small modification to the OMAC algorithm as it was + * originally presented, changing one of its two constants. + * Specifically, the constant 4 at line 85 was the constant 1/2 (the + * multiplicative inverse of 2) in the original definition of OMAC [14]. + * The OMAC authors indicate that they will promulgate this modification + * [15], which slightly simplifies implementations. + */ + const blockLength: any; + + /** + * xor `padding` into the end of `data`. This function implements "the + * operation xor→ [which] xors the shorter string into the end of longer + * one". Since data is always as least as long as padding, we can + * simplify the implementation. + * @param data + * @param padding + */ + function rightXorMut(data: Uint8Array, padding: Uint8Array): void; + } + namespace crypto { /** - * @see module:crypto/public_key/elliptic/ecdh + * Encrypts data using specified algorithm and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param algo Public key algorithm + * @param pub_params Algorithm-specific public key parameters + * @param data Data to be encrypted as MPI + * @param fingerprint Recipient fingerprint + * @returns encrypted session key parameters + */ + function publicKeyEncrypt(algo: enums.publicKey, pub_params: Array, data: type.mpi.MPI, fingerprint: string): any[]; + + /** + * Decrypts data using specified algorithm and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param algo Public key algorithm + * @param key_params Algorithm-specific public, private key parameters + * @param data_params encrypted session key parameters + * @param fingerprint Recipient fingerprint + * @returns An MPI containing the decrypted data + */ + function publicKeyDecrypt(algo: enums.publicKey, key_params: Array, data_params: Array, fingerprint: string): type.mpi.MPI; + + /** + * Returns the types comprising the private key of an algorithm + * @param algo The public key algorithm + * @returns The array of types + */ + function getPrivKeyParamTypes(algo: string): any[]; + + /** + * Returns the types comprising the public key of an algorithm + * @param algo The public key algorithm + * @returns The array of types + */ + function getPubKeyParamTypes(algo: string): any[]; + + /** + * Returns the types comprising the encrypted session key of an algorithm + * @param algo The public key algorithm + * @returns The array of types + */ + function getEncSessionKeyParamTypes(algo: string): any[]; + + /** + * Generate algorithm-specific key parameters + * @param algo The public key algorithm + * @param bits Bit length for RSA keys + * @param oid Object identifier for ECC keys + * @returns The array of parameters + */ + function generateParams(algo: string, bits: Integer, oid: type.oid.OID): any[]; + + /** + * Generates a random byte prefix for the specified algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param algo Symmetric encryption algorithm + * @returns Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. + */ + function getPrefixRandom(algo: enums.symmetric): Uint8Array; + + /** + * Generating a session key for the specified symmetric algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param algo Symmetric encryption algorithm + * @returns Random bytes as a string to be used as a key + */ + function generateSessionKey(algo: enums.symmetric): Uint8Array; + } + + namespace eax { + /** + * Class to en/decrypt using EAX mode. + * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' + * @param key The encryption key + */ + function EAX(cipher: string, key: Uint8Array): void; + + /** + * Encrypt plaintext input. + * @param plaintext The cleartext input to be encrypted + * @param nonce The nonce (16 bytes) + * @param adata Associated data to sign + * @returns The ciphertext output + */ + function encrypt(plaintext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + + /** + * Decrypt ciphertext input. + * @param ciphertext The ciphertext input to be decrypted + * @param nonce The nonce (16 bytes) + * @param adata Associated data to verify + * @returns The plaintext output + */ + function decrypt(ciphertext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + } + + namespace gcm { + /** + * Class to en/decrypt using GCM mode. + * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' + * @param key The encryption key + */ + function GCM(cipher: string, key: Uint8Array): void; + } + + /** + * @see + * @see */ - namespace aes_kw { + namespace hash { + /** + * @see module:md5 + */ + var md5: any; + + /** + * @see asmCrypto + */ + var sha1: any; + + /** + * @see hash.js + */ + var sha224: any; + + /** + * @see asmCrypto + */ + var sha256: any; + + /** + * @see hash.js + */ + var sha384: any; + + /** + * @see asmCrypto + */ + var sha512: any; + + /** + * @see hash.js + */ + var ripemd: any; + + /** + * Create a hash on the specified data using the specified algorithm + * @param algo Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @param data Data to be hashed + * @returns hash value + */ + function digest(algo: enums.hash, data: Uint8Array): Promise; + + /** + * Returns the hash size in bytes of the specified hash algorithm type + * @param algo Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @returns Size in bytes of the resulting hash + */ + function getHashByteLength(algo: enums.hash): Integer; + } + + /** + * @see module:packet.PublicKeyEncryptedSessionKey + */ + namespace pkcs5 { + /** + * Add pkcs5 padding to a text. + * @param msg Text to add padding + * @returns Text with padding added + */ + function encode(msg: string): string; + + /** + * Remove pkcs5 padding from a string. + * @param msg Text to remove padding from + * @returns Text with padding removed + */ + function decode(msg: string): string; + } + + namespace ocb { + /** + * Class to en/decrypt using OCB mode. + * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' + * @param key The encryption key + */ + function OCB(cipher: string, key: Uint8Array): void; + + /** + * Encrypt plaintext input. + * @param plaintext The cleartext input to be encrypted + * @param nonce The nonce (15 bytes) + * @param adata Associated data to sign + * @returns The ciphertext output + */ + function encrypt(plaintext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + + /** + * Decrypt ciphertext input. + * @param ciphertext The ciphertext input to be decrypted + * @param nonce The nonce (15 bytes) + * @param adata Associated data to sign + * @returns The ciphertext output + */ + function decrypt(ciphertext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + } + + /** + * @see module:crypto/public_key/rsa + * @see module:crypto/public_key/elliptic/ecdh + * @see module:packet.PublicKeyEncryptedSessionKey + */ + namespace pkcs1 { + namespace eme { /** - * AES key wrap - * @param key - * @param data - * @returns + * Create a EME-PKCS1-v1_5 padded message + * @see + * @param M message to be encoded + * @param k the length in octets of the key modulus + * @returns EME-PKCS1 padded message */ - function wrap(key: string, data: string): Uint8Array; + function encode(M: string, k: Integer): Promise; /** - * AES key unwrap - * @param key - * @param data - * @returns - * @throws + * Decode a EME-PKCS1-v1_5 padded message + * @see + * @param EM encoded message, an octet string + * @returns message, an octet string */ - function unwrap(key: string, data: string): Uint8Array; + function decode(EM: string): string; } - namespace cfb { - function encrypt(algo: any, key: any, plaintext: any, iv: any): any - function decrypt(algo: any, key: any, ciphertext: any, iv: any): Promise - } - - namespace cipher { + namespace emsa { /** - * AES-128 encryption and decryption (ID 7) - * @param key 128-bit key + * Create a EMSA-PKCS1-v1_5 padded message * @see - * @see - * @returns + * @param algo Hash algorithm type used + * @param hashed message to be encoded + * @param emLen intended length in octets of the encoded message + * @returns encoded message */ - function aes128(key: string): object; - - /** - * AES-128 Block Cipher (ID 8) - * @param key 192-bit key - * @see - * @see - * @returns - */ - function aes192(key: string): object; - - /** - * AES-128 Block Cipher (ID 9) - * @param key 256-bit key - * @see - * @see - * @returns - */ - function aes256(key: string): object; - - /** - * Triple DES Block Cipher (ID 2) - * @param key 192-bit key - * @see - * @returns - */ - function tripledes(key: string): object; - - /** - * CAST-128 Block Cipher (ID 3) - * @param key 128-bit key - * @see - * @returns - */ - function cast5(key: string): object; - - /** - * Twofish Block Cipher (ID 10) - * @param key 256-bit key - * @see - * @returns - */ - function twofish(key: string): object; - - /** - * Blowfish Block Cipher (ID 4) - * @param key 128-bit key - * @see - * @returns - */ - function blowfish(key: string): object; - - /** - * Not implemented - * @throws - */ - function idea(): void; - } - - namespace cmac { - /** - * This implementation of CMAC is based on the description of OMAC in - * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that - * document: - * We have made a small modification to the OMAC algorithm as it was - * originally presented, changing one of its two constants. - * Specifically, the constant 4 at line 85 was the constant 1/2 (the - * multiplicative inverse of 2) in the original definition of OMAC [14]. - * The OMAC authors indicate that they will promulgate this modification - * [15], which slightly simplifies implementations. - */ - const blockLength: any; - - /** - * xor `padding` into the end of `data`. This function implements "the - * operation xor→ [which] xors the shorter string into the end of longer - * one". Since data is always as least as long as padding, we can - * simplify the implementation. - * @param data - * @param padding - */ - function rightXorMut(data: Uint8Array, padding: Uint8Array): void; - } - - namespace crypto { - /** - * Encrypts data using specified algorithm and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. - * @param algo Public key algorithm - * @param pub_params Algorithm-specific public key parameters - * @param data Data to be encrypted as MPI - * @param fingerprint Recipient fingerprint - * @returns encrypted session key parameters - */ - function publicKeyEncrypt(algo: enums.publicKey, pub_params: Array, data: type.mpi.MPI, fingerprint: string): any[]; - - /** - * Decrypts data using specified algorithm and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. - * @param algo Public key algorithm - * @param key_params Algorithm-specific public, private key parameters - * @param data_params encrypted session key parameters - * @param fingerprint Recipient fingerprint - * @returns An MPI containing the decrypted data - */ - function publicKeyDecrypt(algo: enums.publicKey, key_params: Array, data_params: Array, fingerprint: string): type.mpi.MPI; - - /** - * Returns the types comprising the private key of an algorithm - * @param algo The public key algorithm - * @returns The array of types - */ - function getPrivKeyParamTypes(algo: string): any[]; - - /** - * Returns the types comprising the public key of an algorithm - * @param algo The public key algorithm - * @returns The array of types - */ - function getPubKeyParamTypes(algo: string): any[]; - - /** - * Returns the types comprising the encrypted session key of an algorithm - * @param algo The public key algorithm - * @returns The array of types - */ - function getEncSessionKeyParamTypes(algo: string): any[]; - - /** - * Generate algorithm-specific key parameters - * @param algo The public key algorithm - * @param bits Bit length for RSA keys - * @param oid Object identifier for ECC keys - * @returns The array of parameters - */ - function generateParams(algo: string, bits: Integer, oid: type.oid.OID): any[]; - - /** - * Generates a random byte prefix for the specified algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param algo Symmetric encryption algorithm - * @returns Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. - */ - function getPrefixRandom(algo: enums.symmetric): Uint8Array; - - /** - * Generating a session key for the specified symmetric algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param algo Symmetric encryption algorithm - * @returns Random bytes as a string to be used as a key - */ - function generateSessionKey(algo: enums.symmetric): Uint8Array; - } - - namespace eax { - /** - * Class to en/decrypt using EAX mode. - * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' - * @param key The encryption key - */ - function EAX(cipher: string, key: Uint8Array): void; - - /** - * Encrypt plaintext input. - * @param plaintext The cleartext input to be encrypted - * @param nonce The nonce (16 bytes) - * @param adata Associated data to sign - * @returns The ciphertext output - */ - function encrypt(plaintext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; - - /** - * Decrypt ciphertext input. - * @param ciphertext The ciphertext input to be decrypted - * @param nonce The nonce (16 bytes) - * @param adata Associated data to verify - * @returns The plaintext output - */ - function decrypt(ciphertext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; - } - - namespace gcm { - /** - * Class to en/decrypt using GCM mode. - * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' - * @param key The encryption key - */ - function GCM(cipher: string, key: Uint8Array): void; + function encode(algo: Integer, hashed: Uint8Array, emLen: Integer): string; } /** - * @see + * ASN1 object identifiers for hashes * @see */ - namespace hash { + const hash_headers: any; + } + + namespace public_key { + namespace dsa { /** - * @see module:md5 + * DSA Sign function + * @param hash_algo + * @param hashed + * @param g + * @param p + * @param q + * @param x + * @returns */ - var md5: any; + function sign(hash_algo: Integer, hashed: Uint8Array, g: BN, p: BN, q: BN, x: BN): object; /** - * @see asmCrypto + * DSA Verify function + * @param hash_algo + * @param r + * @param s + * @param hashed + * @param g + * @param p + * @param q + * @param y + * @returns BN */ - var sha1: any; + function verify(hash_algo: Integer, r: BN, s: BN, hashed: Uint8Array, g: BN, p: BN, q: BN, y: BN): any; + } + + namespace elgamal { + /** + * ElGamal Encryption function + * @param m + * @param p + * @param g + * @param y + * @returns + */ + function encrypt(m: BN, p: BN, g: BN, y: BN): object; /** - * @see hash.js + * ElGamal Encryption function + * @param c1 + * @param c2 + * @param p + * @param x + * @returns BN */ - var sha224: any; - - /** - * @see asmCrypto - */ - var sha256: any; - - /** - * @see hash.js - */ - var sha384: any; - - /** - * @see asmCrypto - */ - var sha512: any; - - /** - * @see hash.js - */ - var ripemd: any; - - /** - * Create a hash on the specified data using the specified algorithm - * @param algo Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @param data Data to be hashed - * @returns hash value - */ - function digest(algo: enums.hash, data: Uint8Array): Promise; - - /** - * Returns the hash size in bytes of the specified hash algorithm type - * @param algo Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @returns Size in bytes of the resulting hash - */ - function getHashByteLength(algo: enums.hash): Integer; + function decrypt(c1: BN, c2: BN, p: BN, x: BN): any; } /** - * @see module:packet.PublicKeyEncryptedSessionKey - */ - namespace pkcs5 { - /** - * Add pkcs5 padding to a text. - * @param msg Text to add padding - * @returns Text with padding added - */ - function encode(msg: string): string; - - /** - * Remove pkcs5 padding from a string. - * @param msg Text to remove padding from - * @returns Text with padding removed - */ - function decode(msg: string): string; - } - - namespace ocb { - /** - * Class to en/decrypt using OCB mode. - * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' - * @param key The encryption key - */ - function OCB(cipher: string, key: Uint8Array): void; - - /** - * Encrypt plaintext input. - * @param plaintext The cleartext input to be encrypted - * @param nonce The nonce (15 bytes) - * @param adata Associated data to sign - * @returns The ciphertext output - */ - function encrypt(plaintext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; - - /** - * Decrypt ciphertext input. - * @param ciphertext The ciphertext input to be decrypted - * @param nonce The nonce (15 bytes) - * @param adata Associated data to sign - * @returns The ciphertext output - */ - function decrypt(ciphertext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; - } - - /** - * @see module:crypto/public_key/rsa + * @see module:crypto/public_key/elliptic/curve * @see module:crypto/public_key/elliptic/ecdh - * @see module:packet.PublicKeyEncryptedSessionKey + * @see module:crypto/public_key/elliptic/ecdsa + * @see module:crypto/public_key/elliptic/eddsa */ - namespace pkcs1 { - namespace eme { - /** - * Create a EME-PKCS1-v1_5 padded message - * @see - * @param M message to be encoded - * @param k the length in octets of the key modulus - * @returns EME-PKCS1 padded message - */ - function encode(M: string, k: Integer): Promise; - - /** - * Decode a EME-PKCS1-v1_5 padded message - * @see - * @param EM encoded message, an octet string - * @returns message, an octet string - */ - function decode(EM: string): string; - } - - namespace emsa { - /** - * Create a EMSA-PKCS1-v1_5 padded message - * @see - * @param algo Hash algorithm type used - * @param hashed message to be encoded - * @param emLen intended length in octets of the encoded message - * @returns encoded message - */ - function encode(algo: Integer, hashed: Uint8Array, emLen: Integer): string; - } - - /** - * ASN1 object identifiers for hashes - * @see - */ - const hash_headers: any; - } - - namespace public_key { - namespace dsa { - /** - * DSA Sign function - * @param hash_algo - * @param hashed - * @param g - * @param p - * @param q - * @param x - * @returns - */ - function sign(hash_algo: Integer, hashed: Uint8Array, g: BN, p: BN, q: BN, x: BN): object; - - /** - * DSA Verify function - * @param hash_algo - * @param r - * @param s - * @param hashed - * @param g - * @param p - * @param q - * @param y - * @returns BN - */ - function verify(hash_algo: Integer, r: BN, s: BN, hashed: Uint8Array, g: BN, p: BN, q: BN, y: BN): any; - } - - namespace elgamal { - /** - * ElGamal Encryption function - * @param m - * @param p - * @param g - * @param y - * @returns - */ - function encrypt(m: BN, p: BN, g: BN, y: BN): object; - - /** - * ElGamal Encryption function - * @param c1 - * @param c2 - * @param p - * @param x - * @returns BN - */ - function decrypt(c1: BN, c2: BN, p: BN, x: BN): any; - } - - /** - * @see module:crypto/public_key/elliptic/curve - * @see module:crypto/public_key/elliptic/ecdh - * @see module:crypto/public_key/elliptic/ecdsa - * @see module:crypto/public_key/elliptic/eddsa - */ - namespace elliptic { - namespace curve { - class Curve { - } - } - - namespace ecdh { - /** - * Generate ECDHE ephemeral key and secret from public key - * @param curve Elliptic curve object - * @param Q Recipient public key - * @returns Returns public part of ephemeral key and generated ephemeral secret - */ - function genPublicEphemeralKey(curve: curve.Curve, Q: Uint8Array): Promise<{ V: Uint8Array, S: BN }>; - - /** - * Encrypt and wrap a session key - * @param oid Elliptic curve object identifier - * @param cipher_algo Symmetric cipher to use - * @param hash_algo Hash algorithm to use - * @param m Value derived from session key (RFC 6637) - * @param Q Recipient public key - * @param fingerprint Recipient fingerprint - * @returns Returns public part of ephemeral key and encoded session key - */ - function encrypt(oid: type.oid.OID, cipher_algo: enums.symmetric, hash_algo: enums.hash, m: type.mpi.MPI, Q: Uint8Array, fingerprint: string): Promise<{ V: BN, C: BN }>; - - /** - * Generate ECDHE secret from private key and public part of ephemeral key - * @param curve Elliptic curve object - * @param V Public part of ephemeral key - * @param d Recipient private key - * @returns Generated ephemeral secret - */ - function genPrivateEphemeralKey(curve: curve.Curve, V: Uint8Array, d: Uint8Array): Promise; - - /** - * Decrypt and unwrap the value derived from session key - * @param oid Elliptic curve object identifier - * @param cipher_algo Symmetric cipher to use - * @param hash_algo Hash algorithm to use - * @param V Public part of ephemeral key - * @param C Encrypted and wrapped value derived from session key - * @param d Recipient private key - * @param fingerprint Recipient fingerprint - * @returns Value derived from session - */ - function decrypt(oid: type.oid.OID, cipher_algo: enums.symmetric, hash_algo: enums.hash, V: Uint8Array, C: Uint8Array, d: Uint8Array, fingerprint: string): Promise; - } - - namespace ecdsa { - /** - * Sign a message using the provided key - * @param oid Elliptic curve object identifier - * @param hash_algo Hash algorithm used to sign - * @param m Message to sign - * @param d Private key used to sign the message - * @param hashed The hashed message - * @returns Signature of the message - */ - function sign(oid: type.oid.OID, hash_algo: enums.hash, m: Uint8Array, d: Uint8Array, hashed: Uint8Array): object; - - /** - * Verifies if a signature is valid for a message - * @param oid Elliptic curve object identifier - * @param hash_algo Hash algorithm used in the signature - * @param signature Signature to verify - * @param m Message to verify - * @param Q Public key used to verify the message - * @param hashed The hashed message - * @returns - */ - function verify(oid: type.oid.OID, hash_algo: enums.hash, signature: object, m: Uint8Array, Q: Uint8Array, hashed: Uint8Array): boolean; - } - - namespace eddsa { - /** - * Sign a message using the provided keygit - * @param oid Elliptic curve object identifier - * @param hash_algo Hash algorithm used to sign - * @param m Message to sign - * @param d Private key used to sign - * @param hashed The hashed message - * @returns Signature of the message - */ - function sign(oid: type.oid.OID, hash_algo: enums.hash, m: Uint8Array, d: Uint8Array, hashed: Uint8Array): object; - - /** - * Verifies if a signature is valid for a message - * @param oid Elliptic curve object identifier - * @param hash_algo Hash algorithm used in the signature - * @param signature Signature to verify the message - * @param m Message to verify - * @param Q Public key used to verify the message - * @param hashed The hashed message - * @returns - */ - function verify(oid: type.oid.OID, hash_algo: enums.hash, signature: object, m: Uint8Array, Q: Uint8Array, hashed: Uint8Array): boolean; - } - - namespace key { - class KeyPair { - } + namespace elliptic { + namespace curve { + class Curve { } } - namespace prime { + namespace ecdh { /** - * Probabilistic random number generator - * @param bits Bit length of the prime - * @param e Optional RSA exponent to check against the prime - * @param k Optional number of iterations of Miller-Rabin test - * @returns BN + * Generate ECDHE ephemeral key and secret from public key + * @param curve Elliptic curve object + * @param Q Recipient public key + * @returns Returns public part of ephemeral key and generated ephemeral secret */ - function randomProbablePrime(bits: Integer, e: BN, k: Integer): any; + function genPublicEphemeralKey(curve: curve.Curve, Q: Uint8Array): Promise<{ V: Uint8Array, S: BN }>; /** - * Probabilistic primality testing - * @param n Number to test - * @param e Optional RSA exponent to check against the prime - * @param k Optional number of iterations of Miller-Rabin test - * @returns + * Encrypt and wrap a session key + * @param oid Elliptic curve object identifier + * @param cipher_algo Symmetric cipher to use + * @param hash_algo Hash algorithm to use + * @param m Value derived from session key (RFC 6637) + * @param Q Recipient public key + * @param fingerprint Recipient fingerprint + * @returns Returns public part of ephemeral key and encoded session key */ - function isProbablePrime(n: BN, e: BN, k: Integer): boolean; + function encrypt(oid: type.oid.OID, cipher_algo: enums.symmetric, hash_algo: enums.hash, m: type.mpi.MPI, Q: Uint8Array, fingerprint: string): Promise<{ V: BN, C: BN }>; /** - * Tests whether n is probably prime or not using Fermat's test with b = 2. - * Fails if b^(n-1) mod n === 1. - * @param n Number to test - * @param b Optional Fermat test base - * @returns + * Generate ECDHE secret from private key and public part of ephemeral key + * @param curve Elliptic curve object + * @param V Public part of ephemeral key + * @param d Recipient private key + * @returns Generated ephemeral secret */ - function fermat(n: BN, b: Integer): boolean; + function genPrivateEphemeralKey(curve: curve.Curve, V: Uint8Array, d: Uint8Array): Promise; /** - * Tests whether n is probably prime or not using the Miller-Rabin test. - * See HAC Remark 4.28. - * @param n Number to test - * @param k Optional number of iterations of Miller-Rabin test - * @param rand Optional function to generate potential witnesses - * @returns + * Decrypt and unwrap the value derived from session key + * @param oid Elliptic curve object identifier + * @param cipher_algo Symmetric cipher to use + * @param hash_algo Hash algorithm to use + * @param V Public part of ephemeral key + * @param C Encrypted and wrapped value derived from session key + * @param d Recipient private key + * @param fingerprint Recipient fingerprint + * @returns Value derived from session */ - function millerRabin(n: BN, k: Integer, rand: Function): boolean; + function decrypt(oid: type.oid.OID, cipher_algo: enums.symmetric, hash_algo: enums.hash, V: Uint8Array, C: Uint8Array, d: Uint8Array, fingerprint: string): Promise; } - namespace rsa { + namespace ecdsa { /** - * Create signature - * @param m message - * @param n RSA public modulus - * @param e RSA public exponent - * @param d RSA private exponent - * @returns RSA Signature + * Sign a message using the provided key + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used to sign + * @param m Message to sign + * @param d Private key used to sign the message + * @param hashed The hashed message + * @returns Signature of the message */ - function sign(m: BN, n: BN, e: BN, d: BN): BN; + function sign(oid: type.oid.OID, hash_algo: enums.hash, m: Uint8Array, d: Uint8Array, hashed: Uint8Array): object; /** - * Verify signature - * @param s signature - * @param n RSA public modulus - * @param e RSA public exponent + * Verifies if a signature is valid for a message + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used in the signature + * @param signature Signature to verify + * @param m Message to verify + * @param Q Public key used to verify the message + * @param hashed The hashed message * @returns */ - function verify(s: BN, n: BN, e: BN): BN; + function verify(oid: type.oid.OID, hash_algo: enums.hash, signature: object, m: Uint8Array, Q: Uint8Array, hashed: Uint8Array): boolean; + } + + namespace eddsa { + /** + * Sign a message using the provided keygit + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used to sign + * @param m Message to sign + * @param d Private key used to sign + * @param hashed The hashed message + * @returns Signature of the message + */ + function sign(oid: type.oid.OID, hash_algo: enums.hash, m: Uint8Array, d: Uint8Array, hashed: Uint8Array): object; /** - * Encrypt message - * @param m message - * @param n RSA public modulus - * @param e RSA public exponent - * @returns RSA Ciphertext + * Verifies if a signature is valid for a message + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used in the signature + * @param signature Signature to verify the message + * @param m Message to verify + * @param Q Public key used to verify the message + * @param hashed The hashed message + * @returns */ - function encrypt(m: BN, n: BN, e: BN): BN; + function verify(oid: type.oid.OID, hash_algo: enums.hash, signature: object, m: Uint8Array, Q: Uint8Array, hashed: Uint8Array): boolean; + } - /** - * Decrypt RSA message - * @param m message - * @param n RSA public modulus - * @param e RSA public exponent - * @param d RSA private exponent - * @param p RSA private prime p - * @param q RSA private prime q - * @param u RSA private inverse of prime q - * @returns RSA Plaintext - */ - function decrypt(m: BN, n: BN, e: BN, d: BN, p: BN, q: BN, u: BN): BN; - - /** - * Generate a new random private key B bits long with public exponent E. - * When possible, webCrypto is used. Otherwise, primes are generated using - * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. - * @see module:crypto/public_key/prime - * @param B RSA bit length - * @param E RSA public exponent in hex string - * @returns RSA public modulus, RSA public exponent, RSA private exponent, - * RSA private prime p, RSA private prime q, u = q ** -1 mod p - */ - function generate(B: Integer, E: string): object; + namespace key { + class KeyPair { + } } } - namespace random { + namespace prime { /** - * Retrieve secure random byte array of the specified length - * @param length Length in bytes to generate - * @returns Random byte array + * Probabilistic random number generator + * @param bits Bit length of the prime + * @param e Optional RSA exponent to check against the prime + * @param k Optional number of iterations of Miller-Rabin test + * @returns BN */ - function getRandomBytes(length: Integer): Uint8Array; + function randomProbablePrime(bits: Integer, e: BN, k: Integer): any; /** - * Create a secure random MPI that is greater than or equal to min and less than max. - * @param min Lower bound, included - * @param max Upper bound, excluded - * @returns Random MPI - */ - function getRandomBN(min: type.mpi.MPI, max: type.mpi.MPI): BN; - - /** - * Buffer for secure random numbers - */ - function RandomBuffer(): void; - } - - namespace signature { - /** - * Verifies the signature provided for data using specified algorithms and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param algo Public key algorithm - * @param hash_algo Hash algorithm - * @param msg_MPIs Algorithm-specific signature parameters - * @param pub_MPIs Algorithm-specific public key parameters - * @param data Data for which the signature was created - * @param hashed The hashed data - * @returns True if signature is valid - */ - function verify(algo: enums.publicKey, hash_algo: enums.hash, msg_MPIs: type.mpi.MPI[], pub_MPIs: type.mpi.MPI[], data: Uint8Array, hashed: Uint8Array): boolean; - - /** - * Creates a signature on data using specified algorithms and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param algo Public key algorithm - * @param hash_algo Hash algorithm - * @param key_params Algorithm-specific public and private key parameters - * @param data Data to be signed - * @param hashed The hashed data - * @returns Signature - */ - function sign(algo: enums.publicKey, hash_algo: enums.hash, key_params: type.mpi.MPI[], data: Uint8Array, hashed: Uint8Array): Uint8Array; - } - } - - namespace eme { - /** - * Create a EME-PKCS1-v1_5 padded message - * @see - * @param M message to be encoded - * @param k the length in octets of the key modulus - * @returns EME-PKCS1 padded message - */ - function encode(M: string, k: Integer): Promise; - - /** - * Decode a EME-PKCS1-v1_5 padded message - * @see - * @param EM encoded message, an octet string - * @returns message, an octet string - */ - function decode(EM: string): string; - } - - namespace emsa { - /** - * Create a EMSA-PKCS1-v1_5 padded message - * @see - * @param algo Hash algorithm type used - * @param hashed message to be encoded - * @param emLen intended length in octets of the encoded message - * @returns encoded message - */ - function encode(algo: Integer, hashed: Uint8Array, emLen: Integer): string; - } - - namespace encoding { - namespace armor { - /** - * Add additional information to the armor version of an OpenPGP binary - * packet block. - * @author Alex - * @version 2011-12-16 - * @param customComment (optional) additional comment to add to the armored string - * @returns The header information - */ - function addheader(customComment: string): string; - - /** - * Calculates a checksum over the given data and returns it base64 encoded - * @param data Data to create a CRC-24 checksum for - * @returns Base64 encoded checksum - */ - function getCheckSum(data: string | ReadableStream): string | ReadableStream; - - /** - * Internal function to calculate a CRC-24 checksum over a given string (data) - * @param data Data to create a CRC-24 checksum for - * @returns The CRC-24 checksum - */ - function createcrc24(data: string | ReadableStream): Uint8Array | ReadableStream; - - /** - * Splits a message into two parts, the body and the checksum. This is an internal function - * @param text OpenPGP armored message part - * @returns An object with attribute "body" containing the body - * and an attribute "checksum" containing the checksum. - */ - function splitChecksum(text: string): object; - - /** - * DeArmor an OpenPGP armored message; verify the checksum and return - * the encoded bytes - * @param text OpenPGP armored message - * @returns An object with attribute "text" containing the message text, - * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type - */ - function dearmor(text: string): Promise; - - /** - * Armor an OpenPGP binary packet block - * @param messagetype type of the message - * @param body - * @param partindex - * @param parttotal - * @param customComment (optional) additional comment to add to the armored string - * @returns Armored text - */ - function armor(messagetype: Integer, body: any, partindex: Integer, parttotal: Integer, customComment?: string): string | ReadableStream; - } - - namespace base64 { - /** - * Convert binary array to radix-64 - * @param t Uint8Array to convert - * @param u if true, output is URL-safe - * @returns radix-64 version of input string - */ - function s2r(t: Uint8Array | ReadableStream, u?: boolean): string | ReadableStream; - - /** - * Convert radix-64 to binary array - * @param t radix-64 string to convert - * @param u if true, input is interpreted as URL-safe - * @returns binary array version of input string - */ - function r2s(t: string | ReadableStream, u: boolean): Uint8Array | ReadableStream; - } - } - - - - namespace enums { - /** - * Maps curve names under various standards to one - * @see - */ - type curve = "p256" | "p384" | "p251" | "secp256k1" | "ed25519" | "curve25519" | "brainpoolP256r1" | "brainpoolP384r1" | "brainpoolP512r1"; - - /** - * A string to key specifier type - */ - enum s2k { - simple = 0, - salted = 1, - iterated = 3, - gnu = 101, - } - - /** - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.1|RFC4880bis-04, section 9.1} - */ - enum publicKey { - /** - * RSA (Encrypt or Sign) [HAC] - */ - rsa_encrypt_sign = 1, - /** - * RSA (Encrypt only) [HAC] - */ - rsa_encrypt = 2, - /** - * RSA (Sign only) [HAC] - */ - rsa_sign = 3, - /** - * Elgamal (Encrypt only) [ELGAMAL] [HAC] - */ - elgamal = 16, - /** - * DSA (Sign only) [FIPS186] [HAC] - */ - dsa = 17, - /** - * ECDH (Encrypt only) [RFC6637] - */ - ecdh = 18, - /** - * ECDSA (Sign only) [RFC6637] - */ - ecdsa = 19, - /** - * EdDSA (Sign only) - * [ {@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] - */ - eddsa = 22, - /** - * Reserved for AEDH - */ - aedh = 23, - /** - * Reserved for AEDSA - */ - aedsa = 24, - } - - /** - * {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} - */ - enum symmetric { - plaintext = 0, - /** - * Not implemented! - */ - idea = 1, - "3des" = 2, - tripledes = 2, - cast5 = 3, - blowfish = 4, - aes128 = 7, - aes192 = 8, - aes256 = 9, - twofish = 10, - } - - /** - * {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} - */ - enum compression { - uncompressed = 0, - /** - * RFC1951 - */ - zip = 1, - /** - * RFC1950 - */ - zlib = 2, - bzip2 = 3, - } - - /** - * {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} - */ - enum hash { - md5 = 1, - sha1 = 2, - ripemd = 3, - sha256 = 8, - sha384 = 9, - sha512 = 10, - sha224 = 11, - } - - /** - * A list of hash names as accepted by webCrypto functions. - * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo} - */ - enum webHash { - "SHA-1" = 2, - "SHA-256" = 8, - "SHA-384" = 9, - "SHA-512" = 10, - } - - /** - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6} - */ - enum aead { - eax = 1, - ocb = 2, - experimental_gcm = 100, - } - - /** - * A list of packet types and numeric tags associated with them. - */ - enum packet { - publicKeyEncryptedSessionKey = 1, - signature = 2, - symEncryptedSessionKey = 3, - onePassSignature = 4, - secretKey = 5, - publicKey = 6, - secretSubkey = 7, - compressed = 8, - symmetricallyEncrypted = 9, - marker = 10, - literal = 11, - trust = 12, - userid = 13, - publicSubkey = 14, - userAttribute = 17, - symEncryptedIntegrityProtected = 18, - modificationDetectionCode = 19, - symEncryptedAEADProtected = 20, - } - - /** - * Data types in the literal packet - */ - enum literal { - /** - * Binary data 'b' - */ - binary = 98, - /** - * Text data 't' - */ - text = 116, - /** - * Utf8 data 'u' - */ - utf8 = 117, - /** - * MIME message body part 'm' - */ - mime = 109, - } - - /** - * One pass signature packet type - */ - enum signature { - /** - * 0x00: Signature of a binary document. - */ - binary = 0, - /** - * 0x01: Signature of a canonical text document. - * Canonicalyzing the document by converting line endings. - */ - text = 1, - /** - * 0x02: Standalone signature. - * This signature is a signature of only its own subpacket contents. - * It is calculated identically to a signature over a zero-lengh - * binary document. Note that it doesn't make sense to have a V3 - * standalone signature. - */ - standalone = 2, - /** - * 0x10: Generic certification of a User ID and Public-Key packet. - * The issuer of this certification does not make any particular - * assertion as to how well the certifier has checked that the owner - * of the key is in fact the person described by the User ID. - */ - cert_generic = 16, - /** - * 0x11: Persona certification of a User ID and Public-Key packet. - * The issuer of this certification has not done any verification of - * the claim that the owner of this key is the User ID specified. - */ - cert_persona = 17, - /** - * 0x12: Casual certification of a User ID and Public-Key packet. - * The issuer of this certification has done some casual - * verification of the claim of identity. - */ - cert_casual = 18, - /** - * 0x13: Positive certification of a User ID and Public-Key packet. - * The issuer of this certification has done substantial - * verification of the claim of identity. - * Most OpenPGP implementations make their "key signatures" as 0x10 - * certifications. Some implementations can issue 0x11-0x13 - * certifications, but few differentiate between the types. - */ - cert_positive = 19, - /** - * 0x30: Certification revocation signature - * This signature revokes an earlier User ID certification signature - * (signature class 0x10 through 0x13) or direct-key signature - * (0x1F). It should be issued by the same key that issued the - * revoked signature or an authorized revocation key. The signature - * is computed over the same data as the certificate that it - * revokes, and should have a later creation date than that - * certificate. - */ - cert_revocation = 48, - /** - * 0x18: Subkey Binding Signature - * This signature is a statement by the top-level signing key that - * indicates that it owns the subkey. This signature is calculated - * directly on the primary key and subkey, and not on any User ID or - * other packets. A signature that binds a signing subkey MUST have - * an Embedded Signature subpacket in this binding signature that - * contains a 0x19 signature made by the signing subkey on the - * primary key and subkey. - */ - subkey_binding = 24, - /** - * 0x19: Primary Key Binding Signature - * This signature is a statement by a signing subkey, indicating - * that it is owned by the primary key and subkey. This signature - * is calculated the same way as a 0x18 signature: directly on the - * primary key and subkey, and not on any User ID or other packets. - * When a signature is made over a key, the hash data starts with the - * octet 0x99, followed by a two-octet length of the key, and then body - * of the key packet. (Note that this is an old-style packet header for - * a key packet with two-octet length.) A subkey binding signature - * (type 0x18) or primary key binding signature (type 0x19) then hashes - * the subkey using the same format as the main key (also using 0x99 as - * the first octet). - */ - key_binding = 25, - /** - * 0x1F: Signature directly on a key - * This signature is calculated directly on a key. It binds the - * information in the Signature subpackets to the key, and is - * appropriate to be used for subpackets that provide information - * about the key, such as the Revocation Key subpacket. It is also - * appropriate for statements that non-self certifiers want to make - * about the key itself, rather than the binding between a key and a - * name. - */ - key = 31, - /** - * 0x20: Key revocation signature - * The signature is calculated directly on the key being revoked. A - * revoked key is not to be used. Only revocation signatures by the - * key being revoked, or by an authorized revocation key, should be - * considered valid revocation signatures.a - */ - key_revocation = 32, - /** - * 0x28: Subkey revocation signature - * The signature is calculated directly on the subkey being revoked. - * A revoked subkey is not to be used. Only revocation signatures - * by the top-level signature key that is bound to this subkey, or - * by an authorized revocation key, should be considered valid - * revocation signatures. - * Key revocation signatures (types 0x20 and 0x28) - * hash only the key being revoked. - */ - subkey_revocation = 40, - /** - * 0x40: Timestamp signature. - * This signature is only meaningful for the timestamp contained in - * it. - */ - timestamp = 64, - /** - * 0x50: Third-Party Confirmation signature. - * This signature is a signature over some other OpenPGP Signature - * packet(s). It is analogous to a notary seal on the signed data. - * A third-party signature SHOULD include Signature Target - * subpacket(s) to give easy identification. Note that we really do - * mean SHOULD. There are plausible uses for this (such as a blind - * party that only sees the signature, not the key or source - * document) that cannot include a target subpacket. - */ - third_party = 80, - } - - /** - * Signature subpacket type - */ - enum signatureSubpacket { - signature_creation_time = 2, - signature_expiration_time = 3, - exportable_certification = 4, - trust_signature = 5, - regular_expression = 6, - revocable = 7, - key_expiration_time = 9, - placeholder_backwards_compatibility = 10, - preferred_symmetric_algorithms = 11, - revocation_key = 12, - issuer = 16, - notation_data = 20, - preferred_hash_algorithms = 21, - preferred_compression_algorithms = 22, - key_server_preferences = 23, - preferred_key_server = 24, - primary_user_id = 25, - policy_uri = 26, - key_flags = 27, - signers_user_id = 28, - reason_for_revocation = 29, - features = 30, - signature_target = 31, - embedded_signature = 32, - issuer_fingerprint = 33, - preferred_aead_algorithms = 34, - } - - /** - * Key flags - */ - enum keyFlags { - /** - * 0x01 - This key may be used to certify other keys. - */ - certify_keys = 1, - /** - * 0x02 - This key may be used to sign data. - */ - sign_data = 2, - /** - * 0x04 - This key may be used to encrypt communications. - */ - encrypt_communication = 4, - /** - * 0x08 - This key may be used to encrypt storage. - */ - encrypt_storage = 8, - /** - * 0x10 - The private component of this key may have been split - * by a secret-sharing mechanism. - */ - split_private_key = 16, - /** - * 0x20 - This key may be used for authentication. - */ - authentication = 32, - /** - * 0x80 - The private component of this key may be in the - * possession of more than one person. - */ - shared_private_key = 128, - } - - /** - * Key status - */ - enum keyStatus { - invalid = 0, - expired = 1, - revoked = 2, - valid = 3, - no_self_cert = 4, - } - - /** - * Armor type - */ - enum armor { - multipart_section = 0, - multipart_last = 1, - signed = 2, - message = 3, - public_key = 4, - private_key = 5, - signature = 6, - } - - /** - * {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23} - */ - enum reasonForRevocation { - /** - * No reason specified (key revocations or cert revocations) - */ - no_reason = 0, - /** - * Key is superseded (key revocations) - */ - key_superseded = 1, - /** - * Key material has been comPromised (key revocations) - */ - key_comPromised = 2, - /** - * Key is retired and no longer used (key revocations) - */ - key_retired = 3, - /** - * User ID information is no longer valid (cert revocations) - */ - userid_invalid = 32, - } - - /** - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25} - */ - enum features { - /** - * 0x01 - Modification Detection (packets 18 and 19) - */ - modification_detection = 1, - /** - * 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5 - * Symmetric-Key Encrypted Session Key Packets (packet 3) - */ - aead = 2, - /** - * 0x04 - Version 5 Public-Key Packet format and corresponding new - * fingerprint format - */ - v5_keys = 4, - } - - /** - * Asserts validity and converts from string/integer to integer. - */ - function write(): void; - - /** - * Converts from an integer to string. - */ - function read(): void; - } - - namespace hkp { - class HKP { - /** - * Initialize the HKP client and configure it with the key server url and fetch function. - * @param keyServerBaseUrl (optional) The HKP key server base url including - * the protocol to use, e.g. 'https://pgp.mit.edu'; defaults to - * openpgp.config.keyserver (https://keyserver.ubuntu.com) - */ - constructor(keyServerBaseUrl: string); - - /** - * Search for a public key on the key server either by key ID or part of the user ID. - * @param options.keyID The long public key ID. - * @param options.query This can be any part of the key user ID such as name - * or email address. - * @returns The ascii armored public key. - */ - lookup(): Promise; - - /** - * Upload a public key to the server. - * @param publicKeyArmored An ascii armored public key to be uploaded. + * Probabilistic primality testing + * @param n Number to test + * @param e Optional RSA exponent to check against the prime + * @param k Optional number of iterations of Miller-Rabin test * @returns */ - upload(publicKeyArmored: string): Promise; + function isProbablePrime(n: BN, e: BN, k: Integer): boolean; + + /** + * Tests whether n is probably prime or not using Fermat's test with b = 2. + * Fails if b^(n-1) mod n === 1. + * @param n Number to test + * @param b Optional Fermat test base + * @returns + */ + function fermat(n: BN, b: Integer): boolean; + + /** + * Tests whether n is probably prime or not using the Miller-Rabin test. + * See HAC Remark 4.28. + * @param n Number to test + * @param k Optional number of iterations of Miller-Rabin test + * @param rand Optional function to generate potential witnesses + * @returns + */ + function millerRabin(n: BN, k: Integer, rand: Function): boolean; + } + + namespace rsa { + /** + * Create signature + * @param m message + * @param n RSA public modulus + * @param e RSA public exponent + * @param d RSA private exponent + * @returns RSA Signature + */ + function sign(m: BN, n: BN, e: BN, d: BN): BN; + + /** + * Verify signature + * @param s signature + * @param n RSA public modulus + * @param e RSA public exponent + * @returns + */ + function verify(s: BN, n: BN, e: BN): BN; + + /** + * Encrypt message + * @param m message + * @param n RSA public modulus + * @param e RSA public exponent + * @returns RSA Ciphertext + */ + function encrypt(m: BN, n: BN, e: BN): BN; + + /** + * Decrypt RSA message + * @param m message + * @param n RSA public modulus + * @param e RSA public exponent + * @param d RSA private exponent + * @param p RSA private prime p + * @param q RSA private prime q + * @param u RSA private inverse of prime q + * @returns RSA Plaintext + */ + function decrypt(m: BN, n: BN, e: BN, d: BN, p: BN, q: BN, u: BN): BN; + + /** + * Generate a new random private key B bits long with public exponent E. + * When possible, webCrypto is used. Otherwise, primes are generated using + * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. + * @see module:crypto/public_key/prime + * @param B RSA bit length + * @param E RSA public exponent in hex string + * @returns RSA public modulus, RSA public exponent, RSA private exponent, + * RSA private prime p, RSA private prime q, u = q ** -1 mod p + */ + function generate(B: Integer, E: string): object; } } + namespace random { + /** + * Retrieve secure random byte array of the specified length + * @param length Length in bytes to generate + * @returns Random byte array + */ + function getRandomBytes(length: Integer): Uint8Array; + + /** + * Create a secure random MPI that is greater than or equal to min and less than max. + * @param min Lower bound, included + * @param max Upper bound, excluded + * @returns Random MPI + */ + function getRandomBN(min: type.mpi.MPI, max: type.mpi.MPI): BN; + + /** + * Buffer for secure random numbers + */ + function RandomBuffer(): void; + } + + namespace signature { + /** + * Verifies the signature provided for data using specified algorithms and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param algo Public key algorithm + * @param hash_algo Hash algorithm + * @param msg_MPIs Algorithm-specific signature parameters + * @param pub_MPIs Algorithm-specific public key parameters + * @param data Data for which the signature was created + * @param hashed The hashed data + * @returns True if signature is valid + */ + function verify(algo: enums.publicKey, hash_algo: enums.hash, msg_MPIs: type.mpi.MPI[], pub_MPIs: type.mpi.MPI[], data: Uint8Array, hashed: Uint8Array): boolean; + + /** + * Creates a signature on data using specified algorithms and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param algo Public key algorithm + * @param hash_algo Hash algorithm + * @param key_params Algorithm-specific public and private key parameters + * @param data Data to be signed + * @param hashed The hashed data + * @returns Signature + */ + function sign(algo: enums.publicKey, hash_algo: enums.hash, key_params: type.mpi.MPI[], data: Uint8Array, hashed: Uint8Array): Uint8Array; + } +} + +export namespace eme { + /** + * Create a EME-PKCS1-v1_5 padded message + * @see + * @param M message to be encoded + * @param k the length in octets of the key modulus + * @returns EME-PKCS1 padded message + */ + function encode(M: string, k: Integer): Promise; + + /** + * Decode a EME-PKCS1-v1_5 padded message + * @see + * @param EM encoded message, an octet string + * @returns message, an octet string + */ + function decode(EM: string): string; +} + +export namespace emsa { + /** + * Create a EMSA-PKCS1-v1_5 padded message + * @see + * @param algo Hash algorithm type used + * @param hashed message to be encoded + * @param emLen intended length in octets of the encoded message + * @returns encoded message + */ + function encode(algo: Integer, hashed: Uint8Array, emLen: Integer): string; +} + +export namespace encoding { + namespace armor { + /** + * Add additional information to the armor version of an OpenPGP binary + * packet block. + * @author Alex + * @version 2011-12-16 + * @param customComment (optional) additional comment to add to the armored string + * @returns The header information + */ + function addheader(customComment: string): string; + + /** + * Calculates a checksum over the given data and returns it base64 encoded + * @param data Data to create a CRC-24 checksum for + * @returns Base64 encoded checksum + */ + function getCheckSum(data: string | ReadableStream): string | ReadableStream; + + /** + * Internal function to calculate a CRC-24 checksum over a given string (data) + * @param data Data to create a CRC-24 checksum for + * @returns The CRC-24 checksum + */ + function createcrc24(data: string | ReadableStream): Uint8Array | ReadableStream; + + /** + * Splits a message into two parts, the body and the checksum. This is an internal function + * @param text OpenPGP armored message part + * @returns An object with attribute "body" containing the body + * and an attribute "checksum" containing the checksum. + */ + function splitChecksum(text: string): object; + + /** + * DeArmor an OpenPGP armored message; verify the checksum and return + * the encoded bytes + * @param text OpenPGP armored message + * @returns An object with attribute "text" containing the message text, + * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type + */ + function dearmor(text: string): Promise; + + /** + * Armor an OpenPGP binary packet block + * @param messagetype type of the message + * @param body + * @param partindex + * @param parttotal + * @param customComment (optional) additional comment to add to the armored string + * @returns Armored text + */ + function armor(messagetype: Integer, body: any, partindex: Integer, parttotal: Integer, customComment?: string): string | ReadableStream; + } + + namespace base64 { + /** + * Convert binary array to radix-64 + * @param t Uint8Array to convert + * @param u if true, output is URL-safe + * @returns radix-64 version of input string + */ + function s2r(t: Uint8Array | ReadableStream, u?: boolean): string | ReadableStream; + + /** + * Convert radix-64 to binary array + * @param t radix-64 string to convert + * @param u if true, input is interpreted as URL-safe + * @returns binary array version of input string + */ + function r2s(t: string | ReadableStream, u: boolean): Uint8Array | ReadableStream; + } +} + + + +export namespace enums { + /** + * Maps curve names under various standards to one + * @see + */ + type curve = "p256" | "p384" | "p251" | "secp256k1" | "ed25519" | "curve25519" | "brainpoolP256r1" | "brainpoolP384r1" | "brainpoolP512r1"; + + /** + * A string to key specifier type + */ + enum s2k { + simple = 0, + salted = 1, + iterated = 3, + gnu = 101, + } + + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.1|RFC4880bis-04, section 9.1} + */ + enum publicKey { + /** + * RSA (Encrypt or Sign) [HAC] + */ + rsa_encrypt_sign = 1, + /** + * RSA (Encrypt only) [HAC] + */ + rsa_encrypt = 2, + /** + * RSA (Sign only) [HAC] + */ + rsa_sign = 3, + /** + * Elgamal (Encrypt only) [ELGAMAL] [HAC] + */ + elgamal = 16, + /** + * DSA (Sign only) [FIPS186] [HAC] + */ + dsa = 17, + /** + * ECDH (Encrypt only) [RFC6637] + */ + ecdh = 18, + /** + * ECDSA (Sign only) [RFC6637] + */ + ecdsa = 19, + /** + * EdDSA (Sign only) + * [ {@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] + */ + eddsa = 22, + /** + * Reserved for AEDH + */ + aedh = 23, + /** + * Reserved for AEDSA + */ + aedsa = 24, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} + */ + enum symmetric { + plaintext = 0, + /** + * Not implemented! + */ + idea = 1, + "3des" = 2, + tripledes = 2, + cast5 = 3, + blowfish = 4, + aes128 = 7, + aes192 = 8, + aes256 = 9, + twofish = 10, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} + */ + enum compression { + uncompressed = 0, + /** + * RFC1951 + */ + zip = 1, + /** + * RFC1950 + */ + zlib = 2, + bzip2 = 3, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} + */ + enum hash { + md5 = 1, + sha1 = 2, + ripemd = 3, + sha256 = 8, + sha384 = 9, + sha512 = 10, + sha224 = 11, + } + + /** + * A list of hash names as accepted by webCrypto functions. + * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo} + */ + enum webHash { + "SHA-1" = 2, + "SHA-256" = 8, + "SHA-384" = 9, + "SHA-512" = 10, + } + + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6} + */ + enum aead { + eax = 1, + ocb = 2, + experimental_gcm = 100, + } + + /** + * A list of packet types and numeric tags associated with them. + */ + enum packet { + publicKeyEncryptedSessionKey = 1, + signature = 2, + symEncryptedSessionKey = 3, + onePassSignature = 4, + secretKey = 5, + publicKey = 6, + secretSubkey = 7, + compressed = 8, + symmetricallyEncrypted = 9, + marker = 10, + literal = 11, + trust = 12, + userid = 13, + publicSubkey = 14, + userAttribute = 17, + symEncryptedIntegrityProtected = 18, + modificationDetectionCode = 19, + symEncryptedAEADProtected = 20, + } + + /** + * Data types in the literal packet + */ + enum literal { + /** + * Binary data 'b' + */ + binary = 98, + /** + * Text data 't' + */ + text = 116, + /** + * Utf8 data 'u' + */ + utf8 = 117, + /** + * MIME message body part 'm' + */ + mime = 109, + } + + /** + * One pass signature packet type + */ + enum signature { + /** + * 0x00: Signature of a binary document. + */ + binary = 0, + /** + * 0x01: Signature of a canonical text document. + * Canonicalyzing the document by converting line endings. + */ + text = 1, + /** + * 0x02: Standalone signature. + * This signature is a signature of only its own subpacket contents. + * It is calculated identically to a signature over a zero-lengh + * binary document. Note that it doesn't make sense to have a V3 + * standalone signature. + */ + standalone = 2, + /** + * 0x10: Generic certification of a User ID and Public-Key packet. + * The issuer of this certification does not make any particular + * assertion as to how well the certifier has checked that the owner + * of the key is in fact the person described by the User ID. + */ + cert_generic = 16, + /** + * 0x11: Persona certification of a User ID and Public-Key packet. + * The issuer of this certification has not done any verification of + * the claim that the owner of this key is the User ID specified. + */ + cert_persona = 17, + /** + * 0x12: Casual certification of a User ID and Public-Key packet. + * The issuer of this certification has done some casual + * verification of the claim of identity. + */ + cert_casual = 18, + /** + * 0x13: Positive certification of a User ID and Public-Key packet. + * The issuer of this certification has done substantial + * verification of the claim of identity. + * Most OpenPGP implementations make their "key signatures" as 0x10 + * certifications. Some implementations can issue 0x11-0x13 + * certifications, but few differentiate between the types. + */ + cert_positive = 19, + /** + * 0x30: Certification revocation signature + * This signature revokes an earlier User ID certification signature + * (signature class 0x10 through 0x13) or direct-key signature + * (0x1F). It should be issued by the same key that issued the + * revoked signature or an authorized revocation key. The signature + * is computed over the same data as the certificate that it + * revokes, and should have a later creation date than that + * certificate. + */ + cert_revocation = 48, + /** + * 0x18: Subkey Binding Signature + * This signature is a statement by the top-level signing key that + * indicates that it owns the subkey. This signature is calculated + * directly on the primary key and subkey, and not on any User ID or + * other packets. A signature that binds a signing subkey MUST have + * an Embedded Signature subpacket in this binding signature that + * contains a 0x19 signature made by the signing subkey on the + * primary key and subkey. + */ + subkey_binding = 24, + /** + * 0x19: Primary Key Binding Signature + * This signature is a statement by a signing subkey, indicating + * that it is owned by the primary key and subkey. This signature + * is calculated the same way as a 0x18 signature: directly on the + * primary key and subkey, and not on any User ID or other packets. + * When a signature is made over a key, the hash data starts with the + * octet 0x99, followed by a two-octet length of the key, and then body + * of the key packet. (Note that this is an old-style packet header for + * a key packet with two-octet length.) A subkey binding signature + * (type 0x18) or primary key binding signature (type 0x19) then hashes + * the subkey using the same format as the main key (also using 0x99 as + * the first octet). + */ + key_binding = 25, + /** + * 0x1F: Signature directly on a key + * This signature is calculated directly on a key. It binds the + * information in the Signature subpackets to the key, and is + * appropriate to be used for subpackets that provide information + * about the key, such as the Revocation Key subpacket. It is also + * appropriate for statements that non-self certifiers want to make + * about the key itself, rather than the binding between a key and a + * name. + */ + key = 31, + /** + * 0x20: Key revocation signature + * The signature is calculated directly on the key being revoked. A + * revoked key is not to be used. Only revocation signatures by the + * key being revoked, or by an authorized revocation key, should be + * considered valid revocation signatures.a + */ + key_revocation = 32, + /** + * 0x28: Subkey revocation signature + * The signature is calculated directly on the subkey being revoked. + * A revoked subkey is not to be used. Only revocation signatures + * by the top-level signature key that is bound to this subkey, or + * by an authorized revocation key, should be considered valid + * revocation signatures. + * Key revocation signatures (types 0x20 and 0x28) + * hash only the key being revoked. + */ + subkey_revocation = 40, + /** + * 0x40: Timestamp signature. + * This signature is only meaningful for the timestamp contained in + * it. + */ + timestamp = 64, + /** + * 0x50: Third-Party Confirmation signature. + * This signature is a signature over some other OpenPGP Signature + * packet(s). It is analogous to a notary seal on the signed data. + * A third-party signature SHOULD include Signature Target + * subpacket(s) to give easy identification. Note that we really do + * mean SHOULD. There are plausible uses for this (such as a blind + * party that only sees the signature, not the key or source + * document) that cannot include a target subpacket. + */ + third_party = 80, + } + + /** + * Signature subpacket type + */ + enum signatureSubpacket { + signature_creation_time = 2, + signature_expiration_time = 3, + exportable_certification = 4, + trust_signature = 5, + regular_expression = 6, + revocable = 7, + key_expiration_time = 9, + placeholder_backwards_compatibility = 10, + preferred_symmetric_algorithms = 11, + revocation_key = 12, + issuer = 16, + notation_data = 20, + preferred_hash_algorithms = 21, + preferred_compression_algorithms = 22, + key_server_preferences = 23, + preferred_key_server = 24, + primary_user_id = 25, + policy_uri = 26, + key_flags = 27, + signers_user_id = 28, + reason_for_revocation = 29, + features = 30, + signature_target = 31, + embedded_signature = 32, + issuer_fingerprint = 33, + preferred_aead_algorithms = 34, + } + + /** + * Key flags + */ + enum keyFlags { + /** + * 0x01 - This key may be used to certify other keys. + */ + certify_keys = 1, + /** + * 0x02 - This key may be used to sign data. + */ + sign_data = 2, + /** + * 0x04 - This key may be used to encrypt communications. + */ + encrypt_communication = 4, + /** + * 0x08 - This key may be used to encrypt storage. + */ + encrypt_storage = 8, + /** + * 0x10 - The private component of this key may have been split + * by a secret-sharing mechanism. + */ + split_private_key = 16, + /** + * 0x20 - This key may be used for authentication. + */ + authentication = 32, + /** + * 0x80 - The private component of this key may be in the + * possession of more than one person. + */ + shared_private_key = 128, + } + + /** + * Key status + */ + enum keyStatus { + invalid = 0, + expired = 1, + revoked = 2, + valid = 3, + no_self_cert = 4, + } + + /** + * Armor type + */ + enum armor { + multipart_section = 0, + multipart_last = 1, + signed = 2, + message = 3, + public_key = 4, + private_key = 5, + signature = 6, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23} + */ + enum reasonForRevocation { + /** + * No reason specified (key revocations or cert revocations) + */ + no_reason = 0, + /** + * Key is superseded (key revocations) + */ + key_superseded = 1, + /** + * Key material has been comPromised (key revocations) + */ + key_comPromised = 2, + /** + * Key is retired and no longer used (key revocations) + */ + key_retired = 3, + /** + * User ID information is no longer valid (cert revocations) + */ + userid_invalid = 32, + } + + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25} + */ + enum features { + /** + * 0x01 - Modification Detection (packets 18 and 19) + */ + modification_detection = 1, + /** + * 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5 + * Symmetric-Key Encrypted Session Key Packets (packet 3) + */ + aead = 2, + /** + * 0x04 - Version 5 Public-Key Packet format and corresponding new + * fingerprint format + */ + v5_keys = 4, + } + + /** + * Asserts validity and converts from string/integer to integer. + */ + function write(): void; + + /** + * Converts from an integer to string. + */ + function read(): void; +} + +export namespace hkp { class HKP { /** * Initialize the HKP client and configure it with the key server url and fetch function. @@ -1552,557 +1526,301 @@ export namespace openpgp { */ upload(publicKeyArmored: string): Promise; } +} - namespace key { +export class HKP { + /** + * Initialize the HKP client and configure it with the key server url and fetch function. + * @param keyServerBaseUrl (optional) The HKP key server base url including + * the protocol to use, e.g. 'https://pgp.mit.edu'; defaults to + * openpgp.config.keyserver (https://keyserver.ubuntu.com) + */ + constructor(keyServerBaseUrl: string); + + /** + * Search for a public key on the key server either by key ID or part of the user ID. + * @param options.keyID The long public key ID. + * @param options.query This can be any part of the key user ID such as name + * or email address. + * @returns The ascii armored public key. + */ + lookup(): Promise; + + /** + * Upload a public key to the server. + * @param publicKeyArmored An ascii armored public key to be uploaded. + * @returns + */ + upload(publicKeyArmored: string): Promise; +} + +export namespace key { + /** + * Class that represents an OpenPGP key. Must contain a primary key. + * Can contain additional subkeys, signatures, user ids, user attributes. + */ + class Key { /** - * Class that represents an OpenPGP key. Must contain a primary key. - * Can contain additional subkeys, signatures, user ids, user attributes. + * @param packetlist The packets that form this key */ - class Key { - /** - * @param packetlist The packets that form this key - */ - constructor(packetlist: packet.List); - - /** - * Transforms packetlist to structured key data - * @param packetlist The packets that form a key - */ - packetlist2structure(packetlist: packet.List): void; - - /** - * Transforms structured key data to packetlist - * @returns The packets that form a key - */ - toPacketlist(): packet.List; - - /** - * Returns an array containing all public or private subkeys matching keyId; - * If keyId is not present, returns all subkeys. - * @param keyId - * @returns - */ - getSubkeys(keyId: type.keyid.Keyid): any[]; - - /** - * Returns an array containing all public or private keys matching keyId. - * If keyId is not present, returns all keys starting with the primary key. - * @param keyId - * @returns - */ - getKeys(keyId: type.keyid.Keyid): any[]; - - /** - * Returns key IDs of all keys - * @returns - */ - getKeyIds(): any[]; - - /** - * Returns userids - * @returns array of userids - */ - getUserIds(): any[]; - - /** - * Returns true if this is a public key - * @returns - */ - isPublic(): boolean; - - /** - * Returns true if this is a private key - * @returns - */ - isPrivate(): boolean; - - /** - * Returns key as public key (shallow copy) - * @returns new public Key - */ - toPublic(): Key; - - /** - * Returns ASCII armored text of key - * @returns ASCII armor - */ - armor(): ReadableStream; - - /** - * Returns last created key or key by given keyId that is available for signing and verification - * @param keyId, optional - * @param date (optional) use the given date for verification instead of the current time - * @param userId, optional user ID - * @returns key or null if no signing key has been found - */ - getSigningKey(keyId: type.keyid.Keyid, date?: Date, userId?: object): Promise; - - /** - * Returns last created key or key by given keyId that is available for encryption or decryption - * @param keyId, optional - * @param date, optional - * @param userId, optional - * @returns key or null if no encryption key has been found - */ - getEncryptionKey(keyId?: type.keyid.Keyid, date?: Date, userId?: string): Promise; - - /** - * Encrypts all secret key and subkey packets matching keyId - * @param passphrases - if multiple passphrases, then should be in same order as packets each should encrypt - * @param keyId - * @returns - */ - encrypt(passphrases: string | any[], keyId?: type.keyid.Keyid): Promise>; - - /** - * Decrypts all secret key and subkey packets matching keyId - * @param passphrases - * @param keyId - * @returns true if all matching key and subkey packets decrypted successfully - */ - decrypt(passphrases: string | string[], keyId?: type.keyid.Keyid): Promise; - - /** - * Checks if a signature on a key is revoked - * @param - * @param signature The signature to verify - * @param key, optional The key to verify the signature - * @param date Use the given date instead of the current time - * @returns True if the certificate is revoked - */ - isRevoked(signature: packet.Signature, key?: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date?: Date): Promise; - - /** - * Verify primary key. Checks for revocation signatures, expiration time - * and valid self signature - * @param date (optional) use the given date for verification instead of the current time - * @param userId (optional) user ID - * @returns The status of the primary key - */ - verifyPrimaryKey(date?: Date, userId?: object): Promise; - - /** - * Returns the latest date when the key can be used for encrypting, signing, or both, depending on the `capabilities` paramater. - * When `capabilities` is null, defaults to returning the expiry date of the primary key. - * Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid. - * Returns Infinity if the key doesn't expire. - * @param {encrypt | sign | encrypt_sign} capabilities, optional - * @param keyId, optional - * @param userId, optional user ID - * @returns - */ - getExpirationTime(capabilities: any, keyId: type.keyid.Keyid, userId: object): Promise; - - /** - * Returns primary user and most significant (latest valid) self signature - * - if multiple primary users exist, returns the one with the latest self signature - * - otherwise, returns the user with the latest self signature - * @param date (optional) use the given date for verification instead of the current time - * @param userId (optional) user ID to get instead of the primary user, if it exists - * @returns The primary user and the self signature - */ - getPrimaryUser(date: Date, userId: object): Promise<{ user: User, selfCertification: packet.Signature }>; - - /** - * Update key with new components from specified key with same key ID: - * users, subkeys, certificates are merged into the destination key, - * duplicates and expired signatures are ignored. - * If the specified key is a private key and the destination key is public, - * the destination key is transformed to a private key. - * @param key Source key to merge - * @returns - */ - update(key: Key): Promise; - - /** - * Revokes the key - * @param reasonForRevocation optional, object indicating the reason for revocation - * @param reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param reasonForRevocation.string optional, string explaining the reason for revocation - * @param date optional, override the creationtime of the revocation signature - * @returns new key with revocation signature - */ - revoke(reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; - - /** - * Get revocation certificate from a revoked key. - * (To get a revocation certificate for an unrevoked key, call revoke() first.) - * @returns armored revocation certificate - */ - getRevocationCertificate(): Promise; - - /** - * Applies a revocation certificate to a key - * This adds the first signature packet in the armored text to the key, - * if it is a valid revocation signature. - * @param revocationCertificate armored revocation certificate - * @returns new revoked key - */ - applyRevocationCertificate(revocationCertificate: string): Promise; - - /** - * Signs primary user of key - * @param privateKey decrypted private keys for signing - * @param date (optional) use the given date for verification instead of the current time - * @param userId (optional) user ID to get instead of the primary user, if it exists - * @returns new public key with new certificate signature - */ - signPrimaryUser(privateKey: any[], date: Date, userId: object): Promise; - - /** - * Signs all users of key - * @param privateKeys decrypted private keys for signing - * @returns new public key with new certificate signature - */ - signAllUsers(privateKeys: any[]): Promise; - - /** - * Verifies primary user of key - * - if no arguments are given, verifies the self certificates; - * - otherwise, verifies all certificates signed with given keys. - * @param keys array of keys to verify certificate signatures - * @param date (optional) use the given date for verification instead of the current time - * @param userId (optional) user ID to get instead of the primary user, if it exists - * @returns List of signer's keyid and validity of signature - */ - verifyPrimaryUser(keys: any[], date: Date, userId: object): Promise>; - - /** - * Verifies all users of key - * - if no arguments are given, verifies the self certificates; - * - otherwise, verifies all certificates signed with given keys. - * @param keys array of keys to verify certificate signatures - * @returns list of userid, signer's keyid and validity of signature - */ - verifyAllUsers(keys: any[]): Promise>; - - /** - * Calculates the key id of the key - * @returns A 8 byte key id - */ - getKeyId(): string; - - /** - * Calculates the fingerprint of the key - * @returns A string containing the fingerprint in lowercase hex - */ - getFingerprint(): string; - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns Whether the two keys have the same version and public key data - */ - hasSameFingerprintAs(): boolean; - - /** - * Returns algorithm information - * @returns An object of the form {algorithm: string, bits:int, curve:String} - */ - getAlgorithmInfo(): object; - - /** - * Returns the creation time of the key - * @returns - */ - getCreationTime(): Date; - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns - */ - isDecrypted(): boolean | null; - } + constructor(packetlist: packet.List); /** - * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. - * @param signatures List of signatures - * @param date Use the given date instead of the current time - * @returns The latest valid signature + * Transforms packetlist to structured key data + * @param packetlist The packets that form a key */ - function getLatestValidSignature(signatures: any[], date: Date): Promise; + packetlist2structure(packetlist: packet.List): void; /** - * Class that represents an user ID or attribute packet and the relevant signatures. + * Transforms structured key data to packetlist + * @returns The packets that form a key */ - class User { - constructor(); - - /** - * Transforms structured user data to packetlist - * @returns - */ - toPacketlist(): packet.List; - - /** - * Signs user - * @param primaryKey The primary key packet - * @param privateKeys Decrypted private keys for signing - * @returns New user with new certificate signatures - */ - sign(primaryKey: packet.SecretKey | packet.PublicKey, privateKeys: any[]): Promise; - - /** - * Checks if a given certificate of the user is revoked - * @param primaryKey The primary key packet - * @param certificate The certificate to verify - * @param key, optional The key to verify the signature - * @param date Use the given date instead of the current time - * @returns True if the certificate is revoked - */ - isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; - - /** - * Verifies the user certificate - * @param primaryKey The primary key packet - * @param certificate A certificate of this user - * @param keys Array of keys to verify certificate signatures - * @param date Use the given date instead of the current time - * @returns status of the certificate - */ - verifyCertificate(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, keys: any[], date: Date): Promise; - - /** - * Verifies all user certificates - * @param primaryKey The primary key packet - * @param keys Array of keys to verify certificate signatures - * @param date Use the given date instead of the current time - * @returns List of signer's keyid and validity of signature - */ - verifyAllCertifications(primaryKey: packet.SecretKey | packet.PublicKey, keys: any[], date: Date): Promise>; - - /** - * Verify User. Checks for existence of self signatures, revocation signatures - * and validity of self signature - * @param primaryKey The primary key packet - * @param date Use the given date instead of the current time - * @returns Status of user - */ - verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; - - /** - * Update user with new components from specified user - * @param user Source user to merge - * @param primaryKey primary key used for validation - * @returns - */ - update(user: User, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; - } + toPacketlist(): packet.List; /** - * Create signature packet - * @param dataToSign Contains packets to be signed - * @param signingKeyPacket secret key packet for signing - * @param signatureProperties (optional) properties to write on the signature packet before signing - * @param date (optional) override the creationtime of the signature - * @param userId (optional) user ID - * @returns signature packet - */ - function createSignaturePacket(dataToSign: object, signingKeyPacket: packet.SecretKey | packet.SecretSubkey, signatureProperties: object, date: Date, userId: object): packet.Signature; - - /** - * Class that represents a subkey packet and the relevant signatures. - */ - class SubKey { - constructor(); - - /** - * Transforms structured subkey data to packetlist - * @returns - */ - toPacketlist(): packet.List; - - /** - * Checks if a binding signature of a subkey is revoked - * @param primaryKey The primary key packet - * @param signature The binding signature to verify - * @param key, optional The key to verify the signature - * @param date Use the given date instead of the current time - * @returns True if the binding signature is revoked - */ - isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; - - /** - * Verify subkey. Checks for revocation signatures, expiration time - * and valid binding signature - * @param primaryKey The primary key packet - * @param date Use the given date instead of the current time - * @returns The status of the subkey - */ - verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; - - /** - * Returns the expiration time of the subkey or Infinity if key does not expire - * Returns null if the subkey is invalid. - * @param primaryKey The primary key packet - * @param date Use the given date instead of the current time - * @returns - */ - getExpirationTime(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; - - /** - * Update subkey with new components from specified subkey - * @param subKey Source subkey to merge - * @param primaryKey primary key used for validation - * @returns - */ - update(subKey: SubKey, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; - - /** - * Revokes the subkey - * @param primaryKey decrypted private primary key for revocation - * @param reasonForRevocation optional, object indicating the reason for revocation - * @param reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param reasonForRevocation.string optional, string explaining the reason for revocation - * @param date optional, override the creationtime of the revocation signature - * @returns new subkey with revocation signature - */ - revoke(primaryKey: packet.SecretKey, reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; - - /** - * Calculates the key id of the key - * @returns A 8 byte key id - */ - getKeyId(): string; - - /** - * Calculates the fingerprint of the key - * @returns A string containing the fingerprint in lowercase hex - */ - getFingerprint(): string; - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns Whether the two keys have the same version and public key data - */ - hasSameFingerprintAs(): boolean; - - /** - * Returns algorithm information - * @returns An object of the form {algorithm: string, bits:int, curve:String} - */ - getAlgorithmInfo(): object; - - /** - * Returns the creation time of the key - * @returns - */ - getCreationTime(): Date; - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns - */ - isDecrypted(): boolean | null; - } - - /** - * Reads an unarmored OpenPGP key list and returns one or multiple key objects - * @param data to be parsed - * @returns result object with key and error arrays - */ - function read(data: Uint8Array): Promise<{ keys: Array, err: Array | null }>; - - interface KeyResult { keys: Array, err: Array | null } - - /** - * Reads an OpenPGP armored text and returns one or multiple key objects - * @param armoredText text to be parsed - * @returns result object with key and error arrays - */ - function readArmored(armoredText: string | ReadableStream): Promise; - - /** - * Generates a new OpenPGP key. Supports RSA and ECC keys. - * Primary and subkey will be of same type. - * @param options.keyType To indicate what type of key to make. - * RSA is 1. See {@link https://tools.ietf.org/html/rfc4880#section-9.1} - * @param options.numBits number of bits for the key creation. - * @param options.userIds Assumes already in form of "User Name " - * If array is used, the first userId is set as primary user Id - * @param options.passphrase The passphrase used to encrypt the resulting private key - * @param options.keyExpirationTime The number of seconds after the key creation time that the key expires - * @param curve (optional) elliptic curve for ECC keys - * @param date Override the creation date of the key and the key signatures - * @param subkeys (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] - * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + * Returns an array containing all public or private subkeys matching keyId; + * If keyId is not present, returns all subkeys. + * @param keyId * @returns */ - function generate(options: KeyOptions): Promise; + getSubkeys(keyId: type.keyid.Keyid): any[]; /** - * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. - * @param options.privateKey The private key to reformat - * @param options.keyType - * @param options.userIds Assumes already in form of "User Name " - * If array is used, the first userId is set as primary user Id - * @param options.passphrase The passphrase used to encrypt the resulting private key - * @param options.keyExpirationTime The number of seconds after the key creation time that the key expires - * @param date Override the creation date of the key and the key signatures - * @param subkeys (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * Returns an array containing all public or private keys matching keyId. + * If keyId is not present, returns all keys starting with the primary key. + * @param keyId * @returns */ - function reformat(date: Date, subkeys: any[]): Promise; + getKeys(keyId: type.keyid.Keyid): any[]; /** - * Checks if a given certificate or binding signature is revoked - * @param primaryKey The primary key packet - * @param dataToVerify The data to check - * @param revocations The revocation signatures to check - * @param signature The certificate or signature to check - * @param key, optional The key packet to check the signature + * Returns key IDs of all keys + * @returns + */ + getKeyIds(): any[]; + + /** + * Returns userids + * @returns array of userids + */ + getUserIds(): any[]; + + /** + * Returns true if this is a public key + * @returns + */ + isPublic(): boolean; + + /** + * Returns true if this is a private key + * @returns + */ + isPrivate(): boolean; + + /** + * Returns key as public key (shallow copy) + * @returns new public Key + */ + toPublic(): Key; + + /** + * Returns ASCII armored text of key + * @returns ASCII armor + */ + armor(): ReadableStream; + + /** + * Returns last created key or key by given keyId that is available for signing and verification + * @param keyId, optional + * @param date (optional) use the given date for verification instead of the current time + * @param userId, optional user ID + * @returns key or null if no signing key has been found + */ + getSigningKey(keyId: type.keyid.Keyid, date?: Date, userId?: object): Promise; + + /** + * Returns last created key or key by given keyId that is available for encryption or decryption + * @param keyId, optional + * @param date, optional + * @param userId, optional + * @returns key or null if no encryption key has been found + */ + getEncryptionKey(keyId?: type.keyid.Keyid, date?: Date, userId?: string): Promise; + + /** + * Encrypts all secret key and subkey packets matching keyId + * @param passphrases - if multiple passphrases, then should be in same order as packets each should encrypt + * @param keyId + * @returns + */ + encrypt(passphrases: string | any[], keyId?: type.keyid.Keyid): Promise>; + + /** + * Decrypts all secret key and subkey packets matching keyId + * @param passphrases + * @param keyId + * @returns true if all matching key and subkey packets decrypted successfully + */ + decrypt(passphrases: string | string[], keyId?: type.keyid.Keyid): Promise; + + /** + * Checks if a signature on a key is revoked + * @param + * @param signature The signature to verify + * @param key, optional The key to verify the signature * @param date Use the given date instead of the current time - * @returns True if the signature revokes the data + * @returns True if the certificate is revoked */ - function isDataRevoked(primaryKey: packet.SecretKey | packet.PublicKey, dataToVerify: object, revocations: any[], signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + isRevoked(signature: packet.Signature, key?: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date?: Date): Promise; /** - * Check if signature has revocation key sub packet (not supported by OpenPGP.js) - * and throw error if found - * @param signature The certificate or signature to check - * @param keyId Check only certificates or signatures from a certain issuer key ID - */ - function checkRevocationKey(signature: packet.Signature, keyId: type.keyid.Keyid): void; - - /** - * Returns the preferred signature hash algorithm of a key - * @param key (optional) the key to get preferences from - * @param keyPacket key packet used for signing + * Verify primary key. Checks for revocation signatures, expiration time + * and valid self signature * @param date (optional) use the given date for verification instead of the current time * @param userId (optional) user ID + * @returns The status of the primary key + */ + verifyPrimaryKey(date?: Date, userId?: object): Promise; + + /** + * Returns the latest date when the key can be used for encrypting, signing, or both, depending on the `capabilities` paramater. + * When `capabilities` is null, defaults to returning the expiry date of the primary key. + * Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid. + * Returns Infinity if the key doesn't expire. + * @param {encrypt | sign | encrypt_sign} capabilities, optional + * @param keyId, optional + * @param userId, optional user ID * @returns */ - function getPreferredHashAlgo(key: Key, keyPacket: packet.SecretKey | packet.SecretSubkey, date: Date, userId: object): Promise; + getExpirationTime(capabilities: any, keyId: type.keyid.Keyid, userId: object): Promise; /** - * Returns the preferred symmetric/aead algorithm for a set of keys - * @param {symmetric | aead} type Type of preference to return - * @param keys Set of keys + * Returns primary user and most significant (latest valid) self signature + * - if multiple primary users exist, returns the one with the latest self signature + * - otherwise, returns the user with the latest self signature * @param date (optional) use the given date for verification instead of the current time - * @param userIds (optional) user IDs - * @returns Preferred symmetric algorithm + * @param userId (optional) user ID to get instead of the primary user, if it exists + * @returns The primary user and the self signature */ - function getPreferredAlgo(type: any, keys: any[], date: Date, userIds: any[]): Promise; + getPrimaryUser(date: Date, userId: object): Promise<{ user: User, selfCertification: packet.Signature }>; /** - * Returns whether aead is supported by all keys in the set - * @param keys Set of keys - * @param date (optional) use the given date for verification instead of the current time - * @param userIds (optional) user IDs + * Update key with new components from specified key with same key ID: + * users, subkeys, certificates are merged into the destination key, + * duplicates and expired signatures are ignored. + * If the specified key is a private key and the destination key is public, + * the destination key is transformed to a private key. + * @param key Source key to merge * @returns */ - function isAeadSupported(keys: any[], date: Date, userIds: any[]): Promise; + update(key: Key): Promise; + + /** + * Revokes the key + * @param reasonForRevocation optional, object indicating the reason for revocation + * @param reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param reasonForRevocation.string optional, string explaining the reason for revocation + * @param date optional, override the creationtime of the revocation signature + * @returns new key with revocation signature + */ + revoke(reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; + + /** + * Get revocation certificate from a revoked key. + * (To get a revocation certificate for an unrevoked key, call revoke() first.) + * @returns armored revocation certificate + */ + getRevocationCertificate(): Promise; + + /** + * Applies a revocation certificate to a key + * This adds the first signature packet in the armored text to the key, + * if it is a valid revocation signature. + * @param revocationCertificate armored revocation certificate + * @returns new revoked key + */ + applyRevocationCertificate(revocationCertificate: string): Promise; + + /** + * Signs primary user of key + * @param privateKey decrypted private keys for signing + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID to get instead of the primary user, if it exists + * @returns new public key with new certificate signature + */ + signPrimaryUser(privateKey: any[], date: Date, userId: object): Promise; + + /** + * Signs all users of key + * @param privateKeys decrypted private keys for signing + * @returns new public key with new certificate signature + */ + signAllUsers(privateKeys: any[]): Promise; + + /** + * Verifies primary user of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param keys array of keys to verify certificate signatures + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID to get instead of the primary user, if it exists + * @returns List of signer's keyid and validity of signature + */ + verifyPrimaryUser(keys: any[], date: Date, userId: object): Promise>; + + /** + * Verifies all users of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param keys array of keys to verify certificate signatures + * @returns list of userid, signer's keyid and validity of signature + */ + verifyAllUsers(keys: any[]): Promise>; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; } - interface revoke_reasonForRevocation { - /** - * optional, flag indicating the reason for revocation - */ - flag: enums.reasonForRevocation; - /** - * optional, string explaining the reason for revocation - */ - string: string; - } + /** + * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. + * @param signatures List of signatures + * @param date Use the given date instead of the current time + * @returns The latest valid signature + */ + function getLatestValidSignature(signatures: any[], date: Date): Promise; /** * Class that represents an user ID or attribute packet and the relevant signatures. @@ -2122,7 +1840,7 @@ export namespace openpgp { * @param privateKeys Decrypted private keys for signing * @returns New user with new certificate signatures */ - sign(primaryKey: packet.SecretKey | packet.PublicKey, privateKeys: any[]): Promise; + sign(primaryKey: packet.SecretKey | packet.PublicKey, privateKeys: any[]): Promise; /** * Checks if a given certificate of the user is revoked @@ -2168,9 +1886,20 @@ export namespace openpgp { * @param primaryKey primary key used for validation * @returns */ - update(user: key.User, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + update(user: User, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; } + /** + * Create signature packet + * @param dataToSign Contains packets to be signed + * @param signingKeyPacket secret key packet for signing + * @param signatureProperties (optional) properties to write on the signature packet before signing + * @param date (optional) override the creationtime of the signature + * @param userId (optional) user ID + * @returns signature packet + */ + function createSignaturePacket(dataToSign: object, signingKeyPacket: packet.SecretKey | packet.SecretSubkey, signatureProperties: object, date: Date, userId: object): packet.Signature; + /** * Class that represents a subkey packet and the relevant signatures. */ @@ -2217,7 +1946,7 @@ export namespace openpgp { * @param primaryKey primary key used for validation * @returns */ - update(subKey: key.SubKey, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + update(subKey: SubKey, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; /** * Revokes the subkey @@ -2228,7 +1957,7 @@ export namespace openpgp { * @param date optional, override the creationtime of the revocation signature * @returns new subkey with revocation signature */ - revoke(primaryKey: packet.SecretKey, reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; + revoke(primaryKey: packet.SecretKey, reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; /** * Calculates the key id of the key @@ -2268,2895 +1997,3166 @@ export namespace openpgp { } /** - * @see module:keyring/keyring - * @see module:keyring/localstore + * Reads an unarmored OpenPGP key list and returns one or multiple key objects + * @param data to be parsed + * @returns result object with key and error arrays */ + function read(data: Uint8Array): Promise<{ keys: Array, err: Array | null }>; + + interface KeyResult { keys: Array, err: Array | null } + + /** + * Reads an OpenPGP armored text and returns one or multiple key objects + * @param armoredText text to be parsed + * @returns result object with key and error arrays + */ + function readArmored(armoredText: string | ReadableStream): Promise; + + /** + * Generates a new OpenPGP key. Supports RSA and ECC keys. + * Primary and subkey will be of same type. + * @param options.keyType To indicate what type of key to make. + * RSA is 1. See {@link https://tools.ietf.org/html/rfc4880#section-9.1} + * @param options.numBits number of bits for the key creation. + * @param options.userIds Assumes already in form of "User Name " + * If array is used, the first userId is set as primary user Id + * @param options.passphrase The passphrase used to encrypt the resulting private key + * @param options.keyExpirationTime The number of seconds after the key creation time that the key expires + * @param curve (optional) elliptic curve for ECC keys + * @param date Override the creation date of the key and the key signatures + * @param subkeys (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + * @returns + */ + function generate(options: KeyOptions): Promise; + + /** + * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. + * @param options.privateKey The private key to reformat + * @param options.keyType + * @param options.userIds Assumes already in form of "User Name " + * If array is used, the first userId is set as primary user Id + * @param options.passphrase The passphrase used to encrypt the resulting private key + * @param options.keyExpirationTime The number of seconds after the key creation time that the key expires + * @param date Override the creation date of the key and the key signatures + * @param subkeys (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * @returns + */ + function reformat(date: Date, subkeys: any[]): Promise; + + /** + * Checks if a given certificate or binding signature is revoked + * @param primaryKey The primary key packet + * @param dataToVerify The data to check + * @param revocations The revocation signatures to check + * @param signature The certificate or signature to check + * @param key, optional The key packet to check the signature + * @param date Use the given date instead of the current time + * @returns True if the signature revokes the data + */ + function isDataRevoked(primaryKey: packet.SecretKey | packet.PublicKey, dataToVerify: object, revocations: any[], signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Check if signature has revocation key sub packet (not supported by OpenPGP.js) + * and throw error if found + * @param signature The certificate or signature to check + * @param keyId Check only certificates or signatures from a certain issuer key ID + */ + function checkRevocationKey(signature: packet.Signature, keyId: type.keyid.Keyid): void; + + /** + * Returns the preferred signature hash algorithm of a key + * @param key (optional) the key to get preferences from + * @param keyPacket key packet used for signing + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID + * @returns + */ + function getPreferredHashAlgo(key: Key, keyPacket: packet.SecretKey | packet.SecretSubkey, date: Date, userId: object): Promise; + + /** + * Returns the preferred symmetric/aead algorithm for a set of keys + * @param {symmetric | aead} type Type of preference to return + * @param keys Set of keys + * @param date (optional) use the given date for verification instead of the current time + * @param userIds (optional) user IDs + * @returns Preferred symmetric algorithm + */ + function getPreferredAlgo(type: any, keys: any[], date: Date, userIds: any[]): Promise; + + /** + * Returns whether aead is supported by all keys in the set + * @param keys Set of keys + * @param date (optional) use the given date for verification instead of the current time + * @param userIds (optional) user IDs + * @returns + */ + function isAeadSupported(keys: any[], date: Date, userIds: any[]): Promise; +} + +export interface revoke_reasonForRevocation { + /** + * optional, flag indicating the reason for revocation + */ + flag: enums.reasonForRevocation; + /** + * optional, string explaining the reason for revocation + */ + string: string; +} + +/** + * Class that represents an user ID or attribute packet and the relevant signatures. + */ +export class User { + constructor(); + + /** + * Transforms structured user data to packetlist + * @returns + */ + toPacketlist(): packet.List; + + /** + * Signs user + * @param primaryKey The primary key packet + * @param privateKeys Decrypted private keys for signing + * @returns New user with new certificate signatures + */ + sign(primaryKey: packet.SecretKey | packet.PublicKey, privateKeys: any[]): Promise; + + /** + * Checks if a given certificate of the user is revoked + * @param primaryKey The primary key packet + * @param certificate The certificate to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the certificate is revoked + */ + isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Verifies the user certificate + * @param primaryKey The primary key packet + * @param certificate A certificate of this user + * @param keys Array of keys to verify certificate signatures + * @param date Use the given date instead of the current time + * @returns status of the certificate + */ + verifyCertificate(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, keys: any[], date: Date): Promise; + + /** + * Verifies all user certificates + * @param primaryKey The primary key packet + * @param keys Array of keys to verify certificate signatures + * @param date Use the given date instead of the current time + * @returns List of signer's keyid and validity of signature + */ + verifyAllCertifications(primaryKey: packet.SecretKey | packet.PublicKey, keys: any[], date: Date): Promise>; + + /** + * Verify User. Checks for existence of self signatures, revocation signatures + * and validity of self signature + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns Status of user + */ + verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Update user with new components from specified user + * @param user Source user to merge + * @param primaryKey primary key used for validation + * @returns + */ + update(user: key.User, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; +} + +/** + * Class that represents a subkey packet and the relevant signatures. + */ +export class SubKey { + constructor(); + + /** + * Transforms structured subkey data to packetlist + * @returns + */ + toPacketlist(): packet.List; + + /** + * Checks if a binding signature of a subkey is revoked + * @param primaryKey The primary key packet + * @param signature The binding signature to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the binding signature is revoked + */ + isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Verify subkey. Checks for revocation signatures, expiration time + * and valid binding signature + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns The status of the subkey + */ + verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Returns the expiration time of the subkey or Infinity if key does not expire + * Returns null if the subkey is invalid. + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns + */ + getExpirationTime(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Update subkey with new components from specified subkey + * @param subKey Source subkey to merge + * @param primaryKey primary key used for validation + * @returns + */ + update(subKey: key.SubKey, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + + /** + * Revokes the subkey + * @param primaryKey decrypted private primary key for revocation + * @param reasonForRevocation optional, object indicating the reason for revocation + * @param reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param reasonForRevocation.string optional, string explaining the reason for revocation + * @param date optional, override the creationtime of the revocation signature + * @returns new subkey with revocation signature + */ + revoke(primaryKey: packet.SecretKey, reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; +} + +/** + * @see module:keyring/keyring + * @see module:keyring/localstore + */ +export namespace keyring { namespace keyring { - namespace keyring { - class Keyring { - /** - * Initialization routine for the keyring. - * @param storeHandler class implementing loadPublic(), loadPrivate(), storePublic(), and storePrivate() methods - */ - constructor(storeHandler?: localstore.LocalStore); - - /** - * Calls the storeHandler to load the keys - */ - load(): void; - - /** - * Calls the storeHandler to save the keys - */ - store(): void; - - /** - * Clear the keyring - erase all the keys - */ - clear(): void; - - /** - * Searches the keyring for keys having the specified key id - * @param keyId provided as string of lowercase hex number - * withouth 0x prefix (can be 16-character key ID or fingerprint) - * @param deep if true search also in subkeys - * @returns keys found or null - */ - getKeysForId(keyId: string, deep: boolean): any[] | null; - - /** - * Removes keys having the specified key id from the keyring - * @param keyId provided as string of lowercase hex number - * withouth 0x prefix (can be 16-character key ID or fingerprint) - * @returns keys found or null - */ - removeKeysForId(keyId: string): any[] | null; - - /** - * Get all public and private keys - * @returns all keys - */ - getAllKeys(): any[]; - } + class Keyring { + /** + * Initialization routine for the keyring. + * @param storeHandler class implementing loadPublic(), loadPrivate(), storePublic(), and storePrivate() methods + */ + constructor(storeHandler?: localstore.LocalStore); /** - * Array of keys - * @param keys The keys to store in this array + * Calls the storeHandler to load the keys */ - function KeyArray(keys: any[]): void; + load(): void; + + /** + * Calls the storeHandler to save the keys + */ + store(): void; + + /** + * Clear the keyring - erase all the keys + */ + clear(): void; + + /** + * Searches the keyring for keys having the specified key id + * @param keyId provided as string of lowercase hex number + * withouth 0x prefix (can be 16-character key ID or fingerprint) + * @param deep if true search also in subkeys + * @returns keys found or null + */ + getKeysForId(keyId: string, deep: boolean): any[] | null; + + /** + * Removes keys having the specified key id from the keyring + * @param keyId provided as string of lowercase hex number + * withouth 0x prefix (can be 16-character key ID or fingerprint) + * @returns keys found or null + */ + removeKeysForId(keyId: string): any[] | null; + + /** + * Get all public and private keys + * @returns all keys + */ + getAllKeys(): any[]; } - namespace localstore { - class LocalStore { - /** - * The class that deals with storage of the keyring. - * Currently the only option is to use HTML5 local storage. - * @param prefix prefix for itemnames in localstore - */ - constructor(prefix: string); - - /** - * Load the public keys from HTML5 local storage. - * @returns array of keys retrieved from localstore - */ - loadPublic(): any[]; - - /** - * Load the private keys from HTML5 local storage. - * @returns array of keys retrieved from localstore - */ - loadPrivate(): any[]; - - /** - * Saves the current state of the public keys to HTML5 local storage. - * The key array gets stringified using JSON - * @param keys array of keys to save in localstore - */ - storePublic(keys: any[]): void; - - /** - * Saves the current state of the private keys to HTML5 local storage. - * The key array gets stringified using JSON - * @param keys array of keys to save in localstore - */ - storePrivate(keys: any[]): void; - } - } + /** + * Array of keys + * @param keys The keys to store in this array + */ + function KeyArray(keys: any[]): void; } - class LocalStore { - /** - * The class that deals with storage of the keyring. - * Currently the only option is to use HTML5 local storage. - * @param prefix prefix for itemnames in localstore - */ - constructor(prefix: string); - - /** - * Load the public keys from HTML5 local storage. - * @returns array of keys retrieved from localstore - */ - loadPublic(): any[]; - - /** - * Load the private keys from HTML5 local storage. - * @returns array of keys retrieved from localstore - */ - loadPrivate(): any[]; - - /** - * Saves the current state of the public keys to HTML5 local storage. - * The key array gets stringified using JSON - * @param keys array of keys to save in localstore - */ - storePublic(keys: any[]): void; - - /** - * Saves the current state of the private keys to HTML5 local storage. - * The key array gets stringified using JSON - * @param keys array of keys to save in localstore - */ - storePrivate(keys: any[]): void; - } - - namespace message { - /** - * Class that represents an OpenPGP message. - * Can be an encrypted message, signed message, compressed message or literal message - */ - class Message { - packets: packet.List; + namespace localstore { + class LocalStore { + /** + * The class that deals with storage of the keyring. + * Currently the only option is to use HTML5 local storage. + * @param prefix prefix for itemnames in localstore + */ + constructor(prefix: string); /** - * @param packetlist The packets that form this message - * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + * Load the public keys from HTML5 local storage. + * @returns array of keys retrieved from localstore */ - constructor(packetlist: packet.List); + loadPublic(): any[]; /** - * Returns the key IDs of the keys to which the session key is encrypted - * @returns array of keyid objects + * Load the private keys from HTML5 local storage. + * @returns array of keys retrieved from localstore */ - getEncryptionKeyIds(): any[]; + loadPrivate(): any[]; /** - * Returns the key IDs of the keys that signed the message - * @returns array of keyid objects + * Saves the current state of the public keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore */ - getSigningKeyIds(): any[]; + storePublic(keys: any[]): void; /** - * Decrypt the message. Either a private key, a session key, or a password must be specified. - * @param privateKeys (optional) private keys with decrypted secret data - * @param passwords (optional) passwords used to decrypt - * @param sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } - * @param streaming (optional) whether to process data as a stream - * @returns new message with decrypted content + * Saves the current state of the private keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore */ - decrypt(privateKeys?: any[], passwords?: any[], sessionKeys?: any[], streaming?: boolean): Promise; - - /** - * Decrypt encrypted session keys either with private keys or passwords. - * @param privateKeys (optional) private keys with decrypted secret data - * @param passwords (optional) passwords used to decrypt - * @returns array of object with potential sessionKey, algorithm pairs - */ - decryptSessionKeys(privateKeys?: any[], passwords?: any[]): Promise>; - - /** - * Get literal data that is the body of the message - * @returns literal body of the message as Uint8Array - */ - getLiteralData(): Uint8Array | null; - - /** - * Get filename from literal data packet - * @returns filename of literal data packet as string - */ - getFilename(): string | null; - - /** - * Get literal data as text - * @returns literal body of the message interpreted as text - */ - getText(): string | null; - - /** - * Encrypt the message either with public keys, passwords, or both at once. - * @param keys (optional) public key(s) for message encryption - * @param passwords (optional) password(s) for message encryption - * @param sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } - * @param wildcard (optional) use a key ID of 0 instead of the public key IDs - * @param date (optional) override the creation date of the literal package - * @param userIds (optional) user IDs to encrypt for, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] - * @param streaming (optional) whether to process data as a stream - * @returns new message with encrypted content - */ - encrypt(keys?: any[], passwords?: any[], sessionKey?: object, wildcard?: boolean, date?: Date, userIds?: any[], streaming?: boolean): Promise; - - /** - * Sign the message (the literal data packet of the message) - * @param privateKeys private keys with decrypted secret key data for signing - * @param signature (optional) any existing detached signature to add to the message - * @param date (optional) override the creation time of the signature - * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - * @returns new message with signed content - */ - sign(privateKeys: any[], signature?: signature.Signature, date?: Date, userIds?: any[]): Promise; - - /** - * Compresses the message (the literal and -if signed- signature data packets of the message) - * @param compression compression algorithm to be used - * @returns new message with compressed content - */ - compress(compression: enums.compression): Message; - - /** - * Create a detached signature for the message (the literal data packet of the message) - * @param privateKeys private keys with decrypted secret key data for signing - * @param signature (optional) any existing detached signature - * @param date (optional) override the creation time of the signature - * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - * @returns new detached signature of message content - */ - signDetached(privateKeys: any[], signature?: signature.Signature, date?: Date, userIds?: any[]): Promise; - - /** - * Verify message signatures - * @param keys array of keys to verify signatures - * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param streaming (optional) whether to process data as a stream - * @returns list of signer's keyid and validity of signature - */ - verify(keys: any[], date?: Date, streaming?: boolean): Promise>; - - /** - * Verify detached message signature - * @param keys array of keys to verify signatures - * @param signature - * @param date Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @returns list of signer's keyid and validity of signature - */ - verifyDetached(keys: any[], signature: signature.Signature, date?: Date): Promise>; - - /** - * Unwrap compressed message - * @returns message Content of compressed message - */ - unwrapCompressed(): Message; - - /** - * Append signature to unencrypted message object - * @param detachedSignature The detached ASCII-armored or Uint8Array PGP signature - */ - appendSignature(detachedSignature: string | Uint8Array): void; - - /** - * Returns ASCII armored text of message - * @returns ASCII armor - */ - armor(): ReadableStream; + storePrivate(keys: any[]): void; } + } +} + +export class LocalStore { + /** + * The class that deals with storage of the keyring. + * Currently the only option is to use HTML5 local storage. + * @param prefix prefix for itemnames in localstore + */ + constructor(prefix: string); + + /** + * Load the public keys from HTML5 local storage. + * @returns array of keys retrieved from localstore + */ + loadPublic(): any[]; + + /** + * Load the private keys from HTML5 local storage. + * @returns array of keys retrieved from localstore + */ + loadPrivate(): any[]; + + /** + * Saves the current state of the public keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore + */ + storePublic(keys: any[]): void; + + /** + * Saves the current state of the private keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore + */ + storePrivate(keys: any[]): void; +} + +export namespace message { + /** + * Class that represents an OpenPGP message. + * Can be an encrypted message, signed message, compressed message or literal message + */ + class Message { + packets: packet.List; /** - * Encrypt a session key either with public keys, passwords, or both at once. - * @param sessionKey session key for encryption - * @param symAlgo session key algorithm - * @param aeadAlgo (optional) aead algorithm, e.g. 'eax' or 'ocb' - * @param publicKeys (optional) public key(s) for message encryption - * @param passwords (optional) for message encryption + * @param packetlist The packets that form this message + * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + */ + constructor(packetlist: packet.List); + + /** + * Returns the key IDs of the keys to which the session key is encrypted + * @returns array of keyid objects + */ + getEncryptionKeyIds(): any[]; + + /** + * Returns the key IDs of the keys that signed the message + * @returns array of keyid objects + */ + getSigningKeyIds(): any[]; + + /** + * Decrypt the message. Either a private key, a session key, or a password must be specified. + * @param privateKeys (optional) private keys with decrypted secret data + * @param passwords (optional) passwords used to decrypt + * @param sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param streaming (optional) whether to process data as a stream + * @returns new message with decrypted content + */ + decrypt(privateKeys?: any[], passwords?: any[], sessionKeys?: any[], streaming?: boolean): Promise; + + /** + * Decrypt encrypted session keys either with private keys or passwords. + * @param privateKeys (optional) private keys with decrypted secret data + * @param passwords (optional) passwords used to decrypt + * @returns array of object with potential sessionKey, algorithm pairs + */ + decryptSessionKeys(privateKeys?: any[], passwords?: any[]): Promise>; + + /** + * Get literal data that is the body of the message + * @returns literal body of the message as Uint8Array + */ + getLiteralData(): Uint8Array | null; + + /** + * Get filename from literal data packet + * @returns filename of literal data packet as string + */ + getFilename(): string | null; + + /** + * Get literal data as text + * @returns literal body of the message interpreted as text + */ + getText(): string | null; + + /** + * Encrypt the message either with public keys, passwords, or both at once. + * @param keys (optional) public key(s) for message encryption + * @param passwords (optional) password(s) for message encryption + * @param sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } * @param wildcard (optional) use a key ID of 0 instead of the public key IDs - * @param date (optional) override the date + * @param date (optional) override the creation date of the literal package * @param userIds (optional) user IDs to encrypt for, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param streaming (optional) whether to process data as a stream * @returns new message with encrypted content */ - function encryptSessionKey(sessionKey: Uint8Array, symAlgo: string, aeadAlgo: string, publicKeys: any[], passwords: any[], wildcard: boolean, date: Date, userIds: any[]): Promise; + encrypt(keys?: any[], passwords?: any[], sessionKey?: object, wildcard?: boolean, date?: Date, userIds?: any[], streaming?: boolean): Promise; /** - * Create signature packets for the message - * @param literalDataPacket the literal data packet to sign + * Sign the message (the literal data packet of the message) * @param privateKeys private keys with decrypted secret key data for signing - * @param signature (optional) any existing detached signature to append - * @param date (optional) override the creationtime of the signature + * @param signature (optional) any existing detached signature to add to the message + * @param date (optional) override the creation time of the signature * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - * @returns list of signature packets + * @returns new message with signed content */ - function createSignaturePackets(literalDataPacket: packet.Literal, privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; + sign(privateKeys: any[], signature?: signature.Signature, date?: Date, userIds?: any[]): Promise; /** - * Create object containing signer's keyid and validity of signature - * @param signature signature packets - * @param literalDataList array of literal data packets + * Compresses the message (the literal and -if signed- signature data packets of the message) + * @param compression compression algorithm to be used + * @returns new message with compressed content + */ + compress(compression: enums.compression): Message; + + /** + * Create a detached signature for the message (the literal data packet of the message) + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature + * @param date (optional) override the creation time of the signature + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new detached signature of message content + */ + signDetached(privateKeys: any[], signature?: signature.Signature, date?: Date, userIds?: any[]): Promise; + + /** + * Verify message signatures * @param keys array of keys to verify signatures - * @param date Verify the signature against the given date, - * i.e. check signature creation time < date < expiration time + * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param streaming (optional) whether to process data as a stream * @returns list of signer's keyid and validity of signature */ - function createVerificationObject(signature: packet.Signature, literalDataList: any[], keys: any[], date: Date): Promise>; + verify(keys: any[], date?: Date, streaming?: boolean): Promise>; /** - * Create list of objects containing signer's keyid and validity of signature - * @param signatureList array of signature packets - * @param literalDataList array of literal data packets + * Verify detached message signature * @param keys array of keys to verify signatures - * @param date Verify the signature against the given date, - * i.e. check signature creation time < date < expiration time + * @param signature + * @param date Verify the signature against the given date, i.e. check signature creation time < date < expiration time * @returns list of signer's keyid and validity of signature */ - function createVerificationObjects(signatureList: any[], literalDataList: any[], keys: any[], date: Date): Promise>; + verifyDetached(keys: any[], signature: signature.Signature, date?: Date): Promise>; /** - * reads an OpenPGP armored message and returns a message object - * @param armoredText text to be parsed - * @returns new message object + * Unwrap compressed message + * @returns message Content of compressed message */ - function readArmored(armoredText: string | ReadableStream): Promise; + unwrapCompressed(): Message; /** - * reads an OpenPGP message as byte array and returns a message object - * @param input binary message - * @param fromStream whether the message was created from a Stream - * @returns new message object + * Append signature to unencrypted message object + * @param detachedSignature The detached ASCII-armored or Uint8Array PGP signature */ - function read(input: Uint8Array | ReadableStream, fromStream?: boolean): Promise; + appendSignature(detachedSignature: string | Uint8Array): void; /** - * creates new message object from text - * @param text - * @param filename (optional) - * @param date (optional) - * @param {utf8 | binary | text | mime} type (optional) data packet type - * @returns new message object + * Returns ASCII armored text of message + * @returns ASCII armor */ - function fromText(text: string | ReadableStream, filename?: string, date?: Date, type?: any): Message; - - /** - * creates new message object from binary data - * @param bytes - * @param filename (optional) - * @param date (optional) - * @param {utf8 | binary | text | mime} type (optional) data packet type - * @returns new message object - */ - function fromBinary(bytes: Uint8Array | ReadableStream, filename?: string, date?: Date, type?: any): Message; - } - - interface revokeKey_reasonForRevocation { - /** - * (optional) flag indicating the reason for revocation - */ - flag: enums.reasonForRevocation; - /** - * (optional) string explaining the reason for revocation - */ - string: string; + armor(): ReadableStream; } /** - * @see module:packet/all_packets - * @see module:packet/clone - * @see module:packet.List + * Encrypt a session key either with public keys, passwords, or both at once. + * @param sessionKey session key for encryption + * @param symAlgo session key algorithm + * @param aeadAlgo (optional) aead algorithm, e.g. 'eax' or 'ocb' + * @param publicKeys (optional) public key(s) for message encryption + * @param passwords (optional) for message encryption + * @param wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param date (optional) override the date + * @param userIds (optional) user IDs to encrypt for, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] + * @returns new message with encrypted content */ + function encryptSessionKey(sessionKey: Uint8Array, symAlgo: string, aeadAlgo: string, publicKeys: any[], passwords: any[], wildcard: boolean, date: Date, userIds: any[]): Promise; + + /** + * Create signature packets for the message + * @param literalDataPacket the literal data packet to sign + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature to append + * @param date (optional) override the creationtime of the signature + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns list of signature packets + */ + function createSignaturePackets(literalDataPacket: packet.Literal, privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; + + /** + * Create object containing signer's keyid and validity of signature + * @param signature signature packets + * @param literalDataList array of literal data packets + * @param keys array of keys to verify signatures + * @param date Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + function createVerificationObject(signature: packet.Signature, literalDataList: any[], keys: any[], date: Date): Promise>; + + /** + * Create list of objects containing signer's keyid and validity of signature + * @param signatureList array of signature packets + * @param literalDataList array of literal data packets + * @param keys array of keys to verify signatures + * @param date Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + function createVerificationObjects(signatureList: any[], literalDataList: any[], keys: any[], date: Date): Promise>; + + /** + * reads an OpenPGP armored message and returns a message object + * @param armoredText text to be parsed + * @returns new message object + */ + function readArmored(armoredText: string | ReadableStream): Promise; + + /** + * reads an OpenPGP message as byte array and returns a message object + * @param input binary message + * @param fromStream whether the message was created from a Stream + * @returns new message object + */ + function read(input: Uint8Array | ReadableStream, fromStream?: boolean): Promise; + + /** + * creates new message object from text + * @param text + * @param filename (optional) + * @param date (optional) + * @param {utf8 | binary | text | mime} type (optional) data packet type + * @returns new message object + */ + function fromText(text: string | ReadableStream, filename?: string, date?: Date, type?: any): Message; + + /** + * creates new message object from binary data + * @param bytes + * @param filename (optional) + * @param date (optional) + * @param {utf8 | binary | text | mime} type (optional) data packet type + * @returns new message object + */ + function fromBinary(bytes: Uint8Array | ReadableStream, filename?: string, date?: Date, type?: any): Message; +} + +export interface revokeKey_reasonForRevocation { + /** + * (optional) flag indicating the reason for revocation + */ + flag: enums.reasonForRevocation; + /** + * (optional) string explaining the reason for revocation + */ + string: string; +} + +/** + * @see module:packet/all_packets + * @see module:packet/clone + * @see module:packet.List + */ +export namespace packet { + /** + * Allocate a new packet + * @param tag property name from {@link module:enums.packet} + * @returns new packet object with type based on tag + */ + function newPacketFromTag(tag: string): object; + + /** + * Allocate a new packet from structured packet clone + * @see + * @param packetClone packet clone + * @returns new packet object with data from packet clone + */ + function fromStructuredClone(packetClone: object): object; + + class Compressed { + /** + * Implementation of the Compressed Data Packet (Tag 8) + * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: + * The Compressed Data packet contains compressed data. Typically, + * this packet is found as the contents of an encrypted packet, or following + * a Signature or One-Pass Signature packet, and contains a literal data packet. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * List of packets + */ + packets: List; + + /** + * Compression algorithm + * @type {compression} + */ + algorithm: any; + + /** + * Compressed packet data + */ + compressed: Uint8Array | ReadableStream; + + /** + * Parsing function for the packet. + * @param bytes Payload of a tag 8 packet + */ + read(bytes: Uint8Array | ReadableStream): void; + + /** + * Return the compressed packet. + * @returns binary compressed packet + */ + write(): Uint8Array | ReadableStream; + + /** + * Decompression method for decompressing the compressed data + * read by read_packet + */ + decompress(): void; + + /** + * Compress the packet data (member decompressedData) + */ + compress(): void; + } + + class Literal { + /** + * Implementation of the Literal Data Packet (Tag 11) + * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: + * A Literal Data packet contains the body of a message; data that is not to be + * further interpreted. + * @param date the creation date of the literal package + */ + constructor(date: Date); + + /** + * Set the packet data to a javascript native string, end of line + * will be normalized to \r\n and by default text is converted to UTF8 + * @param text Any native javascript string + * @param {utf8 | binary | text | mime} format (optional) The format of the string of bytes + */ + setText(text: string | ReadableStream, format: any): void; + + /** + * Returns literal data packets as native JavaScript string + * with normalized end of line to \n + * @param clone (optional) Whether to return a clone so that getBytes/getText can be called again + * @returns literal data as text + */ + getText(clone: boolean): string | ReadableStream; + + /** + * Set the packet data to value represented by the provided string of bytes. + * @param bytes The string of bytes + * @param {utf8 | binary | text | mime} format The format of the string of bytes + */ + setBytes(bytes: Uint8Array | ReadableStream, format: any): void; + + /** + * Get the byte sequence representing the literal packet data + * @param clone (optional) Whether to return a clone so that getBytes/getText can be called again + * @returns A sequence of bytes + */ + getBytes(clone: boolean): Uint8Array | ReadableStream; + + /** + * Sets the filename of the literal packet data + * @param filename Any native javascript string + */ + setFilename(filename: string): void; + + /** + * Get the filename of the literal packet data + * @returns filename + */ + getFilename(): string; + + /** + * Parsing function for a literal data packet (tag 11). + * @param input Payload of a tag 11 packet + * @returns object representation + */ + read(input: Uint8Array | ReadableStream): Literal; + + /** + * Creates a string representation of the packet + * @returns Uint8Array representation of the packet + */ + write(): Uint8Array | ReadableStream; + } + + class Marker { + /** + * Implementation of the strange "Marker packet" (Tag 10) + * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: + * An experimental version of PGP used this packet as the Literal + * packet, but no released version of PGP generated Literal packets with this + * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as + * the Marker packet. + * Such a packet MUST be ignored when received. + */ + constructor(); + + /** + * Parsing function for a literal data packet (tag 10). + * @param input Payload of a tag 10 packet + * @param position Position to start reading from the input string + * @param len Length of the packet or the remaining length of + * input at position + * @returns Object representation + */ + read(input: string, position: Integer, len: Integer): Marker; + } + + class OnePassSignature { + /** + * Implementation of the One-Pass Signature Packets (Tag 4) + * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: + * The One-Pass Signature packet precedes the signed data and contains + * enough information to allow the receiver to begin calculating any + * hashes needed to verify the signature. It allows the Signature + * packet to be placed at the end of the message, so that the signer + * can compute the entire signed message in one pass. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * A one-octet version number. The current version is 3. + */ + version: any; + + /** + * A one-octet signature type. + * Signature types are described in + * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. + */ + signatureType: any; + + /** + * A one-octet number describing the hash algorithm used. + * @see + */ + hashAlgorithm: any; + + /** + * A one-octet number describing the public-key algorithm used. + * @see + */ + publicKeyAlgorithm: any; + + /** + * An eight-octet number holding the Key ID of the signing key. + */ + issuerKeyId: any; + + /** + * A one-octet number holding a flag showing whether the signature is nested. + * A zero value indicates that the next packet is another One-Pass Signature packet + * that describes another signature to be applied to the same message data. + */ + flags: any; + + /** + * parsing function for a one-pass signature packet (tag 4). + * @param bytes payload of a tag 4 packet + * @returns object representation + */ + read(bytes: Uint8Array): OnePassSignature; + + /** + * creates a string representation of a one-pass signature packet + * @returns a Uint8Array representation of a one-pass signature packet + */ + write(): Uint8Array; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class List { + /** + * This class represents a list of openpgp packets. + * Take care when iterating over it - the packets themselves + * are stored as numerical indices. + */ + constructor(); + + /** + * The number of packets contained within the list. + */ + readonly length: Integer; + + /** + * Reads a stream of binary data and interprents it as a list of packets. + * @param A Uint8Array of bytes. + */ + read(A: Uint8Array | ReadableStream): void; + + /** + * Creates a binary representation of openpgp objects contained within the + * class instance. + * @returns A Uint8Array containing valid openpgp packets. + */ + write(): Uint8Array; + + /** + * Adds a packet to the list. This is the only supported method of doing so; + * writing to packetlist[i] directly will result in an error. + * @param packet Packet to push + */ + push(packet: object): void; + + /** + * Creates a new PacketList with all packets from the given types + */ + filterByTag(): void; + + /** + * Traverses packet tree and returns first matching packet + * @param type The packet type + * @returns + */ + findPacket(type: enums.packet): List | undefined; + + /** + * Returns array of found indices by tag + */ + indexOfTag(): void; + + /** + * Concatenates packetlist or array of packets + */ + concat(): void; + + /** + * Allocate a new packetlist from structured packetlist clone + * See {@link https://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data} + * @param packetClone packetlist clone + * @returns new packetlist object with data from packetlist clone + */ + static fromStructuredClone(packetClone: object): object; + } + + class PublicKey { + /** + * Implementation of the Key Material Packet (Tag 5,6,7,14) + * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: + * A key material packet contains all the information about a public or + * private key. There are four variants of this packet type, and two + * major versions. + * A Public-Key packet starts a series of packets that forms an OpenPGP + * key (sometimes called an OpenPGP certificate). + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} + * called by read_tag<num> + * @param bytes Input array to read the packet from + * @returns This object with attributes set by the parser + */ + read(bytes: Uint8Array): object; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Same as write_private_key, but has less information because of + * public key. + * @returns OpenPGP packet body contents, + */ + write(): Uint8Array; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class PublicKeyEncryptedSessionKey { + /** + * Public-Key Encrypted Session Key Packets (Tag 1) + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + */ + constructor(); + + encrypted: any[]; + + /** + * Parsing function for a publickey encrypted session key packet (tag 1). + * @param input Payload of a tag 1 packet + * @param position Position to start reading from the input string + * @param len Length of the packet or the remaining length of + * input at position + * @returns Object representation + */ + read(input: Uint8Array, position: Integer, len: Integer): PublicKeyEncryptedSessionKey + + /** + * Create a string representation of a tag 1 packet + * @returns The Uint8Array representation + */ + write(): Uint8Array; + + /** + * Encrypt session key packet + * @param key Public key + * @returns + */ + encrypt(key: PublicKey): Promise; + + /** + * Decrypts the session key (only for public key encrypted session key + * packets (tag 1) + * @param key Private key with secret params unlocked + * @returns + */ + decrypt(key: SecretKey): Promise; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class PublicSubkey { + /** + * A Public-Subkey packet (tag 14) has exactly the same format as a + * Public-Key packet, but denotes a subkey. One or more subkeys may be + * associated with a top-level key. By convention, the top-level key + * provides signature services, and the subkeys provide encryption + * services. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} + * called by read_tag<num> + * @param bytes Input array to read the packet from + * @returns This object with attributes set by the parser + */ + read(bytes: Uint8Array): object; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Same as write_private_key, but has less information because of + * public key. + * @returns OpenPGP packet body contents, + */ + write(): Uint8Array; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class SecretKey { + /** + * A Secret-Key packet contains all the information that is found in a + * Public-Key packet, including the public-key material, but also + * includes the secret-key material after all the public-key fields. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Encrypted secret-key data + */ + encrypted: any; + + /** + * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. + */ + isEncrypted: any; + + /** + * Internal parser for private keys as specified in + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} + * @param bytes Input string to read the packet from + */ + read(bytes: string): void; + + /** + * Creates an OpenPGP key packet for the given key. + * @returns A string of bytes containing the secret key OpenPGP packet + */ + write(): string; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Encrypt the payload. By default, we use aes256 and iterated, salted string + * to key specifier. If the key is in a decrypted state (isEncrypted === false) + * and the passphrase is empty or undefined, the key will be set as not encrypted. + * This can be used to remove passphrase protection after calling decrypt(). + * @param passphrase + * @returns + */ + encrypt(passphrase: string): Promise; + + /** + * Decrypts the private key params which are needed to use the key. + * {@link module:packet.SecretKey.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param passphrase The passphrase for this private key as string + * @returns + */ + decrypt(passphrase: string): Promise; + + /** + * Clear private params, return to initial state + */ + clearPrivateParams(): void; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + } + + class SecretSubkey { + /** + * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret + * Key packet and has exactly the same format. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Encrypted secret-key data + */ + encrypted: any; + + /** + * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. + */ + isEncrypted: any; + + /** + * Internal parser for private keys as specified in + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} + * @param bytes Input string to read the packet from + */ + read(bytes: string): void; + + /** + * Creates an OpenPGP key packet for the given key. + * @returns A string of bytes containing the secret key OpenPGP packet + */ + write(): string; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Encrypt the payload. By default, we use aes256 and iterated, salted string + * to key specifier. If the key is in a decrypted state (isEncrypted === false) + * and the passphrase is empty or undefined, the key will be set as not encrypted. + * This can be used to remove passphrase protection after calling decrypt(). + * @param passphrase + * @returns + */ + encrypt(passphrase: string): Promise; + + /** + * Decrypts the private key params which are needed to use the key. + * {@link module:packet.SecretKey.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param passphrase The passphrase for this private key as string + * @returns + */ + decrypt(passphrase: string): Promise; + + /** + * Clear private params, return to initial state + */ + clearPrivateParams(): void; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + } + + class Signature { + /** + * Implementation of the Signature Packet (Tag 2) + * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: + * A Signature packet describes a binding between some public key and + * some data. The most common signatures are a signature of a file or a + * block of text, and a signature that is a certification of a User ID. + * @param date the creation date of the signature + */ + constructor(date: Date); + + /** + * parsing function for a signature packet (tag 2). + * @param bytes payload of a tag 2 packet + * @param position position to start reading from the bytes string + * @param len length of the packet or the remaining length of bytes at position + * @returns object representation + */ + read(bytes: string, position: Integer, len: Integer): Signature; + + /** + * Signs provided data. This needs to be done prior to serialization. + * @param key private key used to sign the message. + * @param data Contains packets to be signed. + * @returns + */ + sign(key: SecretKey, data: object): Promise; + + /** + * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets + * @returns subpacket data + */ + write_hashed_sub_packets(): Uint8Array; + + /** + * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets + * @returns subpacket data + */ + write_unhashed_sub_packets(): Uint8Array; + + /** + * verifys the signature packet. Note: not signature types are implemented + * @param key the public key to verify the signature + * @param signatureType expected signature type + * @param data data which on the signature applies + * @returns True if message is verified, else false. + */ + verify(key: PublicSubkey | PublicKey | SecretSubkey | SecretKey, signatureType: enums.signature, data: string | object): Promise; + + /** + * Verifies signature expiration date + * @param date (optional) use the given date for verification instead of the current time + * @returns true if expired + */ + isExpired(date: Date): boolean; + + /** + * Returns the expiration time of the signature or Infinity if signature does not expire + * @returns expiration time + */ + getExpirationTime(): Date; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class SymEncryptedAEADProtected { + /** + * Implementation of the Symmetrically Encrypted Authenticated Encryption with + * Additional Data (AEAD) Protected Data Packet + * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: + * AEAD Protected Data Packet + */ + constructor(); + + /** + * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @param bytes + */ + read(bytes: Uint8Array | ReadableStream): void; + + /** + * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @returns The encrypted payload + */ + write(): Uint8Array | ReadableStream; + + /** + * Decrypt the encrypted payload. + * @param sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' + * @param key The session key used to encrypt the payload + * @param streaming Whether the top-level function will return a stream + * @returns + */ + decrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): boolean; + + /** + * Encrypt the packet list payload. + * @param sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' + * @param key The session key used to encrypt the payload + * @param streaming Whether the top-level function will return a stream + */ + encrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): void; + + /** + * En/decrypt the payload. + * @param {encrypt | decrypt} fn Whether to encrypt or decrypt + * @param key The session key used to en/decrypt the payload + * @param data The data to en/decrypt + * @param streaming Whether the top-level function will return a stream + * @returns + */ + crypt(fn: any, key: Uint8Array, data: Uint8Array | ReadableStream, streaming: boolean): Uint8Array | ReadableStream; + } + + class SymEncryptedIntegrityProtected { + /** + * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) + * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: + * The Symmetrically Encrypted Integrity Protected Data packet is + * a variant of the Symmetrically Encrypted Data packet. It is a new feature + * created for OpenPGP that addresses the problem of detecting a modification to + * encrypted data. It is used in combination with a Modification Detection Code + * packet. + */ + constructor(); + + /** + * The encrypted payload. + */ + encrypted: any; + + /** + * If after decrypting the packet this is set to true, + * a modification has been detected and thus the contents + * should be discarded. + */ + modification: boolean; + + /** + * Encrypt the payload in the packet. + * @param sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' + * @param key The key of cipher blocksize length to be used + * @param streaming Whether to set this.encrypted to a stream + * @returns + */ + encrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): Promise; + + /** + * Decrypts the encrypted data contained in the packet. + * @param sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' + * @param key The key of cipher blocksize length to be used + * @param streaming Whether to read this.encrypted as a stream + * @returns + */ + decrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): Promise; + } + + class SymEncryptedSessionKey { + /** + * Public-Key Encrypted Session Key Packets (Tag 1) + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + */ + constructor(); + + /** + * Parsing function for a symmetric encrypted session key packet (tag 3). + * @param input Payload of a tag 1 packet + * @param position Position to start reading from the input string + * @param len Length of the packet or the remaining length of + * input at position + * @returns Object representation + */ + read(input: Uint8Array, position: Integer, len: Integer): SymEncryptedSessionKey; + + /** + * Decrypts the session key + * @param passphrase The passphrase in string form + * @returns + */ + decrypt(passphrase: string): Promise; + + /** + * Encrypts the session key + * @param passphrase The passphrase in string form + * @returns + */ + encrypt(passphrase: string): Promise; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class SymmetricallyEncrypted { + /** + * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) + * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: + * The Symmetrically Encrypted Data packet contains data encrypted with a + * symmetric-key algorithm. When it has been decrypted, it contains other + * packets (usually a literal data packet or compressed data packet, but in + * theory other Symmetrically Encrypted Data packets or sequences of packets + * that form whole OpenPGP messages). + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Encrypted secret-key data + */ + encrypted: any; + + /** + * Decrypted packets contained within. + */ + packets: List; + + /** + * When true, decrypt fails if message is not integrity protected + * @see module:config.ignore_mdc_error + */ + ignore_mdc_error: any; + + /** + * Decrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param sessionKeyAlgorithm Symmetric key algorithm to use + * @param key The key of cipher blocksize length to be used + * @returns + */ + decrypt(sessionKeyAlgorithm: enums.symmetric, key: Uint8Array): Promise; + + /** + * Encrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param sessionKeyAlgorithm Symmetric key algorithm to use + * @param key The key of cipher blocksize length to be used + * @returns + */ + encrypt(sessionKeyAlgorithm: enums.symmetric, key: Uint8Array): Promise; + } + + class Trust { + /** + * Implementation of the Trust Packet (Tag 12) + * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: + * The Trust packet is used only within keyrings and is not normally + * exported. Trust packets contain data that record the user's + * specifications of which key holders are trustworthy introducers, + * along with other information that implementing software uses for + * trust information. The format of Trust packets is defined by a given + * implementation. + * Trust packets SHOULD NOT be emitted to output streams that are + * transferred to other users, and they SHOULD be ignored on any input + * other than local keyring files. + */ + constructor(); + + /** + * Parsing function for a trust packet (tag 12). + * Currently not implemented as we ignore trust packets + * @param byptes payload of a tag 12 packet + */ + read(byptes: string): void; + } + + class UserAttribute { + /** + * Implementation of the User Attribute Packet (Tag 17) + * The User Attribute packet is a variation of the User ID packet. It + * is capable of storing more types of data than the User ID packet, + * which is limited to text. Like the User ID packet, a User Attribute + * packet may be certified by the key owner ("self-signed") or any other + * key owner who cares to certify it. Except as noted, a User Attribute + * packet may be used anywhere that a User ID packet may be used. + * While User Attribute packets are not a required part of the OpenPGP + * standard, implementations SHOULD provide at least enough + * compatibility to properly handle a certification signature on the + * User Attribute packet. A simple way to do this is by treating the + * User Attribute packet as a User ID packet with opaque contents, but + * an implementation may use any method desired. + */ + constructor(); + + /** + * parsing function for a user attribute packet (tag 17). + * @param input payload of a tag 17 packet + */ + read(input: Uint8Array): void; + + /** + * Creates a binary representation of the user attribute packet + * @returns string representation + */ + write(): Uint8Array; + + /** + * Compare for equality + * @param usrAttr + * @returns true if equal + */ + equals(usrAttr: UserAttribute): boolean; + } + + class Userid { + /** + * Implementation of the User ID Packet (Tag 13) + * A User ID packet consists of UTF-8 text that is intended to represent + * the name and email address of the key holder. By convention, it + * includes an RFC 2822 [RFC2822] mail name-addr, but there are no + * restrictions on its content. The packet length in the header + * specifies the length of the User ID. + */ + constructor(); + + /** + * A string containing the user id. Usually in the form + * John Doe + */ + userid: string; + + /** + * Parsing function for a user id packet (tag 13). + * @param input payload of a tag 13 packet + */ + read(input: Uint8Array): void; + + /** + * Parse userid string, e.g. 'John Doe ' + */ + parse(): void; + + /** + * Creates a binary representation of the user id packet + * @returns binary representation + */ + write(): Uint8Array; + + /** + * Set userid string from object, e.g. { name:'Phil Zimmermann', email:'phil@openpgp.org' } + */ + format(): void; + } + + namespace all_packets { + /** + * @see module:packet.Compressed + */ + var Compressed: any; + + /** + * @see module:packet.SymEncryptedIntegrityProtected + */ + var SymEncryptedIntegrityProtected: any; + + /** + * @see module:packet.SymEncryptedAEADProtected + */ + var SymEncryptedAEADProtected: any; + + /** + * @see module:packet.PublicKeyEncryptedSessionKey + */ + var PublicKeyEncryptedSessionKey: any; + + /** + * @see module:packet.SymEncryptedSessionKey + */ + var SymEncryptedSessionKey: any; + + /** + * @see module:packet.Literal + */ + var Literal: any; + + /** + * @see module:packet.PublicKey + */ + var PublicKey: any; + + /** + * @see module:packet.SymmetricallyEncrypted + */ + var SymmetricallyEncrypted: any; + + /** + * @see module:packet.Marker + */ + var Marker: any; + + /** + * @see module:packet.PublicSubkey + */ + var PublicSubkey: any; + + /** + * @see module:packet.UserAttribute + */ + var UserAttribute: any; + + /** + * @see module:packet.OnePassSignature + */ + var OnePassSignature: any; + + /** + * @see module:packet.SecretKey + */ + var SecretKey: any; + + /** + * @see module:packet.Userid + */ + var Userid: any; + + /** + * @see module:packet.SecretSubkey + */ + var SecretSubkey: any; + + /** + * @see module:packet.Signature + */ + var Signature: any; + + /** + * @see module:packet.Trust + */ + var Trust: any; + } + + namespace clone { + /** + * Create a packetlist from the correspoding object types. + * @param options the object passed to and from the web worker + * @returns a mutated version of the options optject + */ + function clonePackets(options: object): object; + + /** + * Creates an object with the correct prototype from a corresponding packetlist. + * @param options the object passed to and from the web worker + * @param method the public api function name to be delegated to the worker + * @returns a mutated version of the options optject + */ + function parseClonedPackets(options: object, method: string): object; + } + namespace packet { /** - * Allocate a new packet - * @param tag property name from {@link module:enums.packet} - * @returns new packet object with type based on tag + * Encodes a given integer of length to the openpgp length specifier to a + * string + * @param length The length to encode + * @returns String with openpgp length representation */ - function newPacketFromTag(tag: string): object; + function writeSimpleLength(length: Integer): Uint8Array; /** - * Allocate a new packet from structured packet clone - * @see - * @param packetClone packet clone - * @returns new packet object with data from packet clone + * Writes a packet header version 4 with the given tag_type and length to a + * string + * @param tag_type Tag type + * @param length Length of the payload + * @returns String of the header */ - function fromStructuredClone(packetClone: object): object; - - class Compressed { - /** - * Implementation of the Compressed Data Packet (Tag 8) - * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: - * The Compressed Data packet contains compressed data. Typically, - * this packet is found as the contents of an encrypted packet, or following - * a Signature or One-Pass Signature packet, and contains a literal data packet. - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * List of packets - */ - packets: List; - - /** - * Compression algorithm - * @type {compression} - */ - algorithm: any; - - /** - * Compressed packet data - */ - compressed: Uint8Array | ReadableStream; - - /** - * Parsing function for the packet. - * @param bytes Payload of a tag 8 packet - */ - read(bytes: Uint8Array | ReadableStream): void; - - /** - * Return the compressed packet. - * @returns binary compressed packet - */ - write(): Uint8Array | ReadableStream; - - /** - * Decompression method for decompressing the compressed data - * read by read_packet - */ - decompress(): void; - - /** - * Compress the packet data (member decompressedData) - */ - compress(): void; - } - - class Literal { - /** - * Implementation of the Literal Data Packet (Tag 11) - * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: - * A Literal Data packet contains the body of a message; data that is not to be - * further interpreted. - * @param date the creation date of the literal package - */ - constructor(date: Date); - - /** - * Set the packet data to a javascript native string, end of line - * will be normalized to \r\n and by default text is converted to UTF8 - * @param text Any native javascript string - * @param {utf8 | binary | text | mime} format (optional) The format of the string of bytes - */ - setText(text: string | ReadableStream, format: any): void; - - /** - * Returns literal data packets as native JavaScript string - * with normalized end of line to \n - * @param clone (optional) Whether to return a clone so that getBytes/getText can be called again - * @returns literal data as text - */ - getText(clone: boolean): string | ReadableStream; - - /** - * Set the packet data to value represented by the provided string of bytes. - * @param bytes The string of bytes - * @param {utf8 | binary | text | mime} format The format of the string of bytes - */ - setBytes(bytes: Uint8Array | ReadableStream, format: any): void; - - /** - * Get the byte sequence representing the literal packet data - * @param clone (optional) Whether to return a clone so that getBytes/getText can be called again - * @returns A sequence of bytes - */ - getBytes(clone: boolean): Uint8Array | ReadableStream; - - /** - * Sets the filename of the literal packet data - * @param filename Any native javascript string - */ - setFilename(filename: string): void; - - /** - * Get the filename of the literal packet data - * @returns filename - */ - getFilename(): string; - - /** - * Parsing function for a literal data packet (tag 11). - * @param input Payload of a tag 11 packet - * @returns object representation - */ - read(input: Uint8Array | ReadableStream): Literal; - - /** - * Creates a string representation of the packet - * @returns Uint8Array representation of the packet - */ - write(): Uint8Array | ReadableStream; - } - - class Marker { - /** - * Implementation of the strange "Marker packet" (Tag 10) - * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: - * An experimental version of PGP used this packet as the Literal - * packet, but no released version of PGP generated Literal packets with this - * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as - * the Marker packet. - * Such a packet MUST be ignored when received. - */ - constructor(); - - /** - * Parsing function for a literal data packet (tag 10). - * @param input Payload of a tag 10 packet - * @param position Position to start reading from the input string - * @param len Length of the packet or the remaining length of - * input at position - * @returns Object representation - */ - read(input: string, position: Integer, len: Integer): Marker; - } - - class OnePassSignature { - /** - * Implementation of the One-Pass Signature Packets (Tag 4) - * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: - * The One-Pass Signature packet precedes the signed data and contains - * enough information to allow the receiver to begin calculating any - * hashes needed to verify the signature. It allows the Signature - * packet to be placed at the end of the message, so that the signer - * can compute the entire signed message in one pass. - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * A one-octet version number. The current version is 3. - */ - version: any; - - /** - * A one-octet signature type. - * Signature types are described in - * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. - */ - signatureType: any; - - /** - * A one-octet number describing the hash algorithm used. - * @see - */ - hashAlgorithm: any; - - /** - * A one-octet number describing the public-key algorithm used. - * @see - */ - publicKeyAlgorithm: any; - - /** - * An eight-octet number holding the Key ID of the signing key. - */ - issuerKeyId: any; - - /** - * A one-octet number holding a flag showing whether the signature is nested. - * A zero value indicates that the next packet is another One-Pass Signature packet - * that describes another signature to be applied to the same message data. - */ - flags: any; - - /** - * parsing function for a one-pass signature packet (tag 4). - * @param bytes payload of a tag 4 packet - * @returns object representation - */ - read(bytes: Uint8Array): OnePassSignature; - - /** - * creates a string representation of a one-pass signature packet - * @returns a Uint8Array representation of a one-pass signature packet - */ - write(): Uint8Array; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - } - - class List { - /** - * This class represents a list of openpgp packets. - * Take care when iterating over it - the packets themselves - * are stored as numerical indices. - */ - constructor(); - - /** - * The number of packets contained within the list. - */ - readonly length: Integer; - - /** - * Reads a stream of binary data and interprents it as a list of packets. - * @param A Uint8Array of bytes. - */ - read(A: Uint8Array | ReadableStream): void; - - /** - * Creates a binary representation of openpgp objects contained within the - * class instance. - * @returns A Uint8Array containing valid openpgp packets. - */ - write(): Uint8Array; - - /** - * Adds a packet to the list. This is the only supported method of doing so; - * writing to packetlist[i] directly will result in an error. - * @param packet Packet to push - */ - push(packet: object): void; - - /** - * Creates a new PacketList with all packets from the given types - */ - filterByTag(): void; - - /** - * Traverses packet tree and returns first matching packet - * @param type The packet type - * @returns - */ - findPacket(type: enums.packet): List | undefined; - - /** - * Returns array of found indices by tag - */ - indexOfTag(): void; - - /** - * Concatenates packetlist or array of packets - */ - concat(): void; - - /** - * Allocate a new packetlist from structured packetlist clone - * See {@link https://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data} - * @param packetClone packetlist clone - * @returns new packetlist object with data from packetlist clone - */ - static fromStructuredClone(packetClone: object): object; - } - - class PublicKey { - /** - * Implementation of the Key Material Packet (Tag 5,6,7,14) - * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: - * A key material packet contains all the information about a public or - * private key. There are four variants of this packet type, and two - * major versions. - * A Public-Key packet starts a series of packets that forms an OpenPGP - * key (sometimes called an OpenPGP certificate). - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * Packet version - */ - version: Integer; - - /** - * Key creation date. - */ - created: Date; - - /** - * Public key algorithm. - */ - algorithm: string; - - /** - * Algorithm specific params - */ - params: object[]; - - /** - * Time until expiration in days (V3 only) - */ - expirationTimeV3: Integer; - - /** - * Fingerprint in lowercase hex - */ - fingerprint: string; - - /** - * Keyid - */ - keyid: type.keyid.Keyid; - - /** - * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} - * called by read_tag<num> - * @param bytes Input array to read the packet from - * @returns This object with attributes set by the parser - */ - read(bytes: Uint8Array): object; - - /** - * Alias of read() - * @see module:packet.PublicKey#read - */ - readPublicKey: any; - - /** - * Same as write_private_key, but has less information because of - * public key. - * @returns OpenPGP packet body contents, - */ - write(): Uint8Array; - - /** - * Alias of write() - * @see module:packet.PublicKey#write - */ - writePublicKey: any; - - /** - * Write an old version packet - it's used by some of the internal routines. - */ - writeOld(): void; - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns - */ - isDecrypted(): boolean | null; - - /** - * Returns the creation time of the key - * @returns - */ - getCreationTime(): Date; - - /** - * Calculates the key id of the key - * @returns A 8 byte key id - */ - getKeyId(): string; - - /** - * Calculates the fingerprint of the key - * @returns A Uint8Array containing the fingerprint - */ - getFingerprintBytes(): Uint8Array; - - /** - * Calculates the fingerprint of the key - * @returns A string containing the fingerprint in lowercase hex - */ - getFingerprint(): string; - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns Whether the two keys have the same version and public key data - */ - hasSameFingerprintAs(): boolean; - - /** - * Returns algorithm information - * @returns An object of the form {algorithm: string, bits:int, curve:String} - */ - getAlgorithmInfo(): object; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - } - - class PublicKeyEncryptedSessionKey { - /** - * Public-Key Encrypted Session Key Packets (Tag 1) - * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: - * A Public-Key Encrypted Session Key packet holds the session key - * used to encrypt a message. Zero or more Public-Key Encrypted Session Key - * packets and/or Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data Packet, which holds an encrypted message. The - * message is encrypted with the session key, and the session key is itself - * encrypted and stored in the Encrypted Session Key packet(s). The - * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted - * Session Key packet for each OpenPGP key to which the message is encrypted. - * The recipient of the message finds a session key that is encrypted to their - * public key, decrypts the session key, and then uses the session key to - * decrypt the message. - */ - constructor(); - - encrypted: any[]; - - /** - * Parsing function for a publickey encrypted session key packet (tag 1). - * @param input Payload of a tag 1 packet - * @param position Position to start reading from the input string - * @param len Length of the packet or the remaining length of - * input at position - * @returns Object representation - */ - read(input: Uint8Array, position: Integer, len: Integer): PublicKeyEncryptedSessionKey - - /** - * Create a string representation of a tag 1 packet - * @returns The Uint8Array representation - */ - write(): Uint8Array; - - /** - * Encrypt session key packet - * @param key Public key - * @returns - */ - encrypt(key: PublicKey): Promise; - - /** - * Decrypts the session key (only for public key encrypted session key - * packets (tag 1) - * @param key Private key with secret params unlocked - * @returns - */ - decrypt(key: SecretKey): Promise; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - } - - class PublicSubkey { - /** - * A Public-Subkey packet (tag 14) has exactly the same format as a - * Public-Key packet, but denotes a subkey. One or more subkeys may be - * associated with a top-level key. By convention, the top-level key - * provides signature services, and the subkeys provide encryption - * services. - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * Packet version - */ - version: Integer; - - /** - * Key creation date. - */ - created: Date; - - /** - * Public key algorithm. - */ - algorithm: string; - - /** - * Algorithm specific params - */ - params: object[]; - - /** - * Time until expiration in days (V3 only) - */ - expirationTimeV3: Integer; - - /** - * Fingerprint in lowercase hex - */ - fingerprint: string; - - /** - * Keyid - */ - keyid: type.keyid.Keyid; - - /** - * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} - * called by read_tag<num> - * @param bytes Input array to read the packet from - * @returns This object with attributes set by the parser - */ - read(bytes: Uint8Array): object; - - /** - * Alias of read() - * @see module:packet.PublicKey#read - */ - readPublicKey: any; - - /** - * Same as write_private_key, but has less information because of - * public key. - * @returns OpenPGP packet body contents, - */ - write(): Uint8Array; - - /** - * Alias of write() - * @see module:packet.PublicKey#write - */ - writePublicKey: any; - - /** - * Write an old version packet - it's used by some of the internal routines. - */ - writeOld(): void; - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns - */ - isDecrypted(): boolean | null; - - /** - * Returns the creation time of the key - * @returns - */ - getCreationTime(): Date; - - /** - * Calculates the key id of the key - * @returns A 8 byte key id - */ - getKeyId(): string; - - /** - * Calculates the fingerprint of the key - * @returns A Uint8Array containing the fingerprint - */ - getFingerprintBytes(): Uint8Array; - - /** - * Calculates the fingerprint of the key - * @returns A string containing the fingerprint in lowercase hex - */ - getFingerprint(): string; - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns Whether the two keys have the same version and public key data - */ - hasSameFingerprintAs(): boolean; - - /** - * Returns algorithm information - * @returns An object of the form {algorithm: string, bits:int, curve:String} - */ - getAlgorithmInfo(): object; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - } - - class SecretKey { - /** - * A Secret-Key packet contains all the information that is found in a - * Public-Key packet, including the public-key material, but also - * includes the secret-key material after all the public-key fields. - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * Encrypted secret-key data - */ - encrypted: any; - - /** - * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. - */ - isEncrypted: any; - - /** - * Internal parser for private keys as specified in - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} - * @param bytes Input string to read the packet from - */ - read(bytes: string): void; - - /** - * Creates an OpenPGP key packet for the given key. - * @returns A string of bytes containing the secret key OpenPGP packet - */ - write(): string; - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns - */ - isDecrypted(): boolean | null; - - /** - * Encrypt the payload. By default, we use aes256 and iterated, salted string - * to key specifier. If the key is in a decrypted state (isEncrypted === false) - * and the passphrase is empty or undefined, the key will be set as not encrypted. - * This can be used to remove passphrase protection after calling decrypt(). - * @param passphrase - * @returns - */ - encrypt(passphrase: string): Promise; - - /** - * Decrypts the private key params which are needed to use the key. - * {@link module:packet.SecretKey.isDecrypted} should be false, as - * otherwise calls to this function will throw an error. - * @param passphrase The passphrase for this private key as string - * @returns - */ - decrypt(passphrase: string): Promise; - - /** - * Clear private params, return to initial state - */ - clearPrivateParams(): void; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - - /** - * Packet version - */ - version: Integer; - - /** - * Key creation date. - */ - created: Date; - - /** - * Public key algorithm. - */ - algorithm: string; - - /** - * Algorithm specific params - */ - params: object[]; - - /** - * Time until expiration in days (V3 only) - */ - expirationTimeV3: Integer; - - /** - * Fingerprint in lowercase hex - */ - fingerprint: string; - - /** - * Keyid - */ - keyid: type.keyid.Keyid; - - /** - * Alias of read() - * @see module:packet.PublicKey#read - */ - readPublicKey: any; - - /** - * Alias of write() - * @see module:packet.PublicKey#write - */ - writePublicKey: any; - - /** - * Write an old version packet - it's used by some of the internal routines. - */ - writeOld(): void; - - /** - * Returns the creation time of the key - * @returns - */ - getCreationTime(): Date; - - /** - * Calculates the key id of the key - * @returns A 8 byte key id - */ - getKeyId(): string; - - /** - * Calculates the fingerprint of the key - * @returns A Uint8Array containing the fingerprint - */ - getFingerprintBytes(): Uint8Array; - - /** - * Calculates the fingerprint of the key - * @returns A string containing the fingerprint in lowercase hex - */ - getFingerprint(): string; - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns Whether the two keys have the same version and public key data - */ - hasSameFingerprintAs(): boolean; - - /** - * Returns algorithm information - * @returns An object of the form {algorithm: string, bits:int, curve:String} - */ - getAlgorithmInfo(): object; - } - - class SecretSubkey { - /** - * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret - * Key packet and has exactly the same format. - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * Encrypted secret-key data - */ - encrypted: any; - - /** - * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. - */ - isEncrypted: any; - - /** - * Internal parser for private keys as specified in - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} - * @param bytes Input string to read the packet from - */ - read(bytes: string): void; - - /** - * Creates an OpenPGP key packet for the given key. - * @returns A string of bytes containing the secret key OpenPGP packet - */ - write(): string; - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns - */ - isDecrypted(): boolean | null; - - /** - * Encrypt the payload. By default, we use aes256 and iterated, salted string - * to key specifier. If the key is in a decrypted state (isEncrypted === false) - * and the passphrase is empty or undefined, the key will be set as not encrypted. - * This can be used to remove passphrase protection after calling decrypt(). - * @param passphrase - * @returns - */ - encrypt(passphrase: string): Promise; - - /** - * Decrypts the private key params which are needed to use the key. - * {@link module:packet.SecretKey.isDecrypted} should be false, as - * otherwise calls to this function will throw an error. - * @param passphrase The passphrase for this private key as string - * @returns - */ - decrypt(passphrase: string): Promise; - - /** - * Clear private params, return to initial state - */ - clearPrivateParams(): void; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - - /** - * Packet version - */ - version: Integer; - - /** - * Key creation date. - */ - created: Date; - - /** - * Public key algorithm. - */ - algorithm: string; - - /** - * Algorithm specific params - */ - params: object[]; - - /** - * Time until expiration in days (V3 only) - */ - expirationTimeV3: Integer; - - /** - * Fingerprint in lowercase hex - */ - fingerprint: string; - - /** - * Keyid - */ - keyid: type.keyid.Keyid; - - /** - * Alias of read() - * @see module:packet.PublicKey#read - */ - readPublicKey: any; - - /** - * Alias of write() - * @see module:packet.PublicKey#write - */ - writePublicKey: any; - - /** - * Write an old version packet - it's used by some of the internal routines. - */ - writeOld(): void; - - /** - * Returns the creation time of the key - * @returns - */ - getCreationTime(): Date; - - /** - * Calculates the key id of the key - * @returns A 8 byte key id - */ - getKeyId(): string; - - /** - * Calculates the fingerprint of the key - * @returns A Uint8Array containing the fingerprint - */ - getFingerprintBytes(): Uint8Array; - - /** - * Calculates the fingerprint of the key - * @returns A string containing the fingerprint in lowercase hex - */ - getFingerprint(): string; - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns Whether the two keys have the same version and public key data - */ - hasSameFingerprintAs(): boolean; - - /** - * Returns algorithm information - * @returns An object of the form {algorithm: string, bits:int, curve:String} - */ - getAlgorithmInfo(): object; - } - - class Signature { - /** - * Implementation of the Signature Packet (Tag 2) - * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: - * A Signature packet describes a binding between some public key and - * some data. The most common signatures are a signature of a file or a - * block of text, and a signature that is a certification of a User ID. - * @param date the creation date of the signature - */ - constructor(date: Date); - - /** - * parsing function for a signature packet (tag 2). - * @param bytes payload of a tag 2 packet - * @param position position to start reading from the bytes string - * @param len length of the packet or the remaining length of bytes at position - * @returns object representation - */ - read(bytes: string, position: Integer, len: Integer): Signature; - - /** - * Signs provided data. This needs to be done prior to serialization. - * @param key private key used to sign the message. - * @param data Contains packets to be signed. - * @returns - */ - sign(key: SecretKey, data: object): Promise; - - /** - * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets - * @returns subpacket data - */ - write_hashed_sub_packets(): Uint8Array; - - /** - * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets - * @returns subpacket data - */ - write_unhashed_sub_packets(): Uint8Array; - - /** - * verifys the signature packet. Note: not signature types are implemented - * @param key the public key to verify the signature - * @param signatureType expected signature type - * @param data data which on the signature applies - * @returns True if message is verified, else false. - */ - verify(key: PublicSubkey | PublicKey | SecretSubkey | SecretKey, signatureType: enums.signature, data: string | object): Promise; - - /** - * Verifies signature expiration date - * @param date (optional) use the given date for verification instead of the current time - * @returns true if expired - */ - isExpired(date: Date): boolean; - - /** - * Returns the expiration time of the signature or Infinity if signature does not expire - * @returns expiration time - */ - getExpirationTime(): Date; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - } - - class SymEncryptedAEADProtected { - /** - * Implementation of the Symmetrically Encrypted Authenticated Encryption with - * Additional Data (AEAD) Protected Data Packet - * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: - * AEAD Protected Data Packet - */ - constructor(); - - /** - * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @param bytes - */ - read(bytes: Uint8Array | ReadableStream): void; - - /** - * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @returns The encrypted payload - */ - write(): Uint8Array | ReadableStream; - - /** - * Decrypt the encrypted payload. - * @param sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' - * @param key The session key used to encrypt the payload - * @param streaming Whether the top-level function will return a stream - * @returns - */ - decrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): boolean; - - /** - * Encrypt the packet list payload. - * @param sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' - * @param key The session key used to encrypt the payload - * @param streaming Whether the top-level function will return a stream - */ - encrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): void; - - /** - * En/decrypt the payload. - * @param {encrypt | decrypt} fn Whether to encrypt or decrypt - * @param key The session key used to en/decrypt the payload - * @param data The data to en/decrypt - * @param streaming Whether the top-level function will return a stream - * @returns - */ - crypt(fn: any, key: Uint8Array, data: Uint8Array | ReadableStream, streaming: boolean): Uint8Array | ReadableStream; - } - - class SymEncryptedIntegrityProtected { - /** - * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) - * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: - * The Symmetrically Encrypted Integrity Protected Data packet is - * a variant of the Symmetrically Encrypted Data packet. It is a new feature - * created for OpenPGP that addresses the problem of detecting a modification to - * encrypted data. It is used in combination with a Modification Detection Code - * packet. - */ - constructor(); - - /** - * The encrypted payload. - */ - encrypted: any; - - /** - * If after decrypting the packet this is set to true, - * a modification has been detected and thus the contents - * should be discarded. - */ - modification: boolean; - - /** - * Encrypt the payload in the packet. - * @param sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' - * @param key The key of cipher blocksize length to be used - * @param streaming Whether to set this.encrypted to a stream - * @returns - */ - encrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): Promise; - - /** - * Decrypts the encrypted data contained in the packet. - * @param sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' - * @param key The key of cipher blocksize length to be used - * @param streaming Whether to read this.encrypted as a stream - * @returns - */ - decrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): Promise; - } - - class SymEncryptedSessionKey { - /** - * Public-Key Encrypted Session Key Packets (Tag 1) - * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: - * A Public-Key Encrypted Session Key packet holds the session key - * used to encrypt a message. Zero or more Public-Key Encrypted Session Key - * packets and/or Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data Packet, which holds an encrypted message. The - * message is encrypted with the session key, and the session key is itself - * encrypted and stored in the Encrypted Session Key packet(s). The - * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted - * Session Key packet for each OpenPGP key to which the message is encrypted. - * The recipient of the message finds a session key that is encrypted to their - * public key, decrypts the session key, and then uses the session key to - * decrypt the message. - */ - constructor(); - - /** - * Parsing function for a symmetric encrypted session key packet (tag 3). - * @param input Payload of a tag 1 packet - * @param position Position to start reading from the input string - * @param len Length of the packet or the remaining length of - * input at position - * @returns Object representation - */ - read(input: Uint8Array, position: Integer, len: Integer): SymEncryptedSessionKey; - - /** - * Decrypts the session key - * @param passphrase The passphrase in string form - * @returns - */ - decrypt(passphrase: string): Promise; - - /** - * Encrypts the session key - * @param passphrase The passphrase in string form - * @returns - */ - encrypt(passphrase: string): Promise; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - } - - class SymmetricallyEncrypted { - /** - * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) - * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: - * The Symmetrically Encrypted Data packet contains data encrypted with a - * symmetric-key algorithm. When it has been decrypted, it contains other - * packets (usually a literal data packet or compressed data packet, but in - * theory other Symmetrically Encrypted Data packets or sequences of packets - * that form whole OpenPGP messages). - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * Encrypted secret-key data - */ - encrypted: any; - - /** - * Decrypted packets contained within. - */ - packets: List; - - /** - * When true, decrypt fails if message is not integrity protected - * @see module:config.ignore_mdc_error - */ - ignore_mdc_error: any; - - /** - * Decrypt the symmetrically-encrypted packet data - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param sessionKeyAlgorithm Symmetric key algorithm to use - * @param key The key of cipher blocksize length to be used - * @returns - */ - decrypt(sessionKeyAlgorithm: enums.symmetric, key: Uint8Array): Promise; - - /** - * Encrypt the symmetrically-encrypted packet data - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param sessionKeyAlgorithm Symmetric key algorithm to use - * @param key The key of cipher blocksize length to be used - * @returns - */ - encrypt(sessionKeyAlgorithm: enums.symmetric, key: Uint8Array): Promise; - } - - class Trust { - /** - * Implementation of the Trust Packet (Tag 12) - * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: - * The Trust packet is used only within keyrings and is not normally - * exported. Trust packets contain data that record the user's - * specifications of which key holders are trustworthy introducers, - * along with other information that implementing software uses for - * trust information. The format of Trust packets is defined by a given - * implementation. - * Trust packets SHOULD NOT be emitted to output streams that are - * transferred to other users, and they SHOULD be ignored on any input - * other than local keyring files. - */ - constructor(); - - /** - * Parsing function for a trust packet (tag 12). - * Currently not implemented as we ignore trust packets - * @param byptes payload of a tag 12 packet - */ - read(byptes: string): void; - } - - class UserAttribute { - /** - * Implementation of the User Attribute Packet (Tag 17) - * The User Attribute packet is a variation of the User ID packet. It - * is capable of storing more types of data than the User ID packet, - * which is limited to text. Like the User ID packet, a User Attribute - * packet may be certified by the key owner ("self-signed") or any other - * key owner who cares to certify it. Except as noted, a User Attribute - * packet may be used anywhere that a User ID packet may be used. - * While User Attribute packets are not a required part of the OpenPGP - * standard, implementations SHOULD provide at least enough - * compatibility to properly handle a certification signature on the - * User Attribute packet. A simple way to do this is by treating the - * User Attribute packet as a User ID packet with opaque contents, but - * an implementation may use any method desired. - */ - constructor(); - - /** - * parsing function for a user attribute packet (tag 17). - * @param input payload of a tag 17 packet - */ - read(input: Uint8Array): void; - - /** - * Creates a binary representation of the user attribute packet - * @returns string representation - */ - write(): Uint8Array; - - /** - * Compare for equality - * @param usrAttr - * @returns true if equal - */ - equals(usrAttr: UserAttribute): boolean; - } - - class Userid { - /** - * Implementation of the User ID Packet (Tag 13) - * A User ID packet consists of UTF-8 text that is intended to represent - * the name and email address of the key holder. By convention, it - * includes an RFC 2822 [RFC2822] mail name-addr, but there are no - * restrictions on its content. The packet length in the header - * specifies the length of the User ID. - */ - constructor(); - - /** - * A string containing the user id. Usually in the form - * John Doe - */ - userid: string; - - /** - * Parsing function for a user id packet (tag 13). - * @param input payload of a tag 13 packet - */ - read(input: Uint8Array): void; - - /** - * Parse userid string, e.g. 'John Doe ' - */ - parse(): void; - - /** - * Creates a binary representation of the user id packet - * @returns binary representation - */ - write(): Uint8Array; - - /** - * Set userid string from object, e.g. { name:'Phil Zimmermann', email:'phil@openpgp.org' } - */ - format(): void; - } - - namespace all_packets { - /** - * @see module:packet.Compressed - */ - var Compressed: any; - - /** - * @see module:packet.SymEncryptedIntegrityProtected - */ - var SymEncryptedIntegrityProtected: any; - - /** - * @see module:packet.SymEncryptedAEADProtected - */ - var SymEncryptedAEADProtected: any; - - /** - * @see module:packet.PublicKeyEncryptedSessionKey - */ - var PublicKeyEncryptedSessionKey: any; - - /** - * @see module:packet.SymEncryptedSessionKey - */ - var SymEncryptedSessionKey: any; - - /** - * @see module:packet.Literal - */ - var Literal: any; - - /** - * @see module:packet.PublicKey - */ - var PublicKey: any; - - /** - * @see module:packet.SymmetricallyEncrypted - */ - var SymmetricallyEncrypted: any; - - /** - * @see module:packet.Marker - */ - var Marker: any; - - /** - * @see module:packet.PublicSubkey - */ - var PublicSubkey: any; - - /** - * @see module:packet.UserAttribute - */ - var UserAttribute: any; - - /** - * @see module:packet.OnePassSignature - */ - var OnePassSignature: any; - - /** - * @see module:packet.SecretKey - */ - var SecretKey: any; - - /** - * @see module:packet.Userid - */ - var Userid: any; - - /** - * @see module:packet.SecretSubkey - */ - var SecretSubkey: any; - - /** - * @see module:packet.Signature - */ - var Signature: any; - - /** - * @see module:packet.Trust - */ - var Trust: any; - } - - namespace clone { - /** - * Create a packetlist from the correspoding object types. - * @param options the object passed to and from the web worker - * @returns a mutated version of the options optject - */ - function clonePackets(options: object): object; - - /** - * Creates an object with the correct prototype from a corresponding packetlist. - * @param options the object passed to and from the web worker - * @param method the public api function name to be delegated to the worker - * @returns a mutated version of the options optject - */ - function parseClonedPackets(options: object, method: string): object; - } - - namespace packet { - /** - * Encodes a given integer of length to the openpgp length specifier to a - * string - * @param length The length to encode - * @returns String with openpgp length representation - */ - function writeSimpleLength(length: Integer): Uint8Array; - - /** - * Writes a packet header version 4 with the given tag_type and length to a - * string - * @param tag_type Tag type - * @param length Length of the payload - * @returns String of the header - */ - function writeHeader(tag_type: Integer, length: Integer): string; - - /** - * Writes a packet header Version 3 with the given tag_type and length to a - * string - * @param tag_type Tag type - * @param length Length of the payload - * @returns String of the header - */ - function writeOldHeader(tag_type: Integer, length: Integer): string; - - /** - * Whether the packet type supports partial lengths per RFC4880 - * @param tag_type Tag type - * @returns String of the header - */ - function supportsStreaming(tag_type: Integer): boolean; - - /** - * Generic static Packet Parser function - * @param input Input stream as string - * @param callback Function to call with the parsed packet - * @returns Returns false if the stream was empty and parsing is done, and true otherwise. - */ - function read(input: Uint8Array | ReadableStream, callback: Function): boolean; - } + function writeHeader(tag_type: Integer, length: Integer): string; + + /** + * Writes a packet header Version 3 with the given tag_type and length to a + * string + * @param tag_type Tag type + * @param length Length of the payload + * @returns String of the header + */ + function writeOldHeader(tag_type: Integer, length: Integer): string; + + /** + * Whether the packet type supports partial lengths per RFC4880 + * @param tag_type Tag type + * @returns String of the header + */ + function supportsStreaming(tag_type: Integer): boolean; + + /** + * Generic static Packet Parser function + * @param input Input stream as string + * @param callback Function to call with the parsed packet + * @returns Returns false if the stream was empty and parsing is done, and true otherwise. + */ + function read(input: Uint8Array | ReadableStream, callback: Function): boolean; } +} - namespace polyfills { - } +export namespace polyfills { +} - namespace signature { - /** - * Class that represents an OpenPGP signature. - */ - class Signature { - /** - * @param packetlist The signature packets - */ - constructor(packetlist: packet.List); - - /** - * Returns ASCII armored text of signature - * @returns ASCII armor - */ - armor(): ReadableStream; - } - - /** - * reads an OpenPGP armored signature and returns a signature object - * @param armoredText text to be parsed - * @returns new signature object - */ - function readArmored(armoredText: string | ReadableStream): Signature; - - /** - * reads an OpenPGP signature as byte array and returns a signature object - * @param input binary signature - * @returns new signature object - */ - function read(input: Uint8Array | ReadableStream): Signature; - } - - namespace type { - /** - * Encoded symmetric key for ECDH - */ - namespace ecdh_symkey { - class ECDHSymmetricKey { - constructor(); - - /** - * Read an ECDHSymmetricKey from an Uint8Array - * @param input Where to read the encoded symmetric key from - * @returns Number of read bytes - */ - read(input: Uint8Array): number; - - /** - * Write an ECDHSymmetricKey as an Uint8Array - * @returns An array containing the value - */ - write(): Uint8Array; - } - } - - /** - * Implementation of type KDF parameters - * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: - * A key derivation function (KDF) is necessary to implement the EC - * encryption. The Concatenation Key Derivation Function (Approved - * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is - * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. - */ - namespace kdf_params { - class KDFParams { - /** - * @param hash Hash algorithm - * @param cipher Symmetric algorithm - */ - constructor(hash: enums.hash, cipher: enums.symmetric); - - /** - * Read KDFParams from an Uint8Array - * @param input Where to read the KDFParams from - * @returns Number of read bytes - */ - read(input: Uint8Array): number; - - /** - * Write KDFParams to an Uint8Array - * @returns Array with the KDFParams value - */ - write(): Uint8Array; - } - } - - /** - * Implementation of type key id - * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: - * A Key ID is an eight-octet scalar that identifies a key. - * Implementations SHOULD NOT assume that Key IDs are unique. The - * section "Enhanced Key Formats" below describes how Key IDs are - * formed. - */ - namespace keyid { - class Keyid { - constructor(); - - /** - * Parsing method for a key id - * @param input Input to read the key id from - */ - read(input: Uint8Array): void; - - /** - * Checks equality of Key ID's - * @param keyid - * @param matchWildcard Indicates whether to check if either keyid is a wildcard - */ - equals(keyid: Keyid, matchWildcard: boolean): void; - } - } - - /** - * Implementation of type MPI ( {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2}) - * Multiprecision integers (also called MPIs) are unsigned integers used - * to hold large integers such as the ones used in cryptographic - * calculations. - * An MPI consists of two pieces: a two-octet scalar that is the length - * of the MPI in bits followed by a string of octets that contain the - * actual integer. - */ - namespace mpi { - class MPI { - constructor(); - - /** - * Parsing function for a MPI ( {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC 4880 3.2}). - * @param input Payload of MPI data - * @param endian Endianness of the data; 'be' for big-endian or 'le' for little-endian - * @returns Length of data read - */ - read(input: Uint8Array, endian: string): Integer; - - /** - * Converts the mpi object to a bytes as specified in - * {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2} - * @param endian Endianness of the payload; 'be' for big-endian or 'le' for little-endian - * @param length Length of the data part of the MPI - * @returns mpi Byte representation - */ - write(endian: string, length: Integer): Uint8Array; - } - } - - /** - * Wrapper to an OID value - * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}: - * The sequence of octets in the third column is the result of applying - * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier - * with subsequent truncation. The truncation removes the two fields of - * encoded Object Identifier. The first omitted field is one octet - * representing the Object Identifier tag, and the second omitted field - * is the length of the Object Identifier body. For example, the - * complete ASN.1 DER encoding for the NIST P-256 curve OID is "06 08 2A - * 86 48 CE 3D 03 01 07", from which the first entry in the table above - * is constructed by omitting the first two octets. Only the truncated - * sequence of octets is the valid representation of a curve OID. - */ - namespace oid { - class OID { - constructor(); - - /** - * Method to read an OID object - * @param input Where to read the OID from - * @returns Number of read bytes - */ - read(input: Uint8Array): number; - - /** - * Serialize an OID object - * @returns Array with the serialized value the OID - */ - write(): Uint8Array; - - /** - * Serialize an OID object as a hex string - * @returns String with the hex value of the OID - */ - toHex(): string; - - /** - * If a known curve object identifier, return the canonical name of the curve - * @returns String with the canonical name of the curve - */ - getName(): string; - } - } - - /** - * Implementation of the String-to-key specifier - * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}: - * String-to-key (S2K) specifiers are used to convert passphrase strings - * into symmetric-key encryption/decryption keys. They are used in two - * places, currently: to encrypt the secret part of private keys in the - * private keyring, and to convert passphrases to encryption keys for - * symmetrically encrypted messages. +export namespace signature { + /** + * Class that represents an OpenPGP signature. */ - namespace s2k { - class S2K { - constructor(); + class Signature { + /** + * @param packetlist The signature packets + */ + constructor(packetlist: packet.List); - algorithm: enums.hash; + /** + * Returns ASCII armored text of signature + * @returns ASCII armor + */ + armor(): ReadableStream; + } - type: enums.s2k; + /** + * reads an OpenPGP armored signature and returns a signature object + * @param armoredText text to be parsed + * @returns new signature object + */ + function readArmored(armoredText: string | ReadableStream): Signature; - c: Integer; + /** + * reads an OpenPGP signature as byte array and returns a signature object + * @param input binary signature + * @returns new signature object + */ + function read(input: Uint8Array | ReadableStream): Signature; +} - /** - * Eight bytes of salt in a binary string. - */ - salt: string; +export namespace type { + /** + * Encoded symmetric key for ECDH + */ + namespace ecdh_symkey { + class ECDHSymmetricKey { + constructor(); - /** - * Parsing function for a string-to-key specifier ( {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). - * @param input Payload of string-to-key specifier - * @returns Actual length of the object - */ - read(input: string): Integer; + /** + * Read an ECDHSymmetricKey from an Uint8Array + * @param input Where to read the encoded symmetric key from + * @returns Number of read bytes + */ + read(input: Uint8Array): number; - /** - * Serializes s2k information - * @returns binary representation of s2k - */ - write(): Uint8Array; - - /** - * Produces a key using the specified passphrase and the defined - * hashAlgorithm - * @param passphrase Passphrase containing user input - * @returns Produced key with a length corresponding to - * hashAlgorithm hash length - */ - produce_key(passphrase: string): Uint8Array; - } + /** + * Write an ECDHSymmetricKey as an Uint8Array + * @returns An array containing the value + */ + write(): Uint8Array; } } /** - * This object contains utility functions + * Implementation of type KDF parameters + * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: + * A key derivation function (KDF) is necessary to implement the EC + * encryption. The Concatenation Key Derivation Function (Approved + * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is + * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. */ - namespace util { - /** - * Get transferable objects to pass buffers with zero copy (similar to "pass by reference" in C++) - * See: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage - * Also, convert ReadableStreams to MessagePorts - * @param obj the options object to be passed to the web worker - * @returns an array of binary data to be passed - */ - function getTransferables(obj: object): any[]; + namespace kdf_params { + class KDFParams { + /** + * @param hash Hash algorithm + * @param cipher Symmetric algorithm + */ + constructor(hash: enums.hash, cipher: enums.symmetric); - /** - * Convert MessagePorts back to ReadableStreams - * @param obj - * @returns - */ - function restoreStreams(obj: object): object; + /** + * Read KDFParams from an Uint8Array + * @param input Where to read the KDFParams from + * @returns Number of read bytes + */ + read(input: Uint8Array): number; - /** - * Create hex string from a binary - * @param str String to convert - * @returns String containing the hexadecimal values - */ - function str_to_hex(str: string): string; - - /** - * Create binary string from a hex encoded string - * @param str Hex string to convert - * @returns - */ - function hex_to_str(str: string): string; - - /** - * Convert a Uint8Array to an MPI-formatted Uint8Array. - * Note: the output is **not** an MPI object. - * @see - * @see - * @param bin An array of 8-bit integers to convert - * @returns MPI-formatted Uint8Array - */ - function Uint8Array_to_MPI(bin: Uint8Array): Uint8Array; - - /** - * Convert a Base-64 encoded string an array of 8-bit integer - * Note: accepts both Radix-64 and URL-safe strings - * @param base64 Base-64 encoded string to convert - * @returns An array of 8-bit integers - */ - function b64_to_Uint8Array(base64: string): Uint8Array; - - /** - * Convert an array of 8-bit integer to a Base-64 encoded string - * @param bytes An array of 8-bit integers to convert - * @param url If true, output is URL-safe - * @returns Base-64 encoded string - */ - function Uint8Array_to_b64(bytes: Uint8Array, url: boolean): string; - - /** - * Convert a hex string to an array of 8-bit integers - * @param hex A hex string to convert - * @returns An array of 8-bit integers - */ - function hex_to_Uint8Array(hex: string): Uint8Array; - - /** - * Convert an array of 8-bit integers to a hex string - * @param bytes Array of 8-bit integers to convert - * @returns Hexadecimal representation of the array - */ - function Uint8Array_to_hex(bytes: Uint8Array): string; - - /** - * Convert a string to an array of 8-bit integers - * @param str String to convert - * @returns An array of 8-bit integers - */ - function str_to_Uint8Array(str: string): Uint8Array; - - /** - * Convert an array of 8-bit integers to a string - * @param bytes An array of 8-bit integers to convert - * @returns String representation of the array - */ - function Uint8Array_to_str(bytes: Uint8Array): string; - - /** - * Convert a native javascript string to a Uint8Array of utf8 bytes - * @param str The string to convert - * @returns A valid squence of utf8 bytes - */ - function encode_utf8(str: string | ReadableStream): Uint8Array | ReadableStream; - - /** - * Convert a Uint8Array of utf8 bytes to a native javascript string - * @param utf8 A valid squence of utf8 bytes - * @returns A native javascript string - */ - function decode_utf8(utf8: Uint8Array | ReadableStream): string | ReadableStream; - - /** - * Concat a list of Uint8Arrays, Strings or Streams - * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams. - * @param Array of Uint8Arrays/Strings/Streams to concatenate - * @returns Concatenated array - */ - var concat: any; - - /** - * Concat Uint8Arrays - * @param Array of Uint8Arrays to concatenate - * @returns Concatenated array - */ - var concatUint8Array: any; - - /** - * Check Uint8Array equality - * @param first array - * @param second array - * @returns equality - */ - function equalsUint8Array(first: Uint8Array, second: Uint8Array): boolean; - - /** - * Calculates a 16bit sum of a Uint8Array by adding each character - * codes modulus 65535 - * @param Uint8Array to create a sum of - * @returns 2 bytes containing the sum of all charcodes % 65535 - */ - function write_checksum(Uint8Array: Uint8Array): Uint8Array; - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug(str: string): void; - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug_hexarray_dump(str: string): void; - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug_hexstr_dump(str: string): void; - - /** - * Helper function to print a debug error. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug_error(str: string): void; - - /** - * Read a stream to the end and print it to the console when it's closed. - * @param str String of the debug message - * @param input Stream to print - * @param concat Function to concatenate chunks of the stream (defaults to util.concat). - */ - function print_entire_stream(str: string, input: ReadableStream | Uint8Array | string, concat: Function): void; - - /** - * If S[1] == 0, then double(S) == (S[2..128] || 0); - * otherwise, double(S) == (S[2..128] || 0) xor - * (zeros(120) || 10000111). - * Both OCB and EAX (through CMAC) require this function to be constant-time. - * @param data - */ - /* Illegal function name 'double' can't be used here - function double(data: Uint8Array): void; - */ - - /** - * Shift a Uint8Array to the right by n bits - * @param array The array to shift - * @param bits Amount of bits to shift (MUST be smaller - * than 8) - * @returns Resulting array. - */ - function shiftRight(array: Uint8Array, bits: Integer): string; - - /** - * Get native Web Cryptography api, only the current version of the spec. - * The default configuration is to use the api when available. But it can - * be deactivated with config.use_native - * @returns The SubtleCrypto api or 'undefined' - */ - function getWebCrypto(): object; - - /** - * Get native Web Cryptography api for all browsers, including legacy - * implementations of the spec e.g IE11 and Safari 8/9. The default - * configuration is to use the api when available. But it can be deactivated - * with config.use_native - * @returns The SubtleCrypto api or 'undefined' - */ - function getWebCryptoAll(): object; - - /** - * Detect Node.js runtime. - */ - function detectNode(): void; - - /** - * Get native Node.js module - * @param The module to require - * @returns The required module or 'undefined' - */ - function nodeRequire(The: string): object; - - /** - * Get native Node.js crypto api. The default configuration is to use - * the api when available. But it can also be deactivated with config.use_native - * @returns The crypto module or 'undefined' - */ - function getNodeCrypto(): object; - - /** - * Get native Node.js Buffer constructor. This should be used since - * Buffer is not available under browserify. - * @returns The Buffer constructor or 'undefined' - */ - function getNodeBuffer(): Function; - - /** - * Format user id for internal use. - */ - function formatUserId(): void; - - /** - * Parse user id. - */ - function parseUserId(): void; - - /** - * Normalize line endings to \r\n - */ - function canonicalizeEOL(): void; - - /** - * Convert line endings from canonicalized \r\n to native \n - */ - function nativeEOL(): void; - - /** - * Remove trailing spaces and tabs from each line - */ - function removeTrailingSpaces(): void; - - /** - * Encode input buffer using Z-Base32 encoding. - * See: https://tools.ietf.org/html/rfc6189#section-5.1.6 - * @param data The binary data to encode - * @returns Binary data encoded using Z-Base32 - */ - function encodeZBase32(data: Uint8Array): string; + /** + * Write KDFParams to an Uint8Array + * @returns Array with the KDFParams value + */ + write(): Uint8Array; + } } - namespace wkd { - class WKD { - /** - * Initialize the WKD client - */ + /** + * Implementation of type key id + * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: + * A Key ID is an eight-octet scalar that identifies a key. + * Implementations SHOULD NOT assume that Key IDs are unique. The + * section "Enhanced Key Formats" below describes how Key IDs are + * formed. + */ + namespace keyid { + class Keyid { constructor(); /** - * Search for a public key using Web Key Directory protocol. - * @param options.email User's email. - * @param options.rawBytes Returns Uint8Array instead of parsed key. - * @returns The public key. + * Parsing method for a key id + * @param input Input to read the key id from */ - lookup(): Promise, err: Array | null }>; + read(input: Uint8Array): void; + + /** + * Checks equality of Key ID's + * @param keyid + * @param matchWildcard Indicates whether to check if either keyid is a wildcard + */ + equals(keyid: Keyid, matchWildcard: boolean): void; } } - namespace worker { - /** - * @see module:openpgp.initWorker - * @see module:openpgp.getWorker - * @see module:openpgp.destroyWorker - * @see module:worker/worker + /** + * Implementation of type MPI ( {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2}) + * Multiprecision integers (also called MPIs) are unsigned integers used + * to hold large integers such as the ones used in cryptographic + * calculations. + * An MPI consists of two pieces: a two-octet scalar that is the length + * of the MPI in bits followed by a string of octets that contain the + * actual integer. */ - namespace async_proxy { - class AsyncProxy { - /** - * Initializes a new proxy and loads the web worker - * @param path The path to the worker or 'openpgp.worker.js' by default - * @param n number of workers to initialize if path given - * @param config config The worker configuration - * @param worker alternative to path parameter: web worker initialized with 'openpgp.worker.js' - */ - constructor(path: string, n: number, config: object, worker: any[]); + namespace mpi { + class MPI { + constructor(); - /** - * Message handling - */ - handleMessage(): void; + /** + * Parsing function for a MPI ( {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC 4880 3.2}). + * @param input Payload of MPI data + * @param endian Endianness of the data; 'be' for big-endian or 'le' for little-endian + * @returns Length of data read + */ + read(input: Uint8Array, endian: string): Integer; - /** - * Get new request ID - * @returns New unique request ID - */ - getID(): Integer; - - /** - * Send message to worker with random data - * @param size Number of bytes to send - */ - seedRandom(size: Integer): void; - - /** - * Terminates the workers - */ - terminate(): void; - - /** - * Generic proxy function that handles all commands from the public api. - * @param method the public api function to be delegated to the worker thread - * @param options the api function's options - * @returns see the corresponding public api functions for their return types - */ - delegate(method: string, options: object): Promise; - } + /** + * Converts the mpi object to a bytes as specified in + * {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2} + * @param endian Endianness of the payload; 'be' for big-endian or 'le' for little-endian + * @param length Length of the data part of the MPI + * @returns mpi Byte representation + */ + write(endian: string, length: Integer): Uint8Array; } + } + + /** + * Wrapper to an OID value + * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}: + * The sequence of octets in the third column is the result of applying + * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier + * with subsequent truncation. The truncation removes the two fields of + * encoded Object Identifier. The first omitted field is one octet + * representing the Object Identifier tag, and the second omitted field + * is the length of the Object Identifier body. For example, the + * complete ASN.1 DER encoding for the NIST P-256 curve OID is "06 08 2A + * 86 48 CE 3D 03 01 07", from which the first entry in the table above + * is constructed by omitting the first two octets. Only the truncated + * sequence of octets is the valid representation of a curve OID. + */ + namespace oid { + class OID { + constructor(); + + /** + * Method to read an OID object + * @param input Where to read the OID from + * @returns Number of read bytes + */ + read(input: Uint8Array): number; + + /** + * Serialize an OID object + * @returns Array with the serialized value the OID + */ + write(): Uint8Array; + + /** + * Serialize an OID object as a hex string + * @returns String with the hex value of the OID + */ + toHex(): string; + + /** + * If a known curve object identifier, return the canonical name of the curve + * @returns String with the canonical name of the curve + */ + getName(): string; + } + } + + /** + * Implementation of the String-to-key specifier + * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}: + * String-to-key (S2K) specifiers are used to convert passphrase strings + * into symmetric-key encryption/decryption keys. They are used in two + * places, currently: to encrypt the secret part of private keys in the + * private keyring, and to convert passphrases to encryption keys for + * symmetrically encrypted messages. + */ + namespace s2k { + class S2K { + constructor(); + + algorithm: enums.hash; + + type: enums.s2k; + + c: Integer; + + /** + * Eight bytes of salt in a binary string. + */ + salt: string; + + /** + * Parsing function for a string-to-key specifier ( {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). + * @param input Payload of string-to-key specifier + * @returns Actual length of the object + */ + read(input: string): Integer; + + /** + * Serializes s2k information + * @returns binary representation of s2k + */ + write(): Uint8Array; + + /** + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param passphrase Passphrase containing user input + * @returns Produced key with a length corresponding to + * hashAlgorithm hash length + */ + produce_key(passphrase: string): Uint8Array; + } + } +} + +/** + * This object contains utility functions + */ +export namespace util { + /** + * Get transferable objects to pass buffers with zero copy (similar to "pass by reference" in C++) + * See: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage + * Also, convert ReadableStreams to MessagePorts + * @param obj the options object to be passed to the web worker + * @returns an array of binary data to be passed + */ + function getTransferables(obj: object): any[]; + + /** + * Convert MessagePorts back to ReadableStreams + * @param obj + * @returns + */ + function restoreStreams(obj: object): object; + + /** + * Create hex string from a binary + * @param str String to convert + * @returns String containing the hexadecimal values + */ + function str_to_hex(str: string): string; + + /** + * Create binary string from a hex encoded string + * @param str Hex string to convert + * @returns + */ + function hex_to_str(str: string): string; + + /** + * Convert a Uint8Array to an MPI-formatted Uint8Array. + * Note: the output is **not** an MPI object. + * @see + * @see + * @param bin An array of 8-bit integers to convert + * @returns MPI-formatted Uint8Array + */ + function Uint8Array_to_MPI(bin: Uint8Array): Uint8Array; + + /** + * Convert a Base-64 encoded string an array of 8-bit integer + * Note: accepts both Radix-64 and URL-safe strings + * @param base64 Base-64 encoded string to convert + * @returns An array of 8-bit integers + */ + function b64_to_Uint8Array(base64: string): Uint8Array; + + /** + * Convert an array of 8-bit integer to a Base-64 encoded string + * @param bytes An array of 8-bit integers to convert + * @param url If true, output is URL-safe + * @returns Base-64 encoded string + */ + function Uint8Array_to_b64(bytes: Uint8Array, url: boolean): string; + + /** + * Convert a hex string to an array of 8-bit integers + * @param hex A hex string to convert + * @returns An array of 8-bit integers + */ + function hex_to_Uint8Array(hex: string): Uint8Array; + + /** + * Convert an array of 8-bit integers to a hex string + * @param bytes Array of 8-bit integers to convert + * @returns Hexadecimal representation of the array + */ + function Uint8Array_to_hex(bytes: Uint8Array): string; + + /** + * Convert a string to an array of 8-bit integers + * @param str String to convert + * @returns An array of 8-bit integers + */ + function str_to_Uint8Array(str: string): Uint8Array; + + /** + * Convert an array of 8-bit integers to a string + * @param bytes An array of 8-bit integers to convert + * @returns String representation of the array + */ + function Uint8Array_to_str(bytes: Uint8Array): string; + + /** + * Convert a native javascript string to a Uint8Array of utf8 bytes + * @param str The string to convert + * @returns A valid squence of utf8 bytes + */ + function encode_utf8(str: string | ReadableStream): Uint8Array | ReadableStream; + + /** + * Convert a Uint8Array of utf8 bytes to a native javascript string + * @param utf8 A valid squence of utf8 bytes + * @returns A native javascript string + */ + function decode_utf8(utf8: Uint8Array | ReadableStream): string | ReadableStream; + + /** + * Concat a list of Uint8Arrays, Strings or Streams + * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams. + * @param Array of Uint8Arrays/Strings/Streams to concatenate + * @returns Concatenated array + */ + var concat: any; + + /** + * Concat Uint8Arrays + * @param Array of Uint8Arrays to concatenate + * @returns Concatenated array + */ + var concatUint8Array: any; + + /** + * Check Uint8Array equality + * @param first array + * @param second array + * @returns equality + */ + function equalsUint8Array(first: Uint8Array, second: Uint8Array): boolean; + + /** + * Calculates a 16bit sum of a Uint8Array by adding each character + * codes modulus 65535 + * @param Uint8Array to create a sum of + * @returns 2 bytes containing the sum of all charcodes % 65535 + */ + function write_checksum(Uint8Array: Uint8Array): Uint8Array; + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug(str: string): void; + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug_hexarray_dump(str: string): void; + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug_hexstr_dump(str: string): void; + + /** + * Helper function to print a debug error. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug_error(str: string): void; + + /** + * Read a stream to the end and print it to the console when it's closed. + * @param str String of the debug message + * @param input Stream to print + * @param concat Function to concatenate chunks of the stream (defaults to util.concat). + */ + function print_entire_stream(str: string, input: ReadableStream | Uint8Array | string, concat: Function): void; + + /** + * If S[1] == 0, then double(S) == (S[2..128] || 0); + * otherwise, double(S) == (S[2..128] || 0) xor + * (zeros(120) || 10000111). + * Both OCB and EAX (through CMAC) require this function to be constant-time. + * @param data + */ + /* Illegal function name 'double' can't be used here + function double(data: Uint8Array): void; + */ + + /** + * Shift a Uint8Array to the right by n bits + * @param array The array to shift + * @param bits Amount of bits to shift (MUST be smaller + * than 8) + * @returns Resulting array. + */ + function shiftRight(array: Uint8Array, bits: Integer): string; + + /** + * Get native Web Cryptography api, only the current version of the spec. + * The default configuration is to use the api when available. But it can + * be deactivated with config.use_native + * @returns The SubtleCrypto api or 'undefined' + */ + function getWebCrypto(): object; + + /** + * Get native Web Cryptography api for all browsers, including legacy + * implementations of the spec e.g IE11 and Safari 8/9. The default + * configuration is to use the api when available. But it can be deactivated + * with config.use_native + * @returns The SubtleCrypto api or 'undefined' + */ + function getWebCryptoAll(): object; + + /** + * Detect Node.js runtime. + */ + function detectNode(): void; + + /** + * Get native Node.js module + * @param The module to require + * @returns The required module or 'undefined' + */ + function nodeRequire(The: string): object; + + /** + * Get native Node.js crypto api. The default configuration is to use + * the api when available. But it can also be deactivated with config.use_native + * @returns The crypto module or 'undefined' + */ + function getNodeCrypto(): object; + + /** + * Get native Node.js Buffer constructor. This should be used since + * Buffer is not available under browserify. + * @returns The Buffer constructor or 'undefined' + */ + function getNodeBuffer(): Function; + + /** + * Format user id for internal use. + */ + function formatUserId(): void; + + /** + * Parse user id. + */ + function parseUserId(): void; + + /** + * Normalize line endings to \r\n + */ + function canonicalizeEOL(): void; + + /** + * Convert line endings from canonicalized \r\n to native \n + */ + function nativeEOL(): void; + + /** + * Remove trailing spaces and tabs from each line + */ + function removeTrailingSpaces(): void; + + /** + * Encode input buffer using Z-Base32 encoding. + * See: https://tools.ietf.org/html/rfc6189#section-5.1.6 + * @param data The binary data to encode + * @returns Binary data encoded using Z-Base32 + */ + function encodeZBase32(data: Uint8Array): string; +} + +export namespace wkd { + class WKD { + /** + * Initialize the WKD client + */ + constructor(); /** - * @see module:openpgp.initWorker - * @see module:openpgp.getWorker - * @see module:openpgp.destroyWorker - * @see module:worker/async_proxy - */ - namespace worker { + * Search for a public key using Web Key Directory protocol. + * @param options.email User's email. + * @param options.rawBytes Returns Uint8Array instead of parsed key. + * @returns The public key. + */ + lookup(): Promise, err: Array | null }>; + } +} + +export namespace worker { + /** + * @see module:openpgp.initWorker + * @see module:openpgp.getWorker + * @see module:openpgp.destroyWorker + * @see module:worker/worker + */ + namespace async_proxy { + class AsyncProxy { /** - * Handle random buffer exhaustion by requesting more random bytes from the main window - * @returns Empty Promise whose resolution indicates that the buffer has been refilled + * Initializes a new proxy and loads the web worker + * @param path The path to the worker or 'openpgp.worker.js' by default + * @param n number of workers to initialize if path given + * @param config config The worker configuration + * @param worker alternative to path parameter: web worker initialized with 'openpgp.worker.js' */ - function randomCallback(): Promise; + constructor(path: string, n: number, config: object, worker: any[]); /** - * Set config from main context to worker context. - * @param config The openpgp configuration + * Message handling */ - function configure(config: object): void; + handleMessage(): void; /** - * Seed the library with entropy gathered window.crypto.getRandomValues - * as this api is only avalible in the main window. - * @param buffer Some random bytes + * Get new request ID + * @returns New unique request ID */ - function seedRandom(buffer: any[]): void; + getID(): Integer; + + /** + * Send message to worker with random data + * @param size Number of bytes to send + */ + seedRandom(size: Integer): void; + + /** + * Terminates the workers + */ + terminate(): void; /** * Generic proxy function that handles all commands from the public api. - * @param method The public api function to be delegated to the worker thread - * @param options The api function's options + * @param method the public api function to be delegated to the worker thread + * @param options the api function's options + * @returns see the corresponding public api functions for their return types */ - function delegate(method: string, options: object): void; - - /** - * Respond to the main window. - * @param event Contains event type and data - */ - function response(event: object): void; + delegate(method: string, options: object): Promise; } } - /** - * Set the path for the web worker script and create an instance of the async proxy - * @param path relative path to the worker scripts, default: 'openpgp.worker.js' - * @param n number of workers to initialize - * @param workers alternative to path parameter: web workers initialized with 'openpgp.worker.js' - */ - function initWorker(path: string, n?: number, workers?: any[]): void; + * @see module:openpgp.initWorker + * @see module:openpgp.getWorker + * @see module:openpgp.destroyWorker + * @see module:worker/async_proxy + */ + namespace worker { + /** + * Handle random buffer exhaustion by requesting more random bytes from the main window + * @returns Empty Promise whose resolution indicates that the buffer has been refilled + */ + function randomCallback(): Promise; - /** - * Returns a reference to the async proxy if the worker was initialized with openpgp.initWorker() - * @returns the async proxy or null if not initialized - */ - function getWorker(): worker.async_proxy.AsyncProxy | null; + /** + * Set config from main context to worker context. + * @param config The openpgp configuration + */ + function configure(config: object): void; - /** - * Cleanup the current instance of the web worker. - */ - function destroyWorker(): void; + /** + * Seed the library with entropy gathered window.crypto.getRandomValues + * as this api is only avalible in the main window. + * @param buffer Some random bytes + */ + function seedRandom(buffer: any[]): void; - interface UserID { - name: string; - email: string; + /** + * Generic proxy function that handles all commands from the public api. + * @param method The public api function to be delegated to the worker thread + * @param options The api function's options + */ + function delegate(method: string, options: object): void; + + /** + * Respond to the main window. + * @param event Contains event type and data + */ + function response(event: object): void; } - - interface KeyOptions { - /** - * array of user IDs e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] - */ - userIds: UserID[]; - /** - * (optional) The passphrase used to encrypt the resulting private key - */ - passphrase?: string; - /** - * (optional) number of bits for RSA keys: 2048 or 4096. - */ - numBits?: number; - /** - * (optional) The number of seconds after the key creation time that the key expires - */ - keyExpirationTime?: number; - /** - * (optional) elliptic curve for ECC keys: elliptic curve for ECC keys: - * curve25519, p256, p384, p521, secp256k1, - * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1. - */ - curve?: string; - /** - * (optional) override the creation date of the key and the key signatures - */ - date?: Date; - /** - * (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] - * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt - */ - subkeys?: { sign: true, passphrase: "string" }[]; - } - - /** - * Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type. - * @param options - * @returns The generated key object in the form: - * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } - */ - function generateKey(option: KeyOptions): Promise<{ key: key.Key, privateKeyArmored: string, publicKeyArmored: string, revocationCertificate: string }>; - - /** - * Reformats signature packets for a key and rewraps key object. - * @param privateKey private key to reformat - * @param userIds array of user IDs e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] - * @param passphrase (optional) The passphrase used to encrypt the resulting private key - * @param keyExpirationTime (optional) The number of seconds after the key creation time that the key expires - * @param revocationCertificate (optional) Whether the returned object should include a revocation certificate to revoke the public key - * @returns The generated key object in the form: - * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } - */ - function reformatKey(privateKey: key.Key, userIds: any[], passphrase?: string, keyExpirationTime?: number, revocationCertificate?: boolean): Promise; - - /** - * Revokes a key. Requires either a private key or a revocation certificate. - * If a revocation certificate is passed, the reasonForRevocation parameters will be ignored. - * @param key (optional) public or private key to revoke - * @param revocationCertificate (optional) revocation certificate to revoke the key with - * @param reasonForRevocation (optional) object indicating the reason for revocation - * @param reasonForRevocation.flag (optional) flag indicating the reason for revocation - * @param reasonForRevocation.string (optional) string explaining the reason for revocation - * @returns The revoked key object in the form: - * { privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String } - * (if private key is passed) or { publicKey:Key, publicKeyArmored:String } (otherwise) - */ - function revokeKey(key?: key.Key, revocationCertificate?: string, reasonForRevocation?: revokeKey_reasonForRevocation): Promise<{ - privateKey: key.Key, - privateKeyArmored: string, - publicKey: key.Key, - publicKeyArmored: string - } | { - publicKey: key.Key, - publicKeyArmored: string - }>; - - /** - * Unlock a private key with your passphrase. - * @param privateKey the private key that is to be decrypted - * @param passphrase the user's passphrase(s) chosen during key generation - * @returns the unlocked key object in the form: { key:Key } - */ - function decryptKey(privateKey: key.Key, passphrase: string | any[]): Promise<{ key: key.Key }>; - - /** - * Lock a private key with your passphrase. - * @param privateKey the private key that is to be decrypted - * @param passphrase the user's passphrase(s) chosen during key generation - * @returns the locked key object in the form: { key:Key } - */ - function encryptKey(privateKey: key.Key, passphrase: string | any[]): Promise<{ key: key.Key }>; - - interface EncryptOptions { - /** - * message to be encrypted as created by openpgp.message.fromText or openpgp.message.fromBinary - */ - message: message.Message; - /** - * (optional) array of keys or single key, used to encrypt the message - */ - publicKeys?: key.Key | any[]; - /** - * (optional) private keys for signing. If omitted message will not be signed - */ - privateKeys?: key.Key | any[]; - /** - * (optional) array of passwords or a single password to encrypt the message - */ - passwords?: string | any[]; - /** - * (optional) session key in the form: { data:Uint8Array, algorithm:String } - */ - sessionKey?: { data: Uint8Array, algorithm: string }; - /** - * (optional) which compression algorithm to compress the message with, defaults to what is specified in config - */ - compression?: enums.compression; - /** - * (optional) if the return values should be ascii armored or the message/signature objects - */ - armor?: boolean; - /** - * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - */ - streaming?: 'web' | 'node' | false; - /** - * (optional) if the signature should be detached (if true, signature will be added to returned object) - */ - detached?: boolean; - /** - * (optional) a detached signature to add to the encrypted message - */ - signature?: signature.Signature; - /** - * (optional) if the unencrypted session key should be added to returned object - */ - returnSessionKey?: boolean; - /** - * (optional) use a key ID of 0 instead of the public key IDs - */ - wildcard?: boolean; - /** - * (optional) override the creation date of the message signature - */ - date?: Date; - /** - * (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - */ - fromUserIds?: UserID[]; - /** - * (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] - */ - toUserIds?: UserID[] - } - - interface EncryptResult { - data: string | ReadableStream; - message: message.Message; - signature: string | ReadableStream | signature.Signature; - sessionKey: { data: Uint8Array, algorithm: string, aeadAlgorithm: string }; - } - - /** - * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords - * must be specified. If private keys are specified, those will be used to sign the message. - * @param options - * @returns Object containing encrypted (and optionally signed) message in the form: - * { - * data: string|ReadableStream|NodeStream, (if `armor` was true, the default) - * message: Message, (if `armor` was false) - * signature: string|ReadableStream|NodeStream, (if `detached` was true and `armor` was true) - * signature: Signature (if `detached` was true and `armor` was false) - * sessionKey: { data, algorithm, aeadAlgorithm } (if `returnSessionKey` was true) - * } - */ - function encrypt(options: EncryptOptions): Promise; - - interface DecryptOptions { - /** - * the message object with the encrypted data - */ - message: message.Message; - /** - * (optional) private keys with decrypted secret key data or session key - */ - privateKeys?: key.Key | key.Key[]; - /** - * (optional) passwords to decrypt the message - */ - passwords?: string | string[]; - /** - * (optional) session keys in the form: { data:Uint8Array, algorithm:String } - */ - sessionKeys?: { data: Uint8Array, algorithm: string } | { data: Uint8Array, algorithm: string }[]; - /** - * (optional) array of public keys or single key, to verify signatures - */ - publicKeys?: key.Key | key.Key[]; - /** - * (optional) whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. - */ - format?: 'utf8' | 'binary'; - /** - * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - */ - streaming?: 'web' | 'node' | false; - /** - * (optional) detached signature for verification - */ - signature?: signature.Signature; - /** - * (optional) use the given date for verification instead of the current time - */ - date?: Date - } - - interface DecryptResult { - data: string | ReadableStream | NodeStream | Uint8Array | ReadableStream, - filename: string, - signatures: { - keyid: type.keyid.Keyid, - verified: Promise, - valid: boolean - }[] - } - - /** - * Decrypts a message with the user's private key, a session key or a password. Either a private key, - * a session key or a password must be specified. - * @param options - * @returns Object containing decrypted and verified message in the form: - * { - * data: string|ReadableStream|NodeStream, (if format was 'utf8', the default) - * data: Uint8Array|ReadableStream|NodeStream, (if format was 'binary') - * filename: string, - * signatures: [ - * { - * keyid: module:type/keyid, - * verified: Promise, - * valid: boolean (if streaming was false) - * }, ... - * ] - * } - */ - function decrypt(options: DecryptOptions): Promise; - - interface SignOptions { - /** - * (cleartext) message to be signed - */ - message: cleartext.CleartextMessage | message.Message; - /** - * array of keys or single key with decrypted secret key data to sign cleartext - */ - privateKeys: key.Key | any[]; - /** - * (optional) if the return value should be ascii armored or the message object - */ - armor?: boolean; - /** - * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - */ - streaming?: 'web' | 'node' | false; - /** - * (optional) if the return value should contain a detached signature - */ - detached?: boolean; - /** - * (optional) override the creation date of the signature - */ - date?: Date; - /** - * (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - */ - fromUserIds?: UserID[] - } - - interface SignResult { - data: string | ReadableStream | NodeStream, - message: message.Message, - signature: string | ReadableStream | NodeStream | signature.Signature - } - - /** - * Signs a cleartext message. - * @param options - * @returns Object containing signed message in the form: - * { - * data: string|ReadableStream|NodeStream, (if `armor` was true, the default) - * message: Message (if `armor` was false) - * } - * Or, if `detached` was true: - * { - * signature: string|ReadableStream|NodeStream, (if `armor` was true, the default) - * signature: Signature (if `armor` was false) - * } - */ - function sign(options: SignOptions): Promise; - - interface VerifyOptions { - /** - * array of publicKeys or single key, to verify signatures - */ - publicKeys: key.Key | any[]; - /** - * (cleartext) message object with signatures - */ - message: cleartext.CleartextMessage | message.Message; - /** - * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - */ - streaming?: 'web' | 'node' | false; - /** - * (optional) detached signature for verification - */ - signature?: signature.Signature; - /** - * (optional) use the given date for verification instead of the current time - */ - date?: Date - } - - interface VerifyResult { - data: string | ReadableStream | NodeStream | Uint8Array | ReadableStream | NodeStream, - signatures: { - keyid: type.keyid.Keyid, - verified: Promise, - valid: boolean - }[] - } - - /** - * Verifies signatures of cleartext signed message - * @param options - * @returns Object containing verified message in the form: - * { - * data: string|ReadableStream|NodeStream, (if `message` was a CleartextMessage) - * data: Uint8Array|ReadableStream|NodeStream, (if `message` was a Message) - * signatures: [ - * { - * keyid: module:type/keyid, - * verified: Promise, - * valid: boolean (if `streaming` was false) - * }, ... - * ] - * } - */ - function verify(options: VerifyOptions): Promise; - - /** - * Encrypt a symmetric session key with public keys, passwords, or both at once. At least either public keys - * or passwords must be specified. - * @param data the session key to be encrypted e.g. 16 random bytes (for aes128) - * @param algorithm algorithm of the symmetric session key e.g. 'aes128' or 'aes256' - * @param aeadAlgorithm (optional) aead algorithm, e.g. 'eax' or 'ocb' - * @param publicKeys (optional) array of public keys or single key, used to encrypt the key - * @param passwords (optional) passwords for the message - * @param wildcard (optional) use a key ID of 0 instead of the public key IDs - * @param date (optional) override the date - * @param toUserIds (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] - * @returns the encrypted session key packets contained in a message object - */ - function encryptSessionKey(data: Uint8Array, algorithm: string, aeadAlgorithm?: string, publicKeys?: key.Key | key.Key[], passwords?: string | string[], wildcard?: boolean, date?: Date, toUserIds?: any[]): Promise; - - /** - * Decrypt symmetric session keys with a private key or password. Either a private key or - * a password must be specified. - * @param message a message object containing the encrypted session key packets - * @param privateKeys (optional) private keys with decrypted secret key data - * @param passwords (optional) passwords to decrypt the session key - * @returns Array of decrypted session key, algorithm pairs in form: - * { data:Uint8Array, algorithm:String } - * or 'undefined' if no key packets found - */ - function decryptSessionKeys(message: message.Message, privateKeys?: key.Key | key.Key[], passwords?: string | string[]): Promise<{ data: Uint8Array, algorithm: string }[] | undefined>; - - /** - * Input validation - */ - function checkString(): void; - - /** - * Normalize parameter to an array if it is not undefined. - * @param param the parameter to be normalized - * @returns the resulting array or undefined - */ - function toArray(param: object): any[] | undefined; - - /** - * Convert data to or from Stream - * @param data the data to convert - * @param streaming (optional) whether to return a ReadableStream - * @returns the data in the respective format - */ - function convertStream(data: object, streaming?: 'web' | 'node' | false): object; - - /** - * Convert object properties from Stream - * @param obj the data to convert - * @param streaming (optional) whether to return ReadableStreams - * @param keys (optional) which keys to return as streams, if possible - * @returns the data in the respective format - */ - function convertStreams(obj: object, streaming: 'web' | 'node' | false, keys: any[]): object; - - /** - * Link result.data to the message stream for cancellation. - * Also, forward errors in the message to result.data. - * @param result the data to convert - * @param message message object - * @param erroringStream (optional) stream which either errors or gets closed without data - * @returns - */ - function linkStreams(result: object, message: message.Message, erroringStream: ReadableStream): object; - - /** - * Wait until signature objects have been verified - * @param signatures list of signatures - */ - function prepareSignatures(signatures: object): void; - - /** - * Global error handler that logs the stack trace and rethrows a high lvl error message. - * @param message A human readable high level error Message - * @param error The internal error that caused the failure - */ - function onError(message: string, error: Error): void; - - /** - * Check for native AEAD support and configuration by the user. Only - * browsers that implement the current WebCrypto specification support - * native GCM. Native EAX is built on CTR and CBC, which current - * browsers support. OCB and CFB are not natively supported. - * @returns If authenticated encryption should be used - */ - function nativeAEAD(): boolean; } + + +/** + * Set the path for the web worker script and create an instance of the async proxy + * @param path relative path to the worker scripts, default: 'openpgp.worker.js' + * @param n number of workers to initialize + * @param workers alternative to path parameter: web workers initialized with 'openpgp.worker.js' + */ +export function initWorker(path: string, n?: number, workers?: any[]): void; + +/** + * Returns a reference to the async proxy if the worker was initialized with openpgp.initWorker() + * @returns the async proxy or null if not initialized + */ +export function getWorker(): worker.async_proxy.AsyncProxy | null; + +/** + * Cleanup the current instance of the web worker. + */ +export function destroyWorker(): void; + +export interface UserID { + name: string; + email: string; +} + +export interface KeyOptions { + /** + * array of user IDs e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] + */ + userIds: UserID[]; + /** + * (optional) The passphrase used to encrypt the resulting private key + */ + passphrase?: string; + /** + * (optional) number of bits for RSA keys: 2048 or 4096. + */ + numBits?: number; + /** + * (optional) The number of seconds after the key creation time that the key expires + */ + keyExpirationTime?: number; + /** + * (optional) elliptic curve for ECC keys: elliptic curve for ECC keys: + * curve25519, p256, p384, p521, secp256k1, + * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1. + */ + curve?: string; + /** + * (optional) override the creation date of the key and the key signatures + */ + date?: Date; + /** + * (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + */ + subkeys?: { sign: true, passphrase: "string" }[]; +} + +/** + * Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type. + * @param options + * @returns The generated key object in the form: + * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } + */ +export function generateKey(option: KeyOptions): Promise<{ key: key.Key, privateKeyArmored: string, publicKeyArmored: string, revocationCertificate: string }>; + +/** + * Reformats signature packets for a key and rewraps key object. + * @param privateKey private key to reformat + * @param userIds array of user IDs e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] + * @param passphrase (optional) The passphrase used to encrypt the resulting private key + * @param keyExpirationTime (optional) The number of seconds after the key creation time that the key expires + * @param revocationCertificate (optional) Whether the returned object should include a revocation certificate to revoke the public key + * @returns The generated key object in the form: + * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } + */ +export function reformatKey(privateKey: key.Key, userIds: any[], passphrase?: string, keyExpirationTime?: number, revocationCertificate?: boolean): Promise; + +/** + * Revokes a key. Requires either a private key or a revocation certificate. + * If a revocation certificate is passed, the reasonForRevocation parameters will be ignored. + * @param key (optional) public or private key to revoke + * @param revocationCertificate (optional) revocation certificate to revoke the key with + * @param reasonForRevocation (optional) object indicating the reason for revocation + * @param reasonForRevocation.flag (optional) flag indicating the reason for revocation + * @param reasonForRevocation.string (optional) string explaining the reason for revocation + * @returns The revoked key object in the form: + * { privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String } + * (if private key is passed) or { publicKey:Key, publicKeyArmored:String } (otherwise) + */ +export function revokeKey(key?: key.Key, revocationCertificate?: string, reasonForRevocation?: revokeKey_reasonForRevocation): Promise<{ + privateKey: key.Key, + privateKeyArmored: string, + publicKey: key.Key, + publicKeyArmored: string +} | { + publicKey: key.Key, + publicKeyArmored: string +}>; + +/** + * Unlock a private key with your passphrase. + * @param privateKey the private key that is to be decrypted + * @param passphrase the user's passphrase(s) chosen during key generation + * @returns the unlocked key object in the form: { key:Key } + */ +export function decryptKey(privateKey: key.Key, passphrase: string | any[]): Promise<{ key: key.Key }>; + +/** + * Lock a private key with your passphrase. + * @param privateKey the private key that is to be decrypted + * @param passphrase the user's passphrase(s) chosen during key generation + * @returns the locked key object in the form: { key:Key } + */ +export function encryptKey(privateKey: key.Key, passphrase: string | any[]): Promise<{ key: key.Key }>; + +export interface EncryptOptions { + /** + * message to be encrypted as created by openpgp.message.fromText or openpgp.message.fromBinary + */ + message: message.Message; + /** + * (optional) array of keys or single key, used to encrypt the message + */ + publicKeys?: key.Key | any[]; + /** + * (optional) private keys for signing. If omitted message will not be signed + */ + privateKeys?: key.Key | any[]; + /** + * (optional) array of passwords or a single password to encrypt the message + */ + passwords?: string | any[]; + /** + * (optional) session key in the form: { data:Uint8Array, algorithm:String } + */ + sessionKey?: { data: Uint8Array, algorithm: string }; + /** + * (optional) which compression algorithm to compress the message with, defaults to what is specified in config + */ + compression?: enums.compression; + /** + * (optional) if the return values should be ascii armored or the message/signature objects + */ + armor?: boolean; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) if the signature should be detached (if true, signature will be added to returned object) + */ + detached?: boolean; + /** + * (optional) a detached signature to add to the encrypted message + */ + signature?: signature.Signature; + /** + * (optional) if the unencrypted session key should be added to returned object + */ + returnSessionKey?: boolean; + /** + * (optional) use a key ID of 0 instead of the public key IDs + */ + wildcard?: boolean; + /** + * (optional) override the creation date of the message signature + */ + date?: Date; + /** + * (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + */ + fromUserIds?: UserID[]; + /** + * (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] + */ + toUserIds?: UserID[] +} + +export interface EncryptResult { + data: string | ReadableStream; + message: message.Message; + signature: string | ReadableStream | signature.Signature; + sessionKey: { data: Uint8Array, algorithm: string, aeadAlgorithm: string }; +} + +/** + * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords + * must be specified. If private keys are specified, those will be used to sign the message. + * @param options + * @returns Object containing encrypted (and optionally signed) message in the form: + * { + * data: string|ReadableStream|NodeStream, (if `armor` was true, the default) + * message: Message, (if `armor` was false) + * signature: string|ReadableStream|NodeStream, (if `detached` was true and `armor` was true) + * signature: Signature (if `detached` was true and `armor` was false) + * sessionKey: { data, algorithm, aeadAlgorithm } (if `returnSessionKey` was true) + * } + */ +export function encrypt(options: EncryptOptions): Promise; + +export interface DecryptOptions { + /** + * the message object with the encrypted data + */ + message: message.Message; + /** + * (optional) private keys with decrypted secret key data or session key + */ + privateKeys?: key.Key | key.Key[]; + /** + * (optional) passwords to decrypt the message + */ + passwords?: string | string[]; + /** + * (optional) session keys in the form: { data:Uint8Array, algorithm:String } + */ + sessionKeys?: { data: Uint8Array, algorithm: string } | { data: Uint8Array, algorithm: string }[]; + /** + * (optional) array of public keys or single key, to verify signatures + */ + publicKeys?: key.Key | key.Key[]; + /** + * (optional) whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. + */ + format?: 'utf8' | 'binary'; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) detached signature for verification + */ + signature?: signature.Signature; + /** + * (optional) use the given date for verification instead of the current time + */ + date?: Date +} + +export interface DecryptResult { + data: string | ReadableStream | NodeStream | Uint8Array | ReadableStream, + filename: string, + signatures: { + keyid: type.keyid.Keyid, + verified: Promise, + valid: boolean + }[] +} + +/** + * Decrypts a message with the user's private key, a session key or a password. Either a private key, + * a session key or a password must be specified. + * @param options + * @returns Object containing decrypted and verified message in the form: + * { + * data: string|ReadableStream|NodeStream, (if format was 'utf8', the default) + * data: Uint8Array|ReadableStream|NodeStream, (if format was 'binary') + * filename: string, + * signatures: [ + * { + * keyid: module:type/keyid, + * verified: Promise, + * valid: boolean (if streaming was false) + * }, ... + * ] + * } + */ +export function decrypt(options: DecryptOptions): Promise; + +export interface SignOptions { + /** + * (cleartext) message to be signed + */ + message: cleartext.CleartextMessage | message.Message; + /** + * array of keys or single key with decrypted secret key data to sign cleartext + */ + privateKeys: key.Key | any[]; + /** + * (optional) if the return value should be ascii armored or the message object + */ + armor?: boolean; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) if the return value should contain a detached signature + */ + detached?: boolean; + /** + * (optional) override the creation date of the signature + */ + date?: Date; + /** + * (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + */ + fromUserIds?: UserID[] +} + +export interface SignResult { + data: string | ReadableStream | NodeStream, + message: message.Message, + signature: string | ReadableStream | NodeStream | signature.Signature +} + +/** + * Signs a cleartext message. + * @param options + * @returns Object containing signed message in the form: + * { + * data: string|ReadableStream|NodeStream, (if `armor` was true, the default) + * message: Message (if `armor` was false) + * } + * Or, if `detached` was true: + * { + * signature: string|ReadableStream|NodeStream, (if `armor` was true, the default) + * signature: Signature (if `armor` was false) + * } + */ +export function sign(options: SignOptions): Promise; + +export interface VerifyOptions { + /** + * array of publicKeys or single key, to verify signatures + */ + publicKeys: key.Key | any[]; + /** + * (cleartext) message object with signatures + */ + message: cleartext.CleartextMessage | message.Message; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) detached signature for verification + */ + signature?: signature.Signature; + /** + * (optional) use the given date for verification instead of the current time + */ + date?: Date +} + +export interface VerifyResult { + data: string | ReadableStream | NodeStream | Uint8Array | ReadableStream | NodeStream, + signatures: { + keyid: type.keyid.Keyid, + verified: Promise, + valid: boolean + }[] +} + +/** + * Verifies signatures of cleartext signed message + * @param options + * @returns Object containing verified message in the form: + * { + * data: string|ReadableStream|NodeStream, (if `message` was a CleartextMessage) + * data: Uint8Array|ReadableStream|NodeStream, (if `message` was a Message) + * signatures: [ + * { + * keyid: module:type/keyid, + * verified: Promise, + * valid: boolean (if `streaming` was false) + * }, ... + * ] + * } + */ +export function verify(options: VerifyOptions): Promise; + +/** + * Encrypt a symmetric session key with public keys, passwords, or both at once. At least either public keys + * or passwords must be specified. + * @param data the session key to be encrypted e.g. 16 random bytes (for aes128) + * @param algorithm algorithm of the symmetric session key e.g. 'aes128' or 'aes256' + * @param aeadAlgorithm (optional) aead algorithm, e.g. 'eax' or 'ocb' + * @param publicKeys (optional) array of public keys or single key, used to encrypt the key + * @param passwords (optional) passwords for the message + * @param wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param date (optional) override the date + * @param toUserIds (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] + * @returns the encrypted session key packets contained in a message object + */ +export function encryptSessionKey(data: Uint8Array, algorithm: string, aeadAlgorithm?: string, publicKeys?: key.Key | key.Key[], passwords?: string | string[], wildcard?: boolean, date?: Date, toUserIds?: any[]): Promise; + +/** + * Decrypt symmetric session keys with a private key or password. Either a private key or + * a password must be specified. + * @param message a message object containing the encrypted session key packets + * @param privateKeys (optional) private keys with decrypted secret key data + * @param passwords (optional) passwords to decrypt the session key + * @returns Array of decrypted session key, algorithm pairs in form: + * { data:Uint8Array, algorithm:String } + * or 'undefined' if no key packets found + */ +export function decryptSessionKeys(message: message.Message, privateKeys?: key.Key | key.Key[], passwords?: string | string[]): Promise<{ data: Uint8Array, algorithm: string }[] | undefined>; + +/** + * Input validation + */ +export function checkString(): void; + +/** + * Normalize parameter to an array if it is not undefined. + * @param param the parameter to be normalized + * @returns the resulting array or undefined + */ +export function toArray(param: object): any[] | undefined; + +/** + * Convert data to or from Stream + * @param data the data to convert + * @param streaming (optional) whether to return a ReadableStream + * @returns the data in the respective format + */ +export function convertStream(data: object, streaming?: 'web' | 'node' | false): object; + +/** + * Convert object properties from Stream + * @param obj the data to convert + * @param streaming (optional) whether to return ReadableStreams + * @param keys (optional) which keys to return as streams, if possible + * @returns the data in the respective format + */ +export function convertStreams(obj: object, streaming: 'web' | 'node' | false, keys: any[]): object; + +/** + * Link result.data to the message stream for cancellation. + * Also, forward errors in the message to result.data. + * @param result the data to convert + * @param message message object + * @param erroringStream (optional) stream which either errors or gets closed without data + * @returns + */ +export function linkStreams(result: object, message: message.Message, erroringStream: ReadableStream): object; + +/** + * Wait until signature objects have been verified + * @param signatures list of signatures + */ +export function prepareSignatures(signatures: object): void; + +/** + * Global error handler that logs the stack trace and rethrows a high lvl error message. + * @param message A human readable high level error Message + * @param error The internal error that caused the failure + */ +export function onError(message: string, error: Error): void; + +/** + * Check for native AEAD support and configuration by the user. Only + * browsers that implement the current WebCrypto specification support + * native GCM. Native EAX is built on CTR and CBC, which current + * browsers support. OCB and CFB are not natively supported. + * @returns If authenticated encryption should be used + */ +export function nativeAEAD(): boolean; diff --git a/types/openpgp/openpgp-tests.ts b/types/openpgp/openpgp-tests.ts index 3d5a1e3717..45a69aad1f 100644 --- a/types/openpgp/openpgp-tests.ts +++ b/types/openpgp/openpgp-tests.ts @@ -1,4 +1,4 @@ -import { openpgp } from "openpgp" +import openpgp from "openpgp" // Open PGP Sample codes diff --git a/types/openpgp/ts3.2/index.d.ts b/types/openpgp/ts3.2/index.d.ts index 62bccca432..442a458ccd 100644 --- a/types/openpgp/ts3.2/index.d.ts +++ b/types/openpgp/ts3.2/index.d.ts @@ -16,1589 +16,1560 @@ type NodeStream = stream; type Integer = number; type Infinity = any; - -export namespace openpgp { - namespace cleartext { +export namespace cleartext { + /** + * Class that represents an OpenPGP cleartext signed message. + * See {@link https://tools.ietf.org/html/rfc4880#section-7} + */ + class CleartextMessage { /** - * Class that represents an OpenPGP cleartext signed message. - * See {@link https://tools.ietf.org/html/rfc4880#section-7} + * @param text The cleartext of the signed message + * @param signature The detached signature or an empty signature for unsigned messages */ - class CleartextMessage { - /** - * @param text The cleartext of the signed message - * @param signature The detached signature or an empty signature for unsigned messages - */ - constructor(text: string, signature: signature.Signature); - - /** - * Returns the key IDs of the keys that signed the cleartext message - * @returns array of keyid objects - */ - getSigningKeyIds(): any[]; - - /** - * Sign the cleartext message - * @param privateKeys private keys with decrypted secret key data for signing - * @param signature (optional) any existing detached signature - * @param date (optional) The creation time of the signature that should be created - * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - * @returns new cleartext message with signed content - */ - sign(privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; - - /** - * Sign the cleartext message - * @param privateKeys private keys with decrypted secret key data for signing - * @param signature (optional) any existing detached signature - * @param date (optional) The creation time of the signature that should be created - * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - * @returns new detached signature of message content - */ - signDetached(privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; - - /** - * Verify signatures of cleartext signed message - * @param keys array of keys to verify signatures - * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @returns list of signer's keyid and validity of signature - */ - verify(keys: any[], date: Date): Promise>; - - /** - * Verify signatures of cleartext signed message - * @param keys array of keys to verify signatures - * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @returns list of signer's keyid and validity of signature - */ - verifyDetached(keys: any[], date: Date): Promise>; - - /** - * Get cleartext - * @returns cleartext of message - */ - getText(): string; - - /** - * Returns ASCII armored text of cleartext signed message - * @returns ASCII armor - */ - armor(): string | ReadableStream; - } + constructor(text: string, signature: signature.Signature); /** - * reads an OpenPGP cleartext signed message and returns a CleartextMessage object - * @param armoredText text to be parsed - * @returns new cleartext message object + * Returns the key IDs of the keys that signed the cleartext message + * @returns array of keyid objects */ - function readArmored(armoredText: string | ReadableStream): CleartextMessage; + getSigningKeyIds(): any[]; /** - * Creates a new CleartextMessage object from text - * @param text + * Sign the cleartext message + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature + * @param date (optional) The creation time of the signature that should be created + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new cleartext message with signed content */ - function fromText(text: string): void; + sign(privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; + + /** + * Sign the cleartext message + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature + * @param date (optional) The creation time of the signature that should be created + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new detached signature of message content + */ + signDetached(privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; + + /** + * Verify signatures of cleartext signed message + * @param keys array of keys to verify signatures + * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + verify(keys: any[], date: Date): Promise>; + + /** + * Verify signatures of cleartext signed message + * @param keys array of keys to verify signatures + * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + verifyDetached(keys: any[], date: Date): Promise>; + + /** + * Get cleartext + * @returns cleartext of message + */ + getText(): string; + + /** + * Returns ASCII armored text of cleartext signed message + * @returns ASCII armor + */ + armor(): string | ReadableStream; } /** - * @see module:config/config + * reads an OpenPGP cleartext signed message and returns a CleartextMessage object + * @param armoredText text to be parsed + * @returns new cleartext message object */ - namespace config { - var prefer_hash_algorithm: any; - - var encryption_cipher: any; - - var compression: any; - - var deflate_level: any; - - /** - * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. - * **NOT INTEROPERABLE WITH OTHER OPENPGP IMPLEMENTATIONS** - * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** - */ - var aead_protect: any; - - /** - * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. - * 0 means we implement a variant of {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00|this IETF draft}. - * 4 means we implement {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04|RFC4880bis-04}. - * Note that this determines how AEAD packets are parsed even when aead_protect is set to false - */ - var aead_protect_version: any; - - /** - * Default Authenticated Encryption with Additional Data (AEAD) encryption mode - * Only has an effect when aead_protect is set to true. - */ - var aead_mode: any; - - /** - * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode - * Only has an effect when aead_protect is set to true. - * Must be an integer value from 0 to 56. - */ - var aead_chunk_size_byte: any; - - /** - * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: - * Iteration Count Byte for S2K (String to Key) - */ - var s2k_iteration_count_byte: any; - - /** - * Use integrity protection for symmetric encryption - */ - var integrity_protect: any; - - var ignore_mdc_error: any; - - var allow_unauthenticated_stream: any; - - var checksum_required: any; - - var rsa_blinding: any; - - /** - * Work-around for rare GPG decryption bug when encrypting with multiple passwords. - * **Slower and slightly less secure** - */ - var password_collision_check: any; - - var revocations_expire: any; - - var use_native: any; - - var min_bytes_for_web_crypto: any; - - var zero_copy: any; - - var debug: any; - - var tolerant: any; - - var show_version: any; - - var show_comment: any; - - var versionstring: any; - - var commentstring: any; - - var keyserver: any; - - var node_store: any; - - /** - * Max userid string length (used for parsing) - */ - var max_userid_length: any; - - namespace localStorage { - class LocalStorage { - /** - * This object is used for storing and retrieving configuration from HTML5 local storage. - */ - constructor(); - - /** - * Reads the config out of the HTML5 local storage - * and initializes the object config. - * if config is null the default config will be used - */ - read(): void; - - /** - * Writes the config to HTML5 local storage - */ - write(): void; - } - } - } - - class LocalStorage { - /** - * This object is used for storing and retrieving configuration from HTML5 local storage. - */ - constructor(); - - /** - * Reads the config out of the HTML5 local storage - * and initializes the object config. - * if config is null the default config will be used - */ - read(): void; - - /** - * Writes the config to HTML5 local storage - */ - write(): void; - } - - + function readArmored(armoredText: string | ReadableStream): CleartextMessage; /** - * @see module:crypto/crypto - * @see module:crypto/signature - * @see module:crypto/public_key - * @see module:crypto/cipher - * @see module:crypto/random - * @see module:crypto/hash + * Creates a new CleartextMessage object from text + * @param text */ + function fromText(text: string): void; +} + +/** + * @see module:config/config + */ +export namespace config { + var prefer_hash_algorithm: any; + + var encryption_cipher: any; + + var compression: any; + + var deflate_level: any; + + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * **NOT INTEROPERABLE WITH OTHER OPENPGP IMPLEMENTATIONS** + * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** + */ + var aead_protect: any; + + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * 0 means we implement a variant of {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00|this IETF draft}. + * 4 means we implement {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04|RFC4880bis-04}. + * Note that this determines how AEAD packets are parsed even when aead_protect is set to false + */ + var aead_protect_version: any; + + /** + * Default Authenticated Encryption with Additional Data (AEAD) encryption mode + * Only has an effect when aead_protect is set to true. + */ + var aead_mode: any; + + /** + * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode + * Only has an effect when aead_protect is set to true. + * Must be an integer value from 0 to 56. + */ + var aead_chunk_size_byte: any; + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: + * Iteration Count Byte for S2K (String to Key) + */ + var s2k_iteration_count_byte: any; + + /** + * Use integrity protection for symmetric encryption + */ + var integrity_protect: any; + + var ignore_mdc_error: any; + + var allow_unauthenticated_stream: any; + + var checksum_required: any; + + var rsa_blinding: any; + + /** + * Work-around for rare GPG decryption bug when encrypting with multiple passwords. + * **Slower and slightly less secure** + */ + var password_collision_check: any; + + var revocations_expire: any; + + var use_native: any; + + var min_bytes_for_web_crypto: any; + + var zero_copy: any; + + var debug: any; + + var tolerant: any; + + var show_version: any; + + var show_comment: any; + + var versionstring: any; + + var commentstring: any; + + var keyserver: any; + + var node_store: any; + + /** + * Max userid string length (used for parsing) + */ + var max_userid_length: any; + + namespace localStorage { + class LocalStorage { + /** + * This object is used for storing and retrieving configuration from HTML5 local storage. + */ + constructor(); + + /** + * Reads the config out of the HTML5 local storage + * and initializes the object config. + * if config is null the default config will be used + */ + read(): void; + + /** + * Writes the config to HTML5 local storage + */ + write(): void; + } + } +} + +export class LocalStorage { + /** + * This object is used for storing and retrieving configuration from HTML5 local storage. + */ + constructor(); + + /** + * Reads the config out of the HTML5 local storage + * and initializes the object config. + * if config is null the default config will be used + */ + read(): void; + + /** + * Writes the config to HTML5 local storage + */ + write(): void; +} + + + +/** + * @see module:crypto/crypto + * @see module:crypto/signature + * @see module:crypto/public_key + * @see module:crypto/cipher + * @see module:crypto/random + * @see module:crypto/hash + */ +export namespace crypto { + /** + * @see module:crypto/public_key/elliptic/ecdh + */ + namespace aes_kw { + /** + * AES key wrap + * @param key + * @param data + * @returns + */ + function wrap(key: string, data: string): Uint8Array; + + /** + * AES key unwrap + * @param key + * @param data + * @returns + * @throws + */ + function unwrap(key: string, data: string): Uint8Array; + } + + namespace cfb { + function encrypt(algo: any, key: any, plaintext: any, iv: any): any + function decrypt(algo: any, key: any, ciphertext: any, iv: any): Promise + } + + namespace cipher { + /** + * AES-128 encryption and decryption (ID 7) + * @param key 128-bit key + * @see + * @see + * @returns + */ + function aes128(key: string): object; + + /** + * AES-128 Block Cipher (ID 8) + * @param key 192-bit key + * @see + * @see + * @returns + */ + function aes192(key: string): object; + + /** + * AES-128 Block Cipher (ID 9) + * @param key 256-bit key + * @see + * @see + * @returns + */ + function aes256(key: string): object; + + /** + * Triple DES Block Cipher (ID 2) + * @param key 192-bit key + * @see + * @returns + */ + function tripledes(key: string): object; + + /** + * CAST-128 Block Cipher (ID 3) + * @param key 128-bit key + * @see + * @returns + */ + function cast5(key: string): object; + + /** + * Twofish Block Cipher (ID 10) + * @param key 256-bit key + * @see + * @returns + */ + function twofish(key: string): object; + + /** + * Blowfish Block Cipher (ID 4) + * @param key 128-bit key + * @see + * @returns + */ + function blowfish(key: string): object; + + /** + * Not implemented + * @throws + */ + function idea(): void; + } + + namespace cmac { + /** + * This implementation of CMAC is based on the description of OMAC in + * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that + * document: + * We have made a small modification to the OMAC algorithm as it was + * originally presented, changing one of its two constants. + * Specifically, the constant 4 at line 85 was the constant 1/2 (the + * multiplicative inverse of 2) in the original definition of OMAC [14]. + * The OMAC authors indicate that they will promulgate this modification + * [15], which slightly simplifies implementations. + */ + const blockLength: any; + + /** + * xor `padding` into the end of `data`. This function implements "the + * operation xor→ [which] xors the shorter string into the end of longer + * one". Since data is always as least as long as padding, we can + * simplify the implementation. + * @param data + * @param padding + */ + function rightXorMut(data: Uint8Array, padding: Uint8Array): void; + } + namespace crypto { /** - * @see module:crypto/public_key/elliptic/ecdh + * Encrypts data using specified algorithm and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param algo Public key algorithm + * @param pub_params Algorithm-specific public key parameters + * @param data Data to be encrypted as MPI + * @param fingerprint Recipient fingerprint + * @returns encrypted session key parameters + */ + function publicKeyEncrypt(algo: enums.publicKey, pub_params: Array, data: type.mpi.MPI, fingerprint: string): any[]; + + /** + * Decrypts data using specified algorithm and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param algo Public key algorithm + * @param key_params Algorithm-specific public, private key parameters + * @param data_params encrypted session key parameters + * @param fingerprint Recipient fingerprint + * @returns An MPI containing the decrypted data + */ + function publicKeyDecrypt(algo: enums.publicKey, key_params: Array, data_params: Array, fingerprint: string): type.mpi.MPI; + + /** + * Returns the types comprising the private key of an algorithm + * @param algo The public key algorithm + * @returns The array of types + */ + function getPrivKeyParamTypes(algo: string): any[]; + + /** + * Returns the types comprising the public key of an algorithm + * @param algo The public key algorithm + * @returns The array of types + */ + function getPubKeyParamTypes(algo: string): any[]; + + /** + * Returns the types comprising the encrypted session key of an algorithm + * @param algo The public key algorithm + * @returns The array of types + */ + function getEncSessionKeyParamTypes(algo: string): any[]; + + /** + * Generate algorithm-specific key parameters + * @param algo The public key algorithm + * @param bits Bit length for RSA keys + * @param oid Object identifier for ECC keys + * @returns The array of parameters + */ + function generateParams(algo: string, bits: Integer, oid: type.oid.OID): any[]; + + /** + * Generates a random byte prefix for the specified algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param algo Symmetric encryption algorithm + * @returns Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. + */ + function getPrefixRandom(algo: enums.symmetric): Uint8Array; + + /** + * Generating a session key for the specified symmetric algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param algo Symmetric encryption algorithm + * @returns Random bytes as a string to be used as a key + */ + function generateSessionKey(algo: enums.symmetric): Uint8Array; + } + + namespace eax { + /** + * Class to en/decrypt using EAX mode. + * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' + * @param key The encryption key + */ + function EAX(cipher: string, key: Uint8Array): void; + + /** + * Encrypt plaintext input. + * @param plaintext The cleartext input to be encrypted + * @param nonce The nonce (16 bytes) + * @param adata Associated data to sign + * @returns The ciphertext output + */ + function encrypt(plaintext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + + /** + * Decrypt ciphertext input. + * @param ciphertext The ciphertext input to be decrypted + * @param nonce The nonce (16 bytes) + * @param adata Associated data to verify + * @returns The plaintext output + */ + function decrypt(ciphertext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + } + + namespace gcm { + /** + * Class to en/decrypt using GCM mode. + * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' + * @param key The encryption key + */ + function GCM(cipher: string, key: Uint8Array): void; + } + + /** + * @see + * @see */ - namespace aes_kw { + namespace hash { + /** + * @see module:md5 + */ + var md5: any; + + /** + * @see asmCrypto + */ + var sha1: any; + + /** + * @see hash.js + */ + var sha224: any; + + /** + * @see asmCrypto + */ + var sha256: any; + + /** + * @see hash.js + */ + var sha384: any; + + /** + * @see asmCrypto + */ + var sha512: any; + + /** + * @see hash.js + */ + var ripemd: any; + + /** + * Create a hash on the specified data using the specified algorithm + * @param algo Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @param data Data to be hashed + * @returns hash value + */ + function digest(algo: enums.hash, data: Uint8Array): Promise; + + /** + * Returns the hash size in bytes of the specified hash algorithm type + * @param algo Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @returns Size in bytes of the resulting hash + */ + function getHashByteLength(algo: enums.hash): Integer; + } + + /** + * @see module:packet.PublicKeyEncryptedSessionKey + */ + namespace pkcs5 { + /** + * Add pkcs5 padding to a text. + * @param msg Text to add padding + * @returns Text with padding added + */ + function encode(msg: string): string; + + /** + * Remove pkcs5 padding from a string. + * @param msg Text to remove padding from + * @returns Text with padding removed + */ + function decode(msg: string): string; + } + + namespace ocb { + /** + * Class to en/decrypt using OCB mode. + * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' + * @param key The encryption key + */ + function OCB(cipher: string, key: Uint8Array): void; + + /** + * Encrypt plaintext input. + * @param plaintext The cleartext input to be encrypted + * @param nonce The nonce (15 bytes) + * @param adata Associated data to sign + * @returns The ciphertext output + */ + function encrypt(plaintext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + + /** + * Decrypt ciphertext input. + * @param ciphertext The ciphertext input to be decrypted + * @param nonce The nonce (15 bytes) + * @param adata Associated data to sign + * @returns The ciphertext output + */ + function decrypt(ciphertext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + } + + /** + * @see module:crypto/public_key/rsa + * @see module:crypto/public_key/elliptic/ecdh + * @see module:packet.PublicKeyEncryptedSessionKey + */ + namespace pkcs1 { + namespace eme { /** - * AES key wrap - * @param key - * @param data - * @returns + * Create a EME-PKCS1-v1_5 padded message + * @see + * @param M message to be encoded + * @param k the length in octets of the key modulus + * @returns EME-PKCS1 padded message */ - function wrap(key: string, data: string): Uint8Array; + function encode(M: string, k: Integer): Promise; /** - * AES key unwrap - * @param key - * @param data - * @returns - * @throws + * Decode a EME-PKCS1-v1_5 padded message + * @see + * @param EM encoded message, an octet string + * @returns message, an octet string */ - function unwrap(key: string, data: string): Uint8Array; + function decode(EM: string): string; } - namespace cfb { - function encrypt(algo: any, key: any, plaintext: any, iv: any): any - function decrypt(algo: any, key: any, ciphertext: any, iv: any): Promise - } - - namespace cipher { + namespace emsa { /** - * AES-128 encryption and decryption (ID 7) - * @param key 128-bit key + * Create a EMSA-PKCS1-v1_5 padded message * @see - * @see - * @returns + * @param algo Hash algorithm type used + * @param hashed message to be encoded + * @param emLen intended length in octets of the encoded message + * @returns encoded message */ - function aes128(key: string): object; - - /** - * AES-128 Block Cipher (ID 8) - * @param key 192-bit key - * @see - * @see - * @returns - */ - function aes192(key: string): object; - - /** - * AES-128 Block Cipher (ID 9) - * @param key 256-bit key - * @see - * @see - * @returns - */ - function aes256(key: string): object; - - /** - * Triple DES Block Cipher (ID 2) - * @param key 192-bit key - * @see - * @returns - */ - function tripledes(key: string): object; - - /** - * CAST-128 Block Cipher (ID 3) - * @param key 128-bit key - * @see - * @returns - */ - function cast5(key: string): object; - - /** - * Twofish Block Cipher (ID 10) - * @param key 256-bit key - * @see - * @returns - */ - function twofish(key: string): object; - - /** - * Blowfish Block Cipher (ID 4) - * @param key 128-bit key - * @see - * @returns - */ - function blowfish(key: string): object; - - /** - * Not implemented - * @throws - */ - function idea(): void; - } - - namespace cmac { - /** - * This implementation of CMAC is based on the description of OMAC in - * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that - * document: - * We have made a small modification to the OMAC algorithm as it was - * originally presented, changing one of its two constants. - * Specifically, the constant 4 at line 85 was the constant 1/2 (the - * multiplicative inverse of 2) in the original definition of OMAC [14]. - * The OMAC authors indicate that they will promulgate this modification - * [15], which slightly simplifies implementations. - */ - const blockLength: any; - - /** - * xor `padding` into the end of `data`. This function implements "the - * operation xor→ [which] xors the shorter string into the end of longer - * one". Since data is always as least as long as padding, we can - * simplify the implementation. - * @param data - * @param padding - */ - function rightXorMut(data: Uint8Array, padding: Uint8Array): void; - } - - namespace crypto { - /** - * Encrypts data using specified algorithm and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. - * @param algo Public key algorithm - * @param pub_params Algorithm-specific public key parameters - * @param data Data to be encrypted as MPI - * @param fingerprint Recipient fingerprint - * @returns encrypted session key parameters - */ - function publicKeyEncrypt(algo: enums.publicKey, pub_params: Array, data: type.mpi.MPI, fingerprint: string): any[]; - - /** - * Decrypts data using specified algorithm and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. - * @param algo Public key algorithm - * @param key_params Algorithm-specific public, private key parameters - * @param data_params encrypted session key parameters - * @param fingerprint Recipient fingerprint - * @returns An MPI containing the decrypted data - */ - function publicKeyDecrypt(algo: enums.publicKey, key_params: Array, data_params: Array, fingerprint: string): type.mpi.MPI; - - /** - * Returns the types comprising the private key of an algorithm - * @param algo The public key algorithm - * @returns The array of types - */ - function getPrivKeyParamTypes(algo: string): any[]; - - /** - * Returns the types comprising the public key of an algorithm - * @param algo The public key algorithm - * @returns The array of types - */ - function getPubKeyParamTypes(algo: string): any[]; - - /** - * Returns the types comprising the encrypted session key of an algorithm - * @param algo The public key algorithm - * @returns The array of types - */ - function getEncSessionKeyParamTypes(algo: string): any[]; - - /** - * Generate algorithm-specific key parameters - * @param algo The public key algorithm - * @param bits Bit length for RSA keys - * @param oid Object identifier for ECC keys - * @returns The array of parameters - */ - function generateParams(algo: string, bits: Integer, oid: type.oid.OID): any[]; - - /** - * Generates a random byte prefix for the specified algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param algo Symmetric encryption algorithm - * @returns Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. - */ - function getPrefixRandom(algo: enums.symmetric): Uint8Array; - - /** - * Generating a session key for the specified symmetric algorithm - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param algo Symmetric encryption algorithm - * @returns Random bytes as a string to be used as a key - */ - function generateSessionKey(algo: enums.symmetric): Uint8Array; - } - - namespace eax { - /** - * Class to en/decrypt using EAX mode. - * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' - * @param key The encryption key - */ - function EAX(cipher: string, key: Uint8Array): void; - - /** - * Encrypt plaintext input. - * @param plaintext The cleartext input to be encrypted - * @param nonce The nonce (16 bytes) - * @param adata Associated data to sign - * @returns The ciphertext output - */ - function encrypt(plaintext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; - - /** - * Decrypt ciphertext input. - * @param ciphertext The ciphertext input to be decrypted - * @param nonce The nonce (16 bytes) - * @param adata Associated data to verify - * @returns The plaintext output - */ - function decrypt(ciphertext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; - } - - namespace gcm { - /** - * Class to en/decrypt using GCM mode. - * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' - * @param key The encryption key - */ - function GCM(cipher: string, key: Uint8Array): void; + function encode(algo: Integer, hashed: Uint8Array, emLen: Integer): string; } /** - * @see + * ASN1 object identifiers for hashes * @see */ - namespace hash { + const hash_headers: any; + } + + namespace public_key { + namespace dsa { /** - * @see module:md5 + * DSA Sign function + * @param hash_algo + * @param hashed + * @param g + * @param p + * @param q + * @param x + * @returns */ - var md5: any; + function sign(hash_algo: Integer, hashed: Uint8Array, g: BN, p: BN, q: BN, x: BN): object; /** - * @see asmCrypto + * DSA Verify function + * @param hash_algo + * @param r + * @param s + * @param hashed + * @param g + * @param p + * @param q + * @param y + * @returns BN */ - var sha1: any; + function verify(hash_algo: Integer, r: BN, s: BN, hashed: Uint8Array, g: BN, p: BN, q: BN, y: BN): any; + } + + namespace elgamal { + /** + * ElGamal Encryption function + * @param m + * @param p + * @param g + * @param y + * @returns + */ + function encrypt(m: BN, p: BN, g: BN, y: BN): object; /** - * @see hash.js + * ElGamal Encryption function + * @param c1 + * @param c2 + * @param p + * @param x + * @returns BN */ - var sha224: any; - - /** - * @see asmCrypto - */ - var sha256: any; - - /** - * @see hash.js - */ - var sha384: any; - - /** - * @see asmCrypto - */ - var sha512: any; - - /** - * @see hash.js - */ - var ripemd: any; - - /** - * Create a hash on the specified data using the specified algorithm - * @param algo Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @param data Data to be hashed - * @returns hash value - */ - function digest(algo: enums.hash, data: Uint8Array): Promise; - - /** - * Returns the hash size in bytes of the specified hash algorithm type - * @param algo Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) - * @returns Size in bytes of the resulting hash - */ - function getHashByteLength(algo: enums.hash): Integer; + function decrypt(c1: BN, c2: BN, p: BN, x: BN): any; } /** - * @see module:packet.PublicKeyEncryptedSessionKey - */ - namespace pkcs5 { - /** - * Add pkcs5 padding to a text. - * @param msg Text to add padding - * @returns Text with padding added - */ - function encode(msg: string): string; - - /** - * Remove pkcs5 padding from a string. - * @param msg Text to remove padding from - * @returns Text with padding removed - */ - function decode(msg: string): string; - } - - namespace ocb { - /** - * Class to en/decrypt using OCB mode. - * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' - * @param key The encryption key - */ - function OCB(cipher: string, key: Uint8Array): void; - - /** - * Encrypt plaintext input. - * @param plaintext The cleartext input to be encrypted - * @param nonce The nonce (15 bytes) - * @param adata Associated data to sign - * @returns The ciphertext output - */ - function encrypt(plaintext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; - - /** - * Decrypt ciphertext input. - * @param ciphertext The ciphertext input to be decrypted - * @param nonce The nonce (15 bytes) - * @param adata Associated data to sign - * @returns The ciphertext output - */ - function decrypt(ciphertext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; - } - - /** - * @see module:crypto/public_key/rsa + * @see module:crypto/public_key/elliptic/curve * @see module:crypto/public_key/elliptic/ecdh - * @see module:packet.PublicKeyEncryptedSessionKey + * @see module:crypto/public_key/elliptic/ecdsa + * @see module:crypto/public_key/elliptic/eddsa */ - namespace pkcs1 { - namespace eme { - /** - * Create a EME-PKCS1-v1_5 padded message - * @see - * @param M message to be encoded - * @param k the length in octets of the key modulus - * @returns EME-PKCS1 padded message - */ - function encode(M: string, k: Integer): Promise; - - /** - * Decode a EME-PKCS1-v1_5 padded message - * @see - * @param EM encoded message, an octet string - * @returns message, an octet string - */ - function decode(EM: string): string; - } - - namespace emsa { - /** - * Create a EMSA-PKCS1-v1_5 padded message - * @see - * @param algo Hash algorithm type used - * @param hashed message to be encoded - * @param emLen intended length in octets of the encoded message - * @returns encoded message - */ - function encode(algo: Integer, hashed: Uint8Array, emLen: Integer): string; - } - - /** - * ASN1 object identifiers for hashes - * @see - */ - const hash_headers: any; - } - - namespace public_key { - namespace dsa { - /** - * DSA Sign function - * @param hash_algo - * @param hashed - * @param g - * @param p - * @param q - * @param x - * @returns - */ - function sign(hash_algo: Integer, hashed: Uint8Array, g: BN, p: BN, q: BN, x: BN): object; - - /** - * DSA Verify function - * @param hash_algo - * @param r - * @param s - * @param hashed - * @param g - * @param p - * @param q - * @param y - * @returns BN - */ - function verify(hash_algo: Integer, r: BN, s: BN, hashed: Uint8Array, g: BN, p: BN, q: BN, y: BN): any; - } - - namespace elgamal { - /** - * ElGamal Encryption function - * @param m - * @param p - * @param g - * @param y - * @returns - */ - function encrypt(m: BN, p: BN, g: BN, y: BN): object; - - /** - * ElGamal Encryption function - * @param c1 - * @param c2 - * @param p - * @param x - * @returns BN - */ - function decrypt(c1: BN, c2: BN, p: BN, x: BN): any; - } - - /** - * @see module:crypto/public_key/elliptic/curve - * @see module:crypto/public_key/elliptic/ecdh - * @see module:crypto/public_key/elliptic/ecdsa - * @see module:crypto/public_key/elliptic/eddsa - */ - namespace elliptic { - namespace curve { - class Curve { - } - } - - namespace ecdh { - /** - * Generate ECDHE ephemeral key and secret from public key - * @param curve Elliptic curve object - * @param Q Recipient public key - * @returns Returns public part of ephemeral key and generated ephemeral secret - */ - function genPublicEphemeralKey(curve: curve.Curve, Q: Uint8Array): Promise<{ V: Uint8Array, S: BN }>; - - /** - * Encrypt and wrap a session key - * @param oid Elliptic curve object identifier - * @param cipher_algo Symmetric cipher to use - * @param hash_algo Hash algorithm to use - * @param m Value derived from session key (RFC 6637) - * @param Q Recipient public key - * @param fingerprint Recipient fingerprint - * @returns Returns public part of ephemeral key and encoded session key - */ - function encrypt(oid: type.oid.OID, cipher_algo: enums.symmetric, hash_algo: enums.hash, m: type.mpi.MPI, Q: Uint8Array, fingerprint: string): Promise<{ V: BN, C: BN }>; - - /** - * Generate ECDHE secret from private key and public part of ephemeral key - * @param curve Elliptic curve object - * @param V Public part of ephemeral key - * @param d Recipient private key - * @returns Generated ephemeral secret - */ - function genPrivateEphemeralKey(curve: curve.Curve, V: Uint8Array, d: Uint8Array): Promise; - - /** - * Decrypt and unwrap the value derived from session key - * @param oid Elliptic curve object identifier - * @param cipher_algo Symmetric cipher to use - * @param hash_algo Hash algorithm to use - * @param V Public part of ephemeral key - * @param C Encrypted and wrapped value derived from session key - * @param d Recipient private key - * @param fingerprint Recipient fingerprint - * @returns Value derived from session - */ - function decrypt(oid: type.oid.OID, cipher_algo: enums.symmetric, hash_algo: enums.hash, V: Uint8Array, C: Uint8Array, d: Uint8Array, fingerprint: string): Promise; - } - - namespace ecdsa { - /** - * Sign a message using the provided key - * @param oid Elliptic curve object identifier - * @param hash_algo Hash algorithm used to sign - * @param m Message to sign - * @param d Private key used to sign the message - * @param hashed The hashed message - * @returns Signature of the message - */ - function sign(oid: type.oid.OID, hash_algo: enums.hash, m: Uint8Array, d: Uint8Array, hashed: Uint8Array): object; - - /** - * Verifies if a signature is valid for a message - * @param oid Elliptic curve object identifier - * @param hash_algo Hash algorithm used in the signature - * @param signature Signature to verify - * @param m Message to verify - * @param Q Public key used to verify the message - * @param hashed The hashed message - * @returns - */ - function verify(oid: type.oid.OID, hash_algo: enums.hash, signature: object, m: Uint8Array, Q: Uint8Array, hashed: Uint8Array): boolean; - } - - namespace eddsa { - /** - * Sign a message using the provided keygit - * @param oid Elliptic curve object identifier - * @param hash_algo Hash algorithm used to sign - * @param m Message to sign - * @param d Private key used to sign - * @param hashed The hashed message - * @returns Signature of the message - */ - function sign(oid: type.oid.OID, hash_algo: enums.hash, m: Uint8Array, d: Uint8Array, hashed: Uint8Array): object; - - /** - * Verifies if a signature is valid for a message - * @param oid Elliptic curve object identifier - * @param hash_algo Hash algorithm used in the signature - * @param signature Signature to verify the message - * @param m Message to verify - * @param Q Public key used to verify the message - * @param hashed The hashed message - * @returns - */ - function verify(oid: type.oid.OID, hash_algo: enums.hash, signature: object, m: Uint8Array, Q: Uint8Array, hashed: Uint8Array): boolean; - } - - namespace key { - class KeyPair { - } + namespace elliptic { + namespace curve { + class Curve { } } - namespace prime { + namespace ecdh { /** - * Probabilistic random number generator - * @param bits Bit length of the prime - * @param e Optional RSA exponent to check against the prime - * @param k Optional number of iterations of Miller-Rabin test - * @returns BN + * Generate ECDHE ephemeral key and secret from public key + * @param curve Elliptic curve object + * @param Q Recipient public key + * @returns Returns public part of ephemeral key and generated ephemeral secret */ - function randomProbablePrime(bits: Integer, e: BN, k: Integer): any; + function genPublicEphemeralKey(curve: curve.Curve, Q: Uint8Array): Promise<{ V: Uint8Array, S: BN }>; /** - * Probabilistic primality testing - * @param n Number to test - * @param e Optional RSA exponent to check against the prime - * @param k Optional number of iterations of Miller-Rabin test - * @returns + * Encrypt and wrap a session key + * @param oid Elliptic curve object identifier + * @param cipher_algo Symmetric cipher to use + * @param hash_algo Hash algorithm to use + * @param m Value derived from session key (RFC 6637) + * @param Q Recipient public key + * @param fingerprint Recipient fingerprint + * @returns Returns public part of ephemeral key and encoded session key */ - function isProbablePrime(n: BN, e: BN, k: Integer): boolean; + function encrypt(oid: type.oid.OID, cipher_algo: enums.symmetric, hash_algo: enums.hash, m: type.mpi.MPI, Q: Uint8Array, fingerprint: string): Promise<{ V: BN, C: BN }>; /** - * Tests whether n is probably prime or not using Fermat's test with b = 2. - * Fails if b^(n-1) mod n === 1. - * @param n Number to test - * @param b Optional Fermat test base - * @returns + * Generate ECDHE secret from private key and public part of ephemeral key + * @param curve Elliptic curve object + * @param V Public part of ephemeral key + * @param d Recipient private key + * @returns Generated ephemeral secret */ - function fermat(n: BN, b: Integer): boolean; + function genPrivateEphemeralKey(curve: curve.Curve, V: Uint8Array, d: Uint8Array): Promise; /** - * Tests whether n is probably prime or not using the Miller-Rabin test. - * See HAC Remark 4.28. - * @param n Number to test - * @param k Optional number of iterations of Miller-Rabin test - * @param rand Optional function to generate potential witnesses - * @returns + * Decrypt and unwrap the value derived from session key + * @param oid Elliptic curve object identifier + * @param cipher_algo Symmetric cipher to use + * @param hash_algo Hash algorithm to use + * @param V Public part of ephemeral key + * @param C Encrypted and wrapped value derived from session key + * @param d Recipient private key + * @param fingerprint Recipient fingerprint + * @returns Value derived from session */ - function millerRabin(n: BN, k: Integer, rand: Function): boolean; + function decrypt(oid: type.oid.OID, cipher_algo: enums.symmetric, hash_algo: enums.hash, V: Uint8Array, C: Uint8Array, d: Uint8Array, fingerprint: string): Promise; } - namespace rsa { + namespace ecdsa { /** - * Create signature - * @param m message - * @param n RSA public modulus - * @param e RSA public exponent - * @param d RSA private exponent - * @returns RSA Signature + * Sign a message using the provided key + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used to sign + * @param m Message to sign + * @param d Private key used to sign the message + * @param hashed The hashed message + * @returns Signature of the message */ - function sign(m: BN, n: BN, e: BN, d: BN): BN; + function sign(oid: type.oid.OID, hash_algo: enums.hash, m: Uint8Array, d: Uint8Array, hashed: Uint8Array): object; /** - * Verify signature - * @param s signature - * @param n RSA public modulus - * @param e RSA public exponent + * Verifies if a signature is valid for a message + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used in the signature + * @param signature Signature to verify + * @param m Message to verify + * @param Q Public key used to verify the message + * @param hashed The hashed message * @returns */ - function verify(s: BN, n: BN, e: BN): BN; + function verify(oid: type.oid.OID, hash_algo: enums.hash, signature: object, m: Uint8Array, Q: Uint8Array, hashed: Uint8Array): boolean; + } + + namespace eddsa { + /** + * Sign a message using the provided keygit + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used to sign + * @param m Message to sign + * @param d Private key used to sign + * @param hashed The hashed message + * @returns Signature of the message + */ + function sign(oid: type.oid.OID, hash_algo: enums.hash, m: Uint8Array, d: Uint8Array, hashed: Uint8Array): object; /** - * Encrypt message - * @param m message - * @param n RSA public modulus - * @param e RSA public exponent - * @returns RSA Ciphertext + * Verifies if a signature is valid for a message + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used in the signature + * @param signature Signature to verify the message + * @param m Message to verify + * @param Q Public key used to verify the message + * @param hashed The hashed message + * @returns */ - function encrypt(m: BN, n: BN, e: BN): BN; + function verify(oid: type.oid.OID, hash_algo: enums.hash, signature: object, m: Uint8Array, Q: Uint8Array, hashed: Uint8Array): boolean; + } - /** - * Decrypt RSA message - * @param m message - * @param n RSA public modulus - * @param e RSA public exponent - * @param d RSA private exponent - * @param p RSA private prime p - * @param q RSA private prime q - * @param u RSA private inverse of prime q - * @returns RSA Plaintext - */ - function decrypt(m: BN, n: BN, e: BN, d: BN, p: BN, q: BN, u: BN): BN; - - /** - * Generate a new random private key B bits long with public exponent E. - * When possible, webCrypto is used. Otherwise, primes are generated using - * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. - * @see module:crypto/public_key/prime - * @param B RSA bit length - * @param E RSA public exponent in hex string - * @returns RSA public modulus, RSA public exponent, RSA private exponent, - * RSA private prime p, RSA private prime q, u = q ** -1 mod p - */ - function generate(B: Integer, E: string): object; + namespace key { + class KeyPair { + } } } - namespace random { + namespace prime { /** - * Retrieve secure random byte array of the specified length - * @param length Length in bytes to generate - * @returns Random byte array + * Probabilistic random number generator + * @param bits Bit length of the prime + * @param e Optional RSA exponent to check against the prime + * @param k Optional number of iterations of Miller-Rabin test + * @returns BN */ - function getRandomBytes(length: Integer): Uint8Array; + function randomProbablePrime(bits: Integer, e: BN, k: Integer): any; /** - * Create a secure random MPI that is greater than or equal to min and less than max. - * @param min Lower bound, included - * @param max Upper bound, excluded - * @returns Random MPI - */ - function getRandomBN(min: type.mpi.MPI, max: type.mpi.MPI): BN; - - /** - * Buffer for secure random numbers - */ - function RandomBuffer(): void; - } - - namespace signature { - /** - * Verifies the signature provided for data using specified algorithms and public key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param algo Public key algorithm - * @param hash_algo Hash algorithm - * @param msg_MPIs Algorithm-specific signature parameters - * @param pub_MPIs Algorithm-specific public key parameters - * @param data Data for which the signature was created - * @param hashed The hashed data - * @returns True if signature is valid - */ - function verify(algo: enums.publicKey, hash_algo: enums.hash, msg_MPIs: type.mpi.MPI[], pub_MPIs: type.mpi.MPI[], data: Uint8Array, hashed: Uint8Array): boolean; - - /** - * Creates a signature on data using specified algorithms and private key parameters. - * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} - * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} - * for public key and hash algorithms. - * @param algo Public key algorithm - * @param hash_algo Hash algorithm - * @param key_params Algorithm-specific public and private key parameters - * @param data Data to be signed - * @param hashed The hashed data - * @returns Signature - */ - function sign(algo: enums.publicKey, hash_algo: enums.hash, key_params: type.mpi.MPI[], data: Uint8Array, hashed: Uint8Array): Uint8Array; - } - } - - namespace eme { - /** - * Create a EME-PKCS1-v1_5 padded message - * @see - * @param M message to be encoded - * @param k the length in octets of the key modulus - * @returns EME-PKCS1 padded message - */ - function encode(M: string, k: Integer): Promise; - - /** - * Decode a EME-PKCS1-v1_5 padded message - * @see - * @param EM encoded message, an octet string - * @returns message, an octet string - */ - function decode(EM: string): string; - } - - namespace emsa { - /** - * Create a EMSA-PKCS1-v1_5 padded message - * @see - * @param algo Hash algorithm type used - * @param hashed message to be encoded - * @param emLen intended length in octets of the encoded message - * @returns encoded message - */ - function encode(algo: Integer, hashed: Uint8Array, emLen: Integer): string; - } - - namespace encoding { - namespace armor { - /** - * Add additional information to the armor version of an OpenPGP binary - * packet block. - * @author Alex - * @version 2011-12-16 - * @param customComment (optional) additional comment to add to the armored string - * @returns The header information - */ - function addheader(customComment: string): string; - - /** - * Calculates a checksum over the given data and returns it base64 encoded - * @param data Data to create a CRC-24 checksum for - * @returns Base64 encoded checksum - */ - function getCheckSum(data: string | ReadableStream): string | ReadableStream; - - /** - * Internal function to calculate a CRC-24 checksum over a given string (data) - * @param data Data to create a CRC-24 checksum for - * @returns The CRC-24 checksum - */ - function createcrc24(data: string | ReadableStream): Uint8Array | ReadableStream; - - /** - * Splits a message into two parts, the body and the checksum. This is an internal function - * @param text OpenPGP armored message part - * @returns An object with attribute "body" containing the body - * and an attribute "checksum" containing the checksum. - */ - function splitChecksum(text: string): object; - - /** - * DeArmor an OpenPGP armored message; verify the checksum and return - * the encoded bytes - * @param text OpenPGP armored message - * @returns An object with attribute "text" containing the message text, - * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type - */ - function dearmor(text: string): Promise; - - /** - * Armor an OpenPGP binary packet block - * @param messagetype type of the message - * @param body - * @param partindex - * @param parttotal - * @param customComment (optional) additional comment to add to the armored string - * @returns Armored text - */ - function armor(messagetype: Integer, body: any, partindex: Integer, parttotal: Integer, customComment?: string): string | ReadableStream; - } - - namespace base64 { - /** - * Convert binary array to radix-64 - * @param t Uint8Array to convert - * @param u if true, output is URL-safe - * @returns radix-64 version of input string - */ - function s2r(t: Uint8Array | ReadableStream, u?: boolean): string | ReadableStream; - - /** - * Convert radix-64 to binary array - * @param t radix-64 string to convert - * @param u if true, input is interpreted as URL-safe - * @returns binary array version of input string - */ - function r2s(t: string | ReadableStream, u: boolean): Uint8Array | ReadableStream; - } - } - - namespace enums { - /** - * Maps curve names under various standards to one - * @see - */ - enum curve { - /** - * NIST P-256 Curve - */ - p256 = "p256", - "P-256" = "p256", - secp256r1 = "p256", - prime256v1 = "p256", - "1.2.840.10045.3.1.7" = "p256", - "2a8648ce3d030107" = "p256", - "2A8648CE3D030107" = "p256", - /** - * NIST P-384 Curve - */ - p384 = "p384", - "P-384" = "p384", - secp384r1 = "p384", - "1.3.132.0.34" = "p384", - "2b81040022" = "p384", - "2B81040022" = "p384", - /** - * NIST P-521 Curve - */ - p521 = "p521", - "P-521" = "p521", - secp521r1 = "p521", - "1.3.132.0.35" = "p521", - "2b81040023" = "p521", - "2B81040023" = "p521", - /** - * SECG SECP256k1 Curve - */ - secp256k1 = "secp256k1", - "1.3.132.0.10" = "secp256k1", - "2b8104000a" = "secp256k1", - "2B8104000A" = "secp256k1", - /** - * Ed25519 - */ - ED25519 = "ed25519", - ed25519 = "ed25519", - Ed25519 = "ed25519", - "1.3.6.1.4.1.11591.15.1" = "ed25519", - "2b06010401da470f01" = "ed25519", - "2B06010401DA470F01" = "ed25519", - /** - * Curve25519 - */ - X25519 = "curve25519", - cv25519 = "curve25519", - curve25519 = "curve25519", - Curve25519 = "curve25519", - "1.3.6.1.4.1.3029.1.5.1" = "curve25519", - "2b060104019755010501" = "curve25519", - "2B060104019755010501" = "curve25519", - /** - * BrainpoolP256r1 Curve - */ - brainpoolP256r1 = "brainpoolP256r1", - "1.3.36.3.3.2.8.1.1.7" = "brainpoolP256r1", - "2b2403030208010107" = "brainpoolP256r1", - "2B2403030208010107" = "brainpoolP256r1", - /** - * BrainpoolP384r1 Curve - */ - brainpoolP384r1 = "brainpoolP384r1", - "1.3.36.3.3.2.8.1.1.11" = "brainpoolP384r1", - "2b240303020801010b" = "brainpoolP384r1", - "2B240303020801010B" = "brainpoolP384r1", - /** - * BrainpoolP512r1 Curve - */ - brainpoolP512r1 = "brainpoolP512r1", - "1.3.36.3.3.2.8.1.1.13" = "brainpoolP512r1", - "2b240303020801010d" = "brainpoolP512r1", - "2B240303020801010D" = "brainpoolP512r1", - } - - /** - * A string to key specifier type - */ - enum s2k { - simple = 0, - salted = 1, - iterated = 3, - gnu = 101, - } - - /** - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.1|RFC4880bis-04, section 9.1} - */ - enum publicKey { - /** - * RSA (Encrypt or Sign) [HAC] - */ - rsa_encrypt_sign = 1, - /** - * RSA (Encrypt only) [HAC] - */ - rsa_encrypt = 2, - /** - * RSA (Sign only) [HAC] - */ - rsa_sign = 3, - /** - * Elgamal (Encrypt only) [ELGAMAL] [HAC] - */ - elgamal = 16, - /** - * DSA (Sign only) [FIPS186] [HAC] - */ - dsa = 17, - /** - * ECDH (Encrypt only) [RFC6637] - */ - ecdh = 18, - /** - * ECDSA (Sign only) [RFC6637] - */ - ecdsa = 19, - /** - * EdDSA (Sign only) - * [ {@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] - */ - eddsa = 22, - /** - * Reserved for AEDH - */ - aedh = 23, - /** - * Reserved for AEDSA - */ - aedsa = 24, - } - - /** - * {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} - */ - enum symmetric { - plaintext = 0, - /** - * Not implemented! - */ - idea = 1, - "3des" = 2, - tripledes = 2, - cast5 = 3, - blowfish = 4, - aes128 = 7, - aes192 = 8, - aes256 = 9, - twofish = 10, - } - - /** - * {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} - */ - enum compression { - uncompressed = 0, - /** - * RFC1951 - */ - zip = 1, - /** - * RFC1950 - */ - zlib = 2, - bzip2 = 3, - } - - /** - * {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} - */ - enum hash { - md5 = 1, - sha1 = 2, - ripemd = 3, - sha256 = 8, - sha384 = 9, - sha512 = 10, - sha224 = 11, - } - - /** - * A list of hash names as accepted by webCrypto functions. - * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo} - */ - enum webHash { - "SHA-1" = 2, - "SHA-256" = 8, - "SHA-384" = 9, - "SHA-512" = 10, - } - - /** - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6} - */ - enum aead { - eax = 1, - ocb = 2, - experimental_gcm = 100, - } - - /** - * A list of packet types and numeric tags associated with them. - */ - enum packet { - publicKeyEncryptedSessionKey = 1, - signature = 2, - symEncryptedSessionKey = 3, - onePassSignature = 4, - secretKey = 5, - publicKey = 6, - secretSubkey = 7, - compressed = 8, - symmetricallyEncrypted = 9, - marker = 10, - literal = 11, - trust = 12, - userid = 13, - publicSubkey = 14, - userAttribute = 17, - symEncryptedIntegrityProtected = 18, - modificationDetectionCode = 19, - symEncryptedAEADProtected = 20, - } - - /** - * Data types in the literal packet - */ - enum literal { - /** - * Binary data 'b' - */ - binary = "", - /** - * Text data 't' - */ - text = "", - /** - * Utf8 data 'u' - */ - utf8 = "", - /** - * MIME message body part 'm' - */ - mime = "", - } - - /** - * One pass signature packet type - */ - enum signature { - /** - * 0x00: Signature of a binary document. - */ - binary = 0, - /** - * 0x01: Signature of a canonical text document. - * Canonicalyzing the document by converting line endings. - */ - text = 1, - /** - * 0x02: Standalone signature. - * This signature is a signature of only its own subpacket contents. - * It is calculated identically to a signature over a zero-lengh - * binary document. Note that it doesn't make sense to have a V3 - * standalone signature. - */ - standalone = 2, - /** - * 0x10: Generic certification of a User ID and Public-Key packet. - * The issuer of this certification does not make any particular - * assertion as to how well the certifier has checked that the owner - * of the key is in fact the person described by the User ID. - */ - cert_generic = 16, - /** - * 0x11: Persona certification of a User ID and Public-Key packet. - * The issuer of this certification has not done any verification of - * the claim that the owner of this key is the User ID specified. - */ - cert_persona = 17, - /** - * 0x12: Casual certification of a User ID and Public-Key packet. - * The issuer of this certification has done some casual - * verification of the claim of identity. - */ - cert_casual = 18, - /** - * 0x13: Positive certification of a User ID and Public-Key packet. - * The issuer of this certification has done substantial - * verification of the claim of identity. - * Most OpenPGP implementations make their "key signatures" as 0x10 - * certifications. Some implementations can issue 0x11-0x13 - * certifications, but few differentiate between the types. - */ - cert_positive = 19, - /** - * 0x30: Certification revocation signature - * This signature revokes an earlier User ID certification signature - * (signature class 0x10 through 0x13) or direct-key signature - * (0x1F). It should be issued by the same key that issued the - * revoked signature or an authorized revocation key. The signature - * is computed over the same data as the certificate that it - * revokes, and should have a later creation date than that - * certificate. - */ - cert_revocation = 48, - /** - * 0x18: Subkey Binding Signature - * This signature is a statement by the top-level signing key that - * indicates that it owns the subkey. This signature is calculated - * directly on the primary key and subkey, and not on any User ID or - * other packets. A signature that binds a signing subkey MUST have - * an Embedded Signature subpacket in this binding signature that - * contains a 0x19 signature made by the signing subkey on the - * primary key and subkey. - */ - subkey_binding = 24, - /** - * 0x19: Primary Key Binding Signature - * This signature is a statement by a signing subkey, indicating - * that it is owned by the primary key and subkey. This signature - * is calculated the same way as a 0x18 signature: directly on the - * primary key and subkey, and not on any User ID or other packets. - * When a signature is made over a key, the hash data starts with the - * octet 0x99, followed by a two-octet length of the key, and then body - * of the key packet. (Note that this is an old-style packet header for - * a key packet with two-octet length.) A subkey binding signature - * (type 0x18) or primary key binding signature (type 0x19) then hashes - * the subkey using the same format as the main key (also using 0x99 as - * the first octet). - */ - key_binding = 25, - /** - * 0x1F: Signature directly on a key - * This signature is calculated directly on a key. It binds the - * information in the Signature subpackets to the key, and is - * appropriate to be used for subpackets that provide information - * about the key, such as the Revocation Key subpacket. It is also - * appropriate for statements that non-self certifiers want to make - * about the key itself, rather than the binding between a key and a - * name. - */ - key = 31, - /** - * 0x20: Key revocation signature - * The signature is calculated directly on the key being revoked. A - * revoked key is not to be used. Only revocation signatures by the - * key being revoked, or by an authorized revocation key, should be - * considered valid revocation signatures.a - */ - key_revocation = 32, - /** - * 0x28: Subkey revocation signature - * The signature is calculated directly on the subkey being revoked. - * A revoked subkey is not to be used. Only revocation signatures - * by the top-level signature key that is bound to this subkey, or - * by an authorized revocation key, should be considered valid - * revocation signatures. - * Key revocation signatures (types 0x20 and 0x28) - * hash only the key being revoked. - */ - subkey_revocation = 40, - /** - * 0x40: Timestamp signature. - * This signature is only meaningful for the timestamp contained in - * it. - */ - timestamp = 64, - /** - * 0x50: Third-Party Confirmation signature. - * This signature is a signature over some other OpenPGP Signature - * packet(s). It is analogous to a notary seal on the signed data. - * A third-party signature SHOULD include Signature Target - * subpacket(s) to give easy identification. Note that we really do - * mean SHOULD. There are plausible uses for this (such as a blind - * party that only sees the signature, not the key or source - * document) that cannot include a target subpacket. - */ - third_party = 80, - } - - /** - * Signature subpacket type - */ - enum signatureSubpacket { - signature_creation_time = 2, - signature_expiration_time = 3, - exportable_certification = 4, - trust_signature = 5, - regular_expression = 6, - revocable = 7, - key_expiration_time = 9, - placeholder_backwards_compatibility = 10, - preferred_symmetric_algorithms = 11, - revocation_key = 12, - issuer = 16, - notation_data = 20, - preferred_hash_algorithms = 21, - preferred_compression_algorithms = 22, - key_server_preferences = 23, - preferred_key_server = 24, - primary_user_id = 25, - policy_uri = 26, - key_flags = 27, - signers_user_id = 28, - reason_for_revocation = 29, - features = 30, - signature_target = 31, - embedded_signature = 32, - issuer_fingerprint = 33, - preferred_aead_algorithms = 34, - } - - /** - * Key flags - */ - enum keyFlags { - /** - * 0x01 - This key may be used to certify other keys. - */ - certify_keys = 1, - /** - * 0x02 - This key may be used to sign data. - */ - sign_data = 2, - /** - * 0x04 - This key may be used to encrypt communications. - */ - encrypt_communication = 4, - /** - * 0x08 - This key may be used to encrypt storage. - */ - encrypt_storage = 8, - /** - * 0x10 - The private component of this key may have been split - * by a secret-sharing mechanism. - */ - split_private_key = 16, - /** - * 0x20 - This key may be used for authentication. - */ - authentication = 32, - /** - * 0x80 - The private component of this key may be in the - * possession of more than one person. - */ - shared_private_key = 128, - } - - /** - * Key status - */ - enum keyStatus { - invalid = 0, - expired = 1, - revoked = 2, - valid = 3, - no_self_cert = 4, - } - - /** - * Armor type - */ - enum armor { - multipart_section = 0, - multipart_last = 1, - signed = 2, - message = 3, - public_key = 4, - private_key = 5, - signature = 6, - } - - /** - * {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23} - */ - enum reasonForRevocation { - /** - * No reason specified (key revocations or cert revocations) - */ - no_reason = 0, - /** - * Key is superseded (key revocations) - */ - key_superseded = 1, - /** - * Key material has been comPromised (key revocations) - */ - key_comPromised = 2, - /** - * Key is retired and no longer used (key revocations) - */ - key_retired = 3, - /** - * User ID information is no longer valid (cert revocations) - */ - userid_invalid = 32, - } - - /** - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25} - */ - enum features { - /** - * 0x01 - Modification Detection (packets 18 and 19) - */ - modification_detection = 1, - /** - * 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5 - * Symmetric-Key Encrypted Session Key Packets (packet 3) - */ - aead = 2, - /** - * 0x04 - Version 5 Public-Key Packet format and corresponding new - * fingerprint format - */ - v5_keys = 4, - } - - /** - * Asserts validity and converts from string/integer to integer. - */ - function write(): void; - - /** - * Converts from an integer to string. - */ - function read(): void; - } - - namespace hkp { - class HKP { - /** - * Initialize the HKP client and configure it with the key server url and fetch function. - * @param keyServerBaseUrl (optional) The HKP key server base url including - * the protocol to use, e.g. 'https://pgp.mit.edu'; defaults to - * openpgp.config.keyserver (https://keyserver.ubuntu.com) - */ - constructor(keyServerBaseUrl: string); - - /** - * Search for a public key on the key server either by key ID or part of the user ID. - * @param options.keyID The long public key ID. - * @param options.query This can be any part of the key user ID such as name - * or email address. - * @returns The ascii armored public key. - */ - lookup(): Promise; - - /** - * Upload a public key to the server. - * @param publicKeyArmored An ascii armored public key to be uploaded. + * Probabilistic primality testing + * @param n Number to test + * @param e Optional RSA exponent to check against the prime + * @param k Optional number of iterations of Miller-Rabin test * @returns */ - upload(publicKeyArmored: string): Promise; + function isProbablePrime(n: BN, e: BN, k: Integer): boolean; + + /** + * Tests whether n is probably prime or not using Fermat's test with b = 2. + * Fails if b^(n-1) mod n === 1. + * @param n Number to test + * @param b Optional Fermat test base + * @returns + */ + function fermat(n: BN, b: Integer): boolean; + + /** + * Tests whether n is probably prime or not using the Miller-Rabin test. + * See HAC Remark 4.28. + * @param n Number to test + * @param k Optional number of iterations of Miller-Rabin test + * @param rand Optional function to generate potential witnesses + * @returns + */ + function millerRabin(n: BN, k: Integer, rand: Function): boolean; + } + + namespace rsa { + /** + * Create signature + * @param m message + * @param n RSA public modulus + * @param e RSA public exponent + * @param d RSA private exponent + * @returns RSA Signature + */ + function sign(m: BN, n: BN, e: BN, d: BN): BN; + + /** + * Verify signature + * @param s signature + * @param n RSA public modulus + * @param e RSA public exponent + * @returns + */ + function verify(s: BN, n: BN, e: BN): BN; + + /** + * Encrypt message + * @param m message + * @param n RSA public modulus + * @param e RSA public exponent + * @returns RSA Ciphertext + */ + function encrypt(m: BN, n: BN, e: BN): BN; + + /** + * Decrypt RSA message + * @param m message + * @param n RSA public modulus + * @param e RSA public exponent + * @param d RSA private exponent + * @param p RSA private prime p + * @param q RSA private prime q + * @param u RSA private inverse of prime q + * @returns RSA Plaintext + */ + function decrypt(m: BN, n: BN, e: BN, d: BN, p: BN, q: BN, u: BN): BN; + + /** + * Generate a new random private key B bits long with public exponent E. + * When possible, webCrypto is used. Otherwise, primes are generated using + * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. + * @see module:crypto/public_key/prime + * @param B RSA bit length + * @param E RSA public exponent in hex string + * @returns RSA public modulus, RSA public exponent, RSA private exponent, + * RSA private prime p, RSA private prime q, u = q ** -1 mod p + */ + function generate(B: Integer, E: string): object; } } + namespace random { + /** + * Retrieve secure random byte array of the specified length + * @param length Length in bytes to generate + * @returns Random byte array + */ + function getRandomBytes(length: Integer): Uint8Array; + + /** + * Create a secure random MPI that is greater than or equal to min and less than max. + * @param min Lower bound, included + * @param max Upper bound, excluded + * @returns Random MPI + */ + function getRandomBN(min: type.mpi.MPI, max: type.mpi.MPI): BN; + + /** + * Buffer for secure random numbers + */ + function RandomBuffer(): void; + } + + namespace signature { + /** + * Verifies the signature provided for data using specified algorithms and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param algo Public key algorithm + * @param hash_algo Hash algorithm + * @param msg_MPIs Algorithm-specific signature parameters + * @param pub_MPIs Algorithm-specific public key parameters + * @param data Data for which the signature was created + * @param hashed The hashed data + * @returns True if signature is valid + */ + function verify(algo: enums.publicKey, hash_algo: enums.hash, msg_MPIs: type.mpi.MPI[], pub_MPIs: type.mpi.MPI[], data: Uint8Array, hashed: Uint8Array): boolean; + + /** + * Creates a signature on data using specified algorithms and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param algo Public key algorithm + * @param hash_algo Hash algorithm + * @param key_params Algorithm-specific public and private key parameters + * @param data Data to be signed + * @param hashed The hashed data + * @returns Signature + */ + function sign(algo: enums.publicKey, hash_algo: enums.hash, key_params: type.mpi.MPI[], data: Uint8Array, hashed: Uint8Array): Uint8Array; + } +} + +export namespace eme { + /** + * Create a EME-PKCS1-v1_5 padded message + * @see + * @param M message to be encoded + * @param k the length in octets of the key modulus + * @returns EME-PKCS1 padded message + */ + function encode(M: string, k: Integer): Promise; + + /** + * Decode a EME-PKCS1-v1_5 padded message + * @see + * @param EM encoded message, an octet string + * @returns message, an octet string + */ + function decode(EM: string): string; +} + +export namespace emsa { + /** + * Create a EMSA-PKCS1-v1_5 padded message + * @see + * @param algo Hash algorithm type used + * @param hashed message to be encoded + * @param emLen intended length in octets of the encoded message + * @returns encoded message + */ + function encode(algo: Integer, hashed: Uint8Array, emLen: Integer): string; +} + +export namespace encoding { + namespace armor { + /** + * Add additional information to the armor version of an OpenPGP binary + * packet block. + * @author Alex + * @version 2011-12-16 + * @param customComment (optional) additional comment to add to the armored string + * @returns The header information + */ + function addheader(customComment: string): string; + + /** + * Calculates a checksum over the given data and returns it base64 encoded + * @param data Data to create a CRC-24 checksum for + * @returns Base64 encoded checksum + */ + function getCheckSum(data: string | ReadableStream): string | ReadableStream; + + /** + * Internal function to calculate a CRC-24 checksum over a given string (data) + * @param data Data to create a CRC-24 checksum for + * @returns The CRC-24 checksum + */ + function createcrc24(data: string | ReadableStream): Uint8Array | ReadableStream; + + /** + * Splits a message into two parts, the body and the checksum. This is an internal function + * @param text OpenPGP armored message part + * @returns An object with attribute "body" containing the body + * and an attribute "checksum" containing the checksum. + */ + function splitChecksum(text: string): object; + + /** + * DeArmor an OpenPGP armored message; verify the checksum and return + * the encoded bytes + * @param text OpenPGP armored message + * @returns An object with attribute "text" containing the message text, + * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type + */ + function dearmor(text: string): Promise; + + /** + * Armor an OpenPGP binary packet block + * @param messagetype type of the message + * @param body + * @param partindex + * @param parttotal + * @param customComment (optional) additional comment to add to the armored string + * @returns Armored text + */ + function armor(messagetype: Integer, body: any, partindex: Integer, parttotal: Integer, customComment?: string): string | ReadableStream; + } + + namespace base64 { + /** + * Convert binary array to radix-64 + * @param t Uint8Array to convert + * @param u if true, output is URL-safe + * @returns radix-64 version of input string + */ + function s2r(t: Uint8Array | ReadableStream, u?: boolean): string | ReadableStream; + + /** + * Convert radix-64 to binary array + * @param t radix-64 string to convert + * @param u if true, input is interpreted as URL-safe + * @returns binary array version of input string + */ + function r2s(t: string | ReadableStream, u: boolean): Uint8Array | ReadableStream; + } +} + +export namespace enums { + /** + * Maps curve names under various standards to one + * @see + */ + enum curve { + /** + * NIST P-256 Curve + */ + p256 = "p256", + "P-256" = "p256", + secp256r1 = "p256", + prime256v1 = "p256", + "1.2.840.10045.3.1.7" = "p256", + "2a8648ce3d030107" = "p256", + "2A8648CE3D030107" = "p256", + /** + * NIST P-384 Curve + */ + p384 = "p384", + "P-384" = "p384", + secp384r1 = "p384", + "1.3.132.0.34" = "p384", + "2b81040022" = "p384", + "2B81040022" = "p384", + /** + * NIST P-521 Curve + */ + p521 = "p521", + "P-521" = "p521", + secp521r1 = "p521", + "1.3.132.0.35" = "p521", + "2b81040023" = "p521", + "2B81040023" = "p521", + /** + * SECG SECP256k1 Curve + */ + secp256k1 = "secp256k1", + "1.3.132.0.10" = "secp256k1", + "2b8104000a" = "secp256k1", + "2B8104000A" = "secp256k1", + /** + * Ed25519 + */ + ED25519 = "ed25519", + ed25519 = "ed25519", + Ed25519 = "ed25519", + "1.3.6.1.4.1.11591.15.1" = "ed25519", + "2b06010401da470f01" = "ed25519", + "2B06010401DA470F01" = "ed25519", + /** + * Curve25519 + */ + X25519 = "curve25519", + cv25519 = "curve25519", + curve25519 = "curve25519", + Curve25519 = "curve25519", + "1.3.6.1.4.1.3029.1.5.1" = "curve25519", + "2b060104019755010501" = "curve25519", + "2B060104019755010501" = "curve25519", + /** + * BrainpoolP256r1 Curve + */ + brainpoolP256r1 = "brainpoolP256r1", + "1.3.36.3.3.2.8.1.1.7" = "brainpoolP256r1", + "2b2403030208010107" = "brainpoolP256r1", + "2B2403030208010107" = "brainpoolP256r1", + /** + * BrainpoolP384r1 Curve + */ + brainpoolP384r1 = "brainpoolP384r1", + "1.3.36.3.3.2.8.1.1.11" = "brainpoolP384r1", + "2b240303020801010b" = "brainpoolP384r1", + "2B240303020801010B" = "brainpoolP384r1", + /** + * BrainpoolP512r1 Curve + */ + brainpoolP512r1 = "brainpoolP512r1", + "1.3.36.3.3.2.8.1.1.13" = "brainpoolP512r1", + "2b240303020801010d" = "brainpoolP512r1", + "2B240303020801010D" = "brainpoolP512r1", + } + + /** + * A string to key specifier type + */ + enum s2k { + simple = 0, + salted = 1, + iterated = 3, + gnu = 101, + } + + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.1|RFC4880bis-04, section 9.1} + */ + enum publicKey { + /** + * RSA (Encrypt or Sign) [HAC] + */ + rsa_encrypt_sign = 1, + /** + * RSA (Encrypt only) [HAC] + */ + rsa_encrypt = 2, + /** + * RSA (Sign only) [HAC] + */ + rsa_sign = 3, + /** + * Elgamal (Encrypt only) [ELGAMAL] [HAC] + */ + elgamal = 16, + /** + * DSA (Sign only) [FIPS186] [HAC] + */ + dsa = 17, + /** + * ECDH (Encrypt only) [RFC6637] + */ + ecdh = 18, + /** + * ECDSA (Sign only) [RFC6637] + */ + ecdsa = 19, + /** + * EdDSA (Sign only) + * [ {@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] + */ + eddsa = 22, + /** + * Reserved for AEDH + */ + aedh = 23, + /** + * Reserved for AEDSA + */ + aedsa = 24, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} + */ + enum symmetric { + plaintext = 0, + /** + * Not implemented! + */ + idea = 1, + "3des" = 2, + tripledes = 2, + cast5 = 3, + blowfish = 4, + aes128 = 7, + aes192 = 8, + aes256 = 9, + twofish = 10, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} + */ + enum compression { + uncompressed = 0, + /** + * RFC1951 + */ + zip = 1, + /** + * RFC1950 + */ + zlib = 2, + bzip2 = 3, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} + */ + enum hash { + md5 = 1, + sha1 = 2, + ripemd = 3, + sha256 = 8, + sha384 = 9, + sha512 = 10, + sha224 = 11, + } + + /** + * A list of hash names as accepted by webCrypto functions. + * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo} + */ + enum webHash { + "SHA-1" = 2, + "SHA-256" = 8, + "SHA-384" = 9, + "SHA-512" = 10, + } + + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6} + */ + enum aead { + eax = 1, + ocb = 2, + experimental_gcm = 100, + } + + /** + * A list of packet types and numeric tags associated with them. + */ + enum packet { + publicKeyEncryptedSessionKey = 1, + signature = 2, + symEncryptedSessionKey = 3, + onePassSignature = 4, + secretKey = 5, + publicKey = 6, + secretSubkey = 7, + compressed = 8, + symmetricallyEncrypted = 9, + marker = 10, + literal = 11, + trust = 12, + userid = 13, + publicSubkey = 14, + userAttribute = 17, + symEncryptedIntegrityProtected = 18, + modificationDetectionCode = 19, + symEncryptedAEADProtected = 20, + } + + /** + * Data types in the literal packet + */ + enum literal { + /** + * Binary data 'b' + */ + binary = "", + /** + * Text data 't' + */ + text = "", + /** + * Utf8 data 'u' + */ + utf8 = "", + /** + * MIME message body part 'm' + */ + mime = "", + } + + /** + * One pass signature packet type + */ + enum signature { + /** + * 0x00: Signature of a binary document. + */ + binary = 0, + /** + * 0x01: Signature of a canonical text document. + * Canonicalyzing the document by converting line endings. + */ + text = 1, + /** + * 0x02: Standalone signature. + * This signature is a signature of only its own subpacket contents. + * It is calculated identically to a signature over a zero-lengh + * binary document. Note that it doesn't make sense to have a V3 + * standalone signature. + */ + standalone = 2, + /** + * 0x10: Generic certification of a User ID and Public-Key packet. + * The issuer of this certification does not make any particular + * assertion as to how well the certifier has checked that the owner + * of the key is in fact the person described by the User ID. + */ + cert_generic = 16, + /** + * 0x11: Persona certification of a User ID and Public-Key packet. + * The issuer of this certification has not done any verification of + * the claim that the owner of this key is the User ID specified. + */ + cert_persona = 17, + /** + * 0x12: Casual certification of a User ID and Public-Key packet. + * The issuer of this certification has done some casual + * verification of the claim of identity. + */ + cert_casual = 18, + /** + * 0x13: Positive certification of a User ID and Public-Key packet. + * The issuer of this certification has done substantial + * verification of the claim of identity. + * Most OpenPGP implementations make their "key signatures" as 0x10 + * certifications. Some implementations can issue 0x11-0x13 + * certifications, but few differentiate between the types. + */ + cert_positive = 19, + /** + * 0x30: Certification revocation signature + * This signature revokes an earlier User ID certification signature + * (signature class 0x10 through 0x13) or direct-key signature + * (0x1F). It should be issued by the same key that issued the + * revoked signature or an authorized revocation key. The signature + * is computed over the same data as the certificate that it + * revokes, and should have a later creation date than that + * certificate. + */ + cert_revocation = 48, + /** + * 0x18: Subkey Binding Signature + * This signature is a statement by the top-level signing key that + * indicates that it owns the subkey. This signature is calculated + * directly on the primary key and subkey, and not on any User ID or + * other packets. A signature that binds a signing subkey MUST have + * an Embedded Signature subpacket in this binding signature that + * contains a 0x19 signature made by the signing subkey on the + * primary key and subkey. + */ + subkey_binding = 24, + /** + * 0x19: Primary Key Binding Signature + * This signature is a statement by a signing subkey, indicating + * that it is owned by the primary key and subkey. This signature + * is calculated the same way as a 0x18 signature: directly on the + * primary key and subkey, and not on any User ID or other packets. + * When a signature is made over a key, the hash data starts with the + * octet 0x99, followed by a two-octet length of the key, and then body + * of the key packet. (Note that this is an old-style packet header for + * a key packet with two-octet length.) A subkey binding signature + * (type 0x18) or primary key binding signature (type 0x19) then hashes + * the subkey using the same format as the main key (also using 0x99 as + * the first octet). + */ + key_binding = 25, + /** + * 0x1F: Signature directly on a key + * This signature is calculated directly on a key. It binds the + * information in the Signature subpackets to the key, and is + * appropriate to be used for subpackets that provide information + * about the key, such as the Revocation Key subpacket. It is also + * appropriate for statements that non-self certifiers want to make + * about the key itself, rather than the binding between a key and a + * name. + */ + key = 31, + /** + * 0x20: Key revocation signature + * The signature is calculated directly on the key being revoked. A + * revoked key is not to be used. Only revocation signatures by the + * key being revoked, or by an authorized revocation key, should be + * considered valid revocation signatures.a + */ + key_revocation = 32, + /** + * 0x28: Subkey revocation signature + * The signature is calculated directly on the subkey being revoked. + * A revoked subkey is not to be used. Only revocation signatures + * by the top-level signature key that is bound to this subkey, or + * by an authorized revocation key, should be considered valid + * revocation signatures. + * Key revocation signatures (types 0x20 and 0x28) + * hash only the key being revoked. + */ + subkey_revocation = 40, + /** + * 0x40: Timestamp signature. + * This signature is only meaningful for the timestamp contained in + * it. + */ + timestamp = 64, + /** + * 0x50: Third-Party Confirmation signature. + * This signature is a signature over some other OpenPGP Signature + * packet(s). It is analogous to a notary seal on the signed data. + * A third-party signature SHOULD include Signature Target + * subpacket(s) to give easy identification. Note that we really do + * mean SHOULD. There are plausible uses for this (such as a blind + * party that only sees the signature, not the key or source + * document) that cannot include a target subpacket. + */ + third_party = 80, + } + + /** + * Signature subpacket type + */ + enum signatureSubpacket { + signature_creation_time = 2, + signature_expiration_time = 3, + exportable_certification = 4, + trust_signature = 5, + regular_expression = 6, + revocable = 7, + key_expiration_time = 9, + placeholder_backwards_compatibility = 10, + preferred_symmetric_algorithms = 11, + revocation_key = 12, + issuer = 16, + notation_data = 20, + preferred_hash_algorithms = 21, + preferred_compression_algorithms = 22, + key_server_preferences = 23, + preferred_key_server = 24, + primary_user_id = 25, + policy_uri = 26, + key_flags = 27, + signers_user_id = 28, + reason_for_revocation = 29, + features = 30, + signature_target = 31, + embedded_signature = 32, + issuer_fingerprint = 33, + preferred_aead_algorithms = 34, + } + + /** + * Key flags + */ + enum keyFlags { + /** + * 0x01 - This key may be used to certify other keys. + */ + certify_keys = 1, + /** + * 0x02 - This key may be used to sign data. + */ + sign_data = 2, + /** + * 0x04 - This key may be used to encrypt communications. + */ + encrypt_communication = 4, + /** + * 0x08 - This key may be used to encrypt storage. + */ + encrypt_storage = 8, + /** + * 0x10 - The private component of this key may have been split + * by a secret-sharing mechanism. + */ + split_private_key = 16, + /** + * 0x20 - This key may be used for authentication. + */ + authentication = 32, + /** + * 0x80 - The private component of this key may be in the + * possession of more than one person. + */ + shared_private_key = 128, + } + + /** + * Key status + */ + enum keyStatus { + invalid = 0, + expired = 1, + revoked = 2, + valid = 3, + no_self_cert = 4, + } + + /** + * Armor type + */ + enum armor { + multipart_section = 0, + multipart_last = 1, + signed = 2, + message = 3, + public_key = 4, + private_key = 5, + signature = 6, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23} + */ + enum reasonForRevocation { + /** + * No reason specified (key revocations or cert revocations) + */ + no_reason = 0, + /** + * Key is superseded (key revocations) + */ + key_superseded = 1, + /** + * Key material has been comPromised (key revocations) + */ + key_comPromised = 2, + /** + * Key is retired and no longer used (key revocations) + */ + key_retired = 3, + /** + * User ID information is no longer valid (cert revocations) + */ + userid_invalid = 32, + } + + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25} + */ + enum features { + /** + * 0x01 - Modification Detection (packets 18 and 19) + */ + modification_detection = 1, + /** + * 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5 + * Symmetric-Key Encrypted Session Key Packets (packet 3) + */ + aead = 2, + /** + * 0x04 - Version 5 Public-Key Packet format and corresponding new + * fingerprint format + */ + v5_keys = 4, + } + + /** + * Asserts validity and converts from string/integer to integer. + */ + function write(): void; + + /** + * Converts from an integer to string. + */ + function read(): void; +} + +export namespace hkp { class HKP { /** * Initialize the HKP client and configure it with the key server url and fetch function. @@ -1624,557 +1595,301 @@ export namespace openpgp { */ upload(publicKeyArmored: string): Promise; } +} - namespace key { +export class HKP { + /** + * Initialize the HKP client and configure it with the key server url and fetch function. + * @param keyServerBaseUrl (optional) The HKP key server base url including + * the protocol to use, e.g. 'https://pgp.mit.edu'; defaults to + * openpgp.config.keyserver (https://keyserver.ubuntu.com) + */ + constructor(keyServerBaseUrl: string); + + /** + * Search for a public key on the key server either by key ID or part of the user ID. + * @param options.keyID The long public key ID. + * @param options.query This can be any part of the key user ID such as name + * or email address. + * @returns The ascii armored public key. + */ + lookup(): Promise; + + /** + * Upload a public key to the server. + * @param publicKeyArmored An ascii armored public key to be uploaded. + * @returns + */ + upload(publicKeyArmored: string): Promise; +} + +export namespace key { + /** + * Class that represents an OpenPGP key. Must contain a primary key. + * Can contain additional subkeys, signatures, user ids, user attributes. + */ + class Key { /** - * Class that represents an OpenPGP key. Must contain a primary key. - * Can contain additional subkeys, signatures, user ids, user attributes. + * @param packetlist The packets that form this key */ - class Key { - /** - * @param packetlist The packets that form this key - */ - constructor(packetlist: packet.List); - - /** - * Transforms packetlist to structured key data - * @param packetlist The packets that form a key - */ - packetlist2structure(packetlist: packet.List): void; - - /** - * Transforms structured key data to packetlist - * @returns The packets that form a key - */ - toPacketlist(): packet.List; - - /** - * Returns an array containing all public or private subkeys matching keyId; - * If keyId is not present, returns all subkeys. - * @param keyId - * @returns - */ - getSubkeys(keyId: type.keyid.Keyid): any[]; - - /** - * Returns an array containing all public or private keys matching keyId. - * If keyId is not present, returns all keys starting with the primary key. - * @param keyId - * @returns - */ - getKeys(keyId: type.keyid.Keyid): any[]; - - /** - * Returns key IDs of all keys - * @returns - */ - getKeyIds(): any[]; - - /** - * Returns userids - * @returns array of userids - */ - getUserIds(): any[]; - - /** - * Returns true if this is a public key - * @returns - */ - isPublic(): boolean; - - /** - * Returns true if this is a private key - * @returns - */ - isPrivate(): boolean; - - /** - * Returns key as public key (shallow copy) - * @returns new public Key - */ - toPublic(): Key; - - /** - * Returns ASCII armored text of key - * @returns ASCII armor - */ - armor(): ReadableStream; - - /** - * Returns last created key or key by given keyId that is available for signing and verification - * @param keyId, optional - * @param date (optional) use the given date for verification instead of the current time - * @param userId, optional user ID - * @returns key or null if no signing key has been found - */ - getSigningKey(keyId: type.keyid.Keyid, date?: Date, userId?: object): Promise; - - /** - * Returns last created key or key by given keyId that is available for encryption or decryption - * @param keyId, optional - * @param date, optional - * @param userId, optional - * @returns key or null if no encryption key has been found - */ - getEncryptionKey(keyId?: type.keyid.Keyid, date?: Date, userId?: string): Promise; - - /** - * Encrypts all secret key and subkey packets matching keyId - * @param passphrases - if multiple passphrases, then should be in same order as packets each should encrypt - * @param keyId - * @returns - */ - encrypt(passphrases: string | any[], keyId?: type.keyid.Keyid): Promise>; - - /** - * Decrypts all secret key and subkey packets matching keyId - * @param passphrases - * @param keyId - * @returns true if all matching key and subkey packets decrypted successfully - */ - decrypt(passphrases: string | string[], keyId?: type.keyid.Keyid): Promise; - - /** - * Checks if a signature on a key is revoked - * @param - * @param signature The signature to verify - * @param key, optional The key to verify the signature - * @param date Use the given date instead of the current time - * @returns True if the certificate is revoked - */ - isRevoked(signature: packet.Signature, key?: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date?: Date): Promise; - - /** - * Verify primary key. Checks for revocation signatures, expiration time - * and valid self signature - * @param date (optional) use the given date for verification instead of the current time - * @param userId (optional) user ID - * @returns The status of the primary key - */ - verifyPrimaryKey(date?: Date, userId?: object): Promise; - - /** - * Returns the latest date when the key can be used for encrypting, signing, or both, depending on the `capabilities` paramater. - * When `capabilities` is null, defaults to returning the expiry date of the primary key. - * Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid. - * Returns Infinity if the key doesn't expire. - * @param {encrypt | sign | encrypt_sign} capabilities, optional - * @param keyId, optional - * @param userId, optional user ID - * @returns - */ - getExpirationTime(capabilities: any, keyId: type.keyid.Keyid, userId: object): Promise; - - /** - * Returns primary user and most significant (latest valid) self signature - * - if multiple primary users exist, returns the one with the latest self signature - * - otherwise, returns the user with the latest self signature - * @param date (optional) use the given date for verification instead of the current time - * @param userId (optional) user ID to get instead of the primary user, if it exists - * @returns The primary user and the self signature - */ - getPrimaryUser(date: Date, userId: object): Promise<{ user: User, selfCertification: packet.Signature }>; - - /** - * Update key with new components from specified key with same key ID: - * users, subkeys, certificates are merged into the destination key, - * duplicates and expired signatures are ignored. - * If the specified key is a private key and the destination key is public, - * the destination key is transformed to a private key. - * @param key Source key to merge - * @returns - */ - update(key: Key): Promise; - - /** - * Revokes the key - * @param reasonForRevocation optional, object indicating the reason for revocation - * @param reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param reasonForRevocation.string optional, string explaining the reason for revocation - * @param date optional, override the creationtime of the revocation signature - * @returns new key with revocation signature - */ - revoke(reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; - - /** - * Get revocation certificate from a revoked key. - * (To get a revocation certificate for an unrevoked key, call revoke() first.) - * @returns armored revocation certificate - */ - getRevocationCertificate(): Promise; - - /** - * Applies a revocation certificate to a key - * This adds the first signature packet in the armored text to the key, - * if it is a valid revocation signature. - * @param revocationCertificate armored revocation certificate - * @returns new revoked key - */ - applyRevocationCertificate(revocationCertificate: string): Promise; - - /** - * Signs primary user of key - * @param privateKey decrypted private keys for signing - * @param date (optional) use the given date for verification instead of the current time - * @param userId (optional) user ID to get instead of the primary user, if it exists - * @returns new public key with new certificate signature - */ - signPrimaryUser(privateKey: any[], date: Date, userId: object): Promise; - - /** - * Signs all users of key - * @param privateKeys decrypted private keys for signing - * @returns new public key with new certificate signature - */ - signAllUsers(privateKeys: any[]): Promise; - - /** - * Verifies primary user of key - * - if no arguments are given, verifies the self certificates; - * - otherwise, verifies all certificates signed with given keys. - * @param keys array of keys to verify certificate signatures - * @param date (optional) use the given date for verification instead of the current time - * @param userId (optional) user ID to get instead of the primary user, if it exists - * @returns List of signer's keyid and validity of signature - */ - verifyPrimaryUser(keys: any[], date: Date, userId: object): Promise>; - - /** - * Verifies all users of key - * - if no arguments are given, verifies the self certificates; - * - otherwise, verifies all certificates signed with given keys. - * @param keys array of keys to verify certificate signatures - * @returns list of userid, signer's keyid and validity of signature - */ - verifyAllUsers(keys: any[]): Promise>; - - /** - * Calculates the key id of the key - * @returns A 8 byte key id - */ - getKeyId(): string; - - /** - * Calculates the fingerprint of the key - * @returns A string containing the fingerprint in lowercase hex - */ - getFingerprint(): string; - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns Whether the two keys have the same version and public key data - */ - hasSameFingerprintAs(): boolean; - - /** - * Returns algorithm information - * @returns An object of the form {algorithm: string, bits:int, curve:String} - */ - getAlgorithmInfo(): object; - - /** - * Returns the creation time of the key - * @returns - */ - getCreationTime(): Date; - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns - */ - isDecrypted(): boolean | null; - } + constructor(packetlist: packet.List); /** - * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. - * @param signatures List of signatures - * @param date Use the given date instead of the current time - * @returns The latest valid signature + * Transforms packetlist to structured key data + * @param packetlist The packets that form a key */ - function getLatestValidSignature(signatures: any[], date: Date): Promise; + packetlist2structure(packetlist: packet.List): void; /** - * Class that represents an user ID or attribute packet and the relevant signatures. + * Transforms structured key data to packetlist + * @returns The packets that form a key */ - class User { - constructor(); - - /** - * Transforms structured user data to packetlist - * @returns - */ - toPacketlist(): packet.List; - - /** - * Signs user - * @param primaryKey The primary key packet - * @param privateKeys Decrypted private keys for signing - * @returns New user with new certificate signatures - */ - sign(primaryKey: packet.SecretKey | packet.PublicKey, privateKeys: any[]): Promise; - - /** - * Checks if a given certificate of the user is revoked - * @param primaryKey The primary key packet - * @param certificate The certificate to verify - * @param key, optional The key to verify the signature - * @param date Use the given date instead of the current time - * @returns True if the certificate is revoked - */ - isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; - - /** - * Verifies the user certificate - * @param primaryKey The primary key packet - * @param certificate A certificate of this user - * @param keys Array of keys to verify certificate signatures - * @param date Use the given date instead of the current time - * @returns status of the certificate - */ - verifyCertificate(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, keys: any[], date: Date): Promise; - - /** - * Verifies all user certificates - * @param primaryKey The primary key packet - * @param keys Array of keys to verify certificate signatures - * @param date Use the given date instead of the current time - * @returns List of signer's keyid and validity of signature - */ - verifyAllCertifications(primaryKey: packet.SecretKey | packet.PublicKey, keys: any[], date: Date): Promise>; - - /** - * Verify User. Checks for existence of self signatures, revocation signatures - * and validity of self signature - * @param primaryKey The primary key packet - * @param date Use the given date instead of the current time - * @returns Status of user - */ - verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; - - /** - * Update user with new components from specified user - * @param user Source user to merge - * @param primaryKey primary key used for validation - * @returns - */ - update(user: User, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; - } + toPacketlist(): packet.List; /** - * Create signature packet - * @param dataToSign Contains packets to be signed - * @param signingKeyPacket secret key packet for signing - * @param signatureProperties (optional) properties to write on the signature packet before signing - * @param date (optional) override the creationtime of the signature - * @param userId (optional) user ID - * @returns signature packet - */ - function createSignaturePacket(dataToSign: object, signingKeyPacket: packet.SecretKey | packet.SecretSubkey, signatureProperties: object, date: Date, userId: object): packet.Signature; - - /** - * Class that represents a subkey packet and the relevant signatures. - */ - class SubKey { - constructor(); - - /** - * Transforms structured subkey data to packetlist - * @returns - */ - toPacketlist(): packet.List; - - /** - * Checks if a binding signature of a subkey is revoked - * @param primaryKey The primary key packet - * @param signature The binding signature to verify - * @param key, optional The key to verify the signature - * @param date Use the given date instead of the current time - * @returns True if the binding signature is revoked - */ - isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; - - /** - * Verify subkey. Checks for revocation signatures, expiration time - * and valid binding signature - * @param primaryKey The primary key packet - * @param date Use the given date instead of the current time - * @returns The status of the subkey - */ - verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; - - /** - * Returns the expiration time of the subkey or Infinity if key does not expire - * Returns null if the subkey is invalid. - * @param primaryKey The primary key packet - * @param date Use the given date instead of the current time - * @returns - */ - getExpirationTime(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; - - /** - * Update subkey with new components from specified subkey - * @param subKey Source subkey to merge - * @param primaryKey primary key used for validation - * @returns - */ - update(subKey: SubKey, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; - - /** - * Revokes the subkey - * @param primaryKey decrypted private primary key for revocation - * @param reasonForRevocation optional, object indicating the reason for revocation - * @param reasonForRevocation.flag optional, flag indicating the reason for revocation - * @param reasonForRevocation.string optional, string explaining the reason for revocation - * @param date optional, override the creationtime of the revocation signature - * @returns new subkey with revocation signature - */ - revoke(primaryKey: packet.SecretKey, reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; - - /** - * Calculates the key id of the key - * @returns A 8 byte key id - */ - getKeyId(): string; - - /** - * Calculates the fingerprint of the key - * @returns A string containing the fingerprint in lowercase hex - */ - getFingerprint(): string; - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns Whether the two keys have the same version and public key data - */ - hasSameFingerprintAs(): boolean; - - /** - * Returns algorithm information - * @returns An object of the form {algorithm: string, bits:int, curve:String} - */ - getAlgorithmInfo(): object; - - /** - * Returns the creation time of the key - * @returns - */ - getCreationTime(): Date; - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns - */ - isDecrypted(): boolean | null; - } - - /** - * Reads an unarmored OpenPGP key list and returns one or multiple key objects - * @param data to be parsed - * @returns result object with key and error arrays - */ - function read(data: Uint8Array): Promise<{ keys: Array, err: Array | null }>; - - interface KeyResult { keys: Array, err: Array | null } - - /** - * Reads an OpenPGP armored text and returns one or multiple key objects - * @param armoredText text to be parsed - * @returns result object with key and error arrays - */ - function readArmored(armoredText: string | ReadableStream): Promise; - - /** - * Generates a new OpenPGP key. Supports RSA and ECC keys. - * Primary and subkey will be of same type. - * @param options.keyType To indicate what type of key to make. - * RSA is 1. See {@link https://tools.ietf.org/html/rfc4880#section-9.1} - * @param options.numBits number of bits for the key creation. - * @param options.userIds Assumes already in form of "User Name " - * If array is used, the first userId is set as primary user Id - * @param options.passphrase The passphrase used to encrypt the resulting private key - * @param options.keyExpirationTime The number of seconds after the key creation time that the key expires - * @param curve (optional) elliptic curve for ECC keys - * @param date Override the creation date of the key and the key signatures - * @param subkeys (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] - * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + * Returns an array containing all public or private subkeys matching keyId; + * If keyId is not present, returns all subkeys. + * @param keyId * @returns */ - function generate(options: KeyOptions): Promise; + getSubkeys(keyId: type.keyid.Keyid): any[]; /** - * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. - * @param options.privateKey The private key to reformat - * @param options.keyType - * @param options.userIds Assumes already in form of "User Name " - * If array is used, the first userId is set as primary user Id - * @param options.passphrase The passphrase used to encrypt the resulting private key - * @param options.keyExpirationTime The number of seconds after the key creation time that the key expires - * @param date Override the creation date of the key and the key signatures - * @param subkeys (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * Returns an array containing all public or private keys matching keyId. + * If keyId is not present, returns all keys starting with the primary key. + * @param keyId * @returns */ - function reformat(date: Date, subkeys: any[]): Promise; + getKeys(keyId: type.keyid.Keyid): any[]; /** - * Checks if a given certificate or binding signature is revoked - * @param primaryKey The primary key packet - * @param dataToVerify The data to check - * @param revocations The revocation signatures to check - * @param signature The certificate or signature to check - * @param key, optional The key packet to check the signature + * Returns key IDs of all keys + * @returns + */ + getKeyIds(): any[]; + + /** + * Returns userids + * @returns array of userids + */ + getUserIds(): any[]; + + /** + * Returns true if this is a public key + * @returns + */ + isPublic(): boolean; + + /** + * Returns true if this is a private key + * @returns + */ + isPrivate(): boolean; + + /** + * Returns key as public key (shallow copy) + * @returns new public Key + */ + toPublic(): Key; + + /** + * Returns ASCII armored text of key + * @returns ASCII armor + */ + armor(): ReadableStream; + + /** + * Returns last created key or key by given keyId that is available for signing and verification + * @param keyId, optional + * @param date (optional) use the given date for verification instead of the current time + * @param userId, optional user ID + * @returns key or null if no signing key has been found + */ + getSigningKey(keyId: type.keyid.Keyid, date?: Date, userId?: object): Promise; + + /** + * Returns last created key or key by given keyId that is available for encryption or decryption + * @param keyId, optional + * @param date, optional + * @param userId, optional + * @returns key or null if no encryption key has been found + */ + getEncryptionKey(keyId?: type.keyid.Keyid, date?: Date, userId?: string): Promise; + + /** + * Encrypts all secret key and subkey packets matching keyId + * @param passphrases - if multiple passphrases, then should be in same order as packets each should encrypt + * @param keyId + * @returns + */ + encrypt(passphrases: string | any[], keyId?: type.keyid.Keyid): Promise>; + + /** + * Decrypts all secret key and subkey packets matching keyId + * @param passphrases + * @param keyId + * @returns true if all matching key and subkey packets decrypted successfully + */ + decrypt(passphrases: string | string[], keyId?: type.keyid.Keyid): Promise; + + /** + * Checks if a signature on a key is revoked + * @param + * @param signature The signature to verify + * @param key, optional The key to verify the signature * @param date Use the given date instead of the current time - * @returns True if the signature revokes the data + * @returns True if the certificate is revoked */ - function isDataRevoked(primaryKey: packet.SecretKey | packet.PublicKey, dataToVerify: object, revocations: any[], signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + isRevoked(signature: packet.Signature, key?: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date?: Date): Promise; /** - * Check if signature has revocation key sub packet (not supported by OpenPGP.js) - * and throw error if found - * @param signature The certificate or signature to check - * @param keyId Check only certificates or signatures from a certain issuer key ID - */ - function checkRevocationKey(signature: packet.Signature, keyId: type.keyid.Keyid): void; - - /** - * Returns the preferred signature hash algorithm of a key - * @param key (optional) the key to get preferences from - * @param keyPacket key packet used for signing + * Verify primary key. Checks for revocation signatures, expiration time + * and valid self signature * @param date (optional) use the given date for verification instead of the current time * @param userId (optional) user ID + * @returns The status of the primary key + */ + verifyPrimaryKey(date?: Date, userId?: object): Promise; + + /** + * Returns the latest date when the key can be used for encrypting, signing, or both, depending on the `capabilities` paramater. + * When `capabilities` is null, defaults to returning the expiry date of the primary key. + * Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid. + * Returns Infinity if the key doesn't expire. + * @param {encrypt | sign | encrypt_sign} capabilities, optional + * @param keyId, optional + * @param userId, optional user ID * @returns */ - function getPreferredHashAlgo(key: Key, keyPacket: packet.SecretKey | packet.SecretSubkey, date: Date, userId: object): Promise; + getExpirationTime(capabilities: any, keyId: type.keyid.Keyid, userId: object): Promise; /** - * Returns the preferred symmetric/aead algorithm for a set of keys - * @param {symmetric | aead} type Type of preference to return - * @param keys Set of keys + * Returns primary user and most significant (latest valid) self signature + * - if multiple primary users exist, returns the one with the latest self signature + * - otherwise, returns the user with the latest self signature * @param date (optional) use the given date for verification instead of the current time - * @param userIds (optional) user IDs - * @returns Preferred symmetric algorithm + * @param userId (optional) user ID to get instead of the primary user, if it exists + * @returns The primary user and the self signature */ - function getPreferredAlgo(type: any, keys: any[], date: Date, userIds: any[]): Promise; + getPrimaryUser(date: Date, userId: object): Promise<{ user: User, selfCertification: packet.Signature }>; /** - * Returns whether aead is supported by all keys in the set - * @param keys Set of keys - * @param date (optional) use the given date for verification instead of the current time - * @param userIds (optional) user IDs + * Update key with new components from specified key with same key ID: + * users, subkeys, certificates are merged into the destination key, + * duplicates and expired signatures are ignored. + * If the specified key is a private key and the destination key is public, + * the destination key is transformed to a private key. + * @param key Source key to merge * @returns */ - function isAeadSupported(keys: any[], date: Date, userIds: any[]): Promise; + update(key: Key): Promise; + + /** + * Revokes the key + * @param reasonForRevocation optional, object indicating the reason for revocation + * @param reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param reasonForRevocation.string optional, string explaining the reason for revocation + * @param date optional, override the creationtime of the revocation signature + * @returns new key with revocation signature + */ + revoke(reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; + + /** + * Get revocation certificate from a revoked key. + * (To get a revocation certificate for an unrevoked key, call revoke() first.) + * @returns armored revocation certificate + */ + getRevocationCertificate(): Promise; + + /** + * Applies a revocation certificate to a key + * This adds the first signature packet in the armored text to the key, + * if it is a valid revocation signature. + * @param revocationCertificate armored revocation certificate + * @returns new revoked key + */ + applyRevocationCertificate(revocationCertificate: string): Promise; + + /** + * Signs primary user of key + * @param privateKey decrypted private keys for signing + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID to get instead of the primary user, if it exists + * @returns new public key with new certificate signature + */ + signPrimaryUser(privateKey: any[], date: Date, userId: object): Promise; + + /** + * Signs all users of key + * @param privateKeys decrypted private keys for signing + * @returns new public key with new certificate signature + */ + signAllUsers(privateKeys: any[]): Promise; + + /** + * Verifies primary user of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param keys array of keys to verify certificate signatures + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID to get instead of the primary user, if it exists + * @returns List of signer's keyid and validity of signature + */ + verifyPrimaryUser(keys: any[], date: Date, userId: object): Promise>; + + /** + * Verifies all users of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param keys array of keys to verify certificate signatures + * @returns list of userid, signer's keyid and validity of signature + */ + verifyAllUsers(keys: any[]): Promise>; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; } - interface revoke_reasonForRevocation { - /** - * optional, flag indicating the reason for revocation - */ - flag: enums.reasonForRevocation; - /** - * optional, string explaining the reason for revocation - */ - string: string; - } + /** + * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. + * @param signatures List of signatures + * @param date Use the given date instead of the current time + * @returns The latest valid signature + */ + function getLatestValidSignature(signatures: any[], date: Date): Promise; /** * Class that represents an user ID or attribute packet and the relevant signatures. @@ -2194,7 +1909,7 @@ export namespace openpgp { * @param privateKeys Decrypted private keys for signing * @returns New user with new certificate signatures */ - sign(primaryKey: packet.SecretKey | packet.PublicKey, privateKeys: any[]): Promise; + sign(primaryKey: packet.SecretKey | packet.PublicKey, privateKeys: any[]): Promise; /** * Checks if a given certificate of the user is revoked @@ -2240,9 +1955,20 @@ export namespace openpgp { * @param primaryKey primary key used for validation * @returns */ - update(user: key.User, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + update(user: User, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; } + /** + * Create signature packet + * @param dataToSign Contains packets to be signed + * @param signingKeyPacket secret key packet for signing + * @param signatureProperties (optional) properties to write on the signature packet before signing + * @param date (optional) override the creationtime of the signature + * @param userId (optional) user ID + * @returns signature packet + */ + function createSignaturePacket(dataToSign: object, signingKeyPacket: packet.SecretKey | packet.SecretSubkey, signatureProperties: object, date: Date, userId: object): packet.Signature; + /** * Class that represents a subkey packet and the relevant signatures. */ @@ -2289,7 +2015,7 @@ export namespace openpgp { * @param primaryKey primary key used for validation * @returns */ - update(subKey: key.SubKey, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + update(subKey: SubKey, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; /** * Revokes the subkey @@ -2300,7 +2026,7 @@ export namespace openpgp { * @param date optional, override the creationtime of the revocation signature * @returns new subkey with revocation signature */ - revoke(primaryKey: packet.SecretKey, reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; + revoke(primaryKey: packet.SecretKey, reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; /** * Calculates the key id of the key @@ -2340,2895 +2066,3168 @@ export namespace openpgp { } /** - * @see module:keyring/keyring - * @see module:keyring/localstore + * Reads an unarmored OpenPGP key list and returns one or multiple key objects + * @param data to be parsed + * @returns result object with key and error arrays */ + function read(data: Uint8Array): Promise<{ keys: Array, err: Array | null }>; + + interface KeyResult { keys: Array, err: Array | null } + + /** + * Reads an OpenPGP armored text and returns one or multiple key objects + * @param armoredText text to be parsed + * @returns result object with key and error arrays + */ + function readArmored(armoredText: string | ReadableStream): Promise; + + /** + * Generates a new OpenPGP key. Supports RSA and ECC keys. + * Primary and subkey will be of same type. + * @param options.keyType To indicate what type of key to make. + * RSA is 1. See {@link https://tools.ietf.org/html/rfc4880#section-9.1} + * @param options.numBits number of bits for the key creation. + * @param options.userIds Assumes already in form of "User Name " + * If array is used, the first userId is set as primary user Id + * @param options.passphrase The passphrase used to encrypt the resulting private key + * @param options.keyExpirationTime The number of seconds after the key creation time that the key expires + * @param curve (optional) elliptic curve for ECC keys + * @param date Override the creation date of the key and the key signatures + * @param subkeys (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + * @returns + */ + function generate(options: KeyOptions): Promise; + + /** + * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. + * @param options.privateKey The private key to reformat + * @param options.keyType + * @param options.userIds Assumes already in form of "User Name " + * If array is used, the first userId is set as primary user Id + * @param options.passphrase The passphrase used to encrypt the resulting private key + * @param options.keyExpirationTime The number of seconds after the key creation time that the key expires + * @param date Override the creation date of the key and the key signatures + * @param subkeys (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * @returns + */ + function reformat(date: Date, subkeys: any[]): Promise; + + /** + * Checks if a given certificate or binding signature is revoked + * @param primaryKey The primary key packet + * @param dataToVerify The data to check + * @param revocations The revocation signatures to check + * @param signature The certificate or signature to check + * @param key, optional The key packet to check the signature + * @param date Use the given date instead of the current time + * @returns True if the signature revokes the data + */ + function isDataRevoked(primaryKey: packet.SecretKey | packet.PublicKey, dataToVerify: object, revocations: any[], signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Check if signature has revocation key sub packet (not supported by OpenPGP.js) + * and throw error if found + * @param signature The certificate or signature to check + * @param keyId Check only certificates or signatures from a certain issuer key ID + */ + function checkRevocationKey(signature: packet.Signature, keyId: type.keyid.Keyid): void; + + /** + * Returns the preferred signature hash algorithm of a key + * @param key (optional) the key to get preferences from + * @param keyPacket key packet used for signing + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID + * @returns + */ + function getPreferredHashAlgo(key: Key, keyPacket: packet.SecretKey | packet.SecretSubkey, date: Date, userId: object): Promise; + + /** + * Returns the preferred symmetric/aead algorithm for a set of keys + * @param {symmetric | aead} type Type of preference to return + * @param keys Set of keys + * @param date (optional) use the given date for verification instead of the current time + * @param userIds (optional) user IDs + * @returns Preferred symmetric algorithm + */ + function getPreferredAlgo(type: any, keys: any[], date: Date, userIds: any[]): Promise; + + /** + * Returns whether aead is supported by all keys in the set + * @param keys Set of keys + * @param date (optional) use the given date for verification instead of the current time + * @param userIds (optional) user IDs + * @returns + */ + function isAeadSupported(keys: any[], date: Date, userIds: any[]): Promise; +} + +export interface revoke_reasonForRevocation { + /** + * optional, flag indicating the reason for revocation + */ + flag: enums.reasonForRevocation; + /** + * optional, string explaining the reason for revocation + */ + string: string; +} + +/** + * Class that represents an user ID or attribute packet and the relevant signatures. + */ +export class User { + constructor(); + + /** + * Transforms structured user data to packetlist + * @returns + */ + toPacketlist(): packet.List; + + /** + * Signs user + * @param primaryKey The primary key packet + * @param privateKeys Decrypted private keys for signing + * @returns New user with new certificate signatures + */ + sign(primaryKey: packet.SecretKey | packet.PublicKey, privateKeys: any[]): Promise; + + /** + * Checks if a given certificate of the user is revoked + * @param primaryKey The primary key packet + * @param certificate The certificate to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the certificate is revoked + */ + isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Verifies the user certificate + * @param primaryKey The primary key packet + * @param certificate A certificate of this user + * @param keys Array of keys to verify certificate signatures + * @param date Use the given date instead of the current time + * @returns status of the certificate + */ + verifyCertificate(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, keys: any[], date: Date): Promise; + + /** + * Verifies all user certificates + * @param primaryKey The primary key packet + * @param keys Array of keys to verify certificate signatures + * @param date Use the given date instead of the current time + * @returns List of signer's keyid and validity of signature + */ + verifyAllCertifications(primaryKey: packet.SecretKey | packet.PublicKey, keys: any[], date: Date): Promise>; + + /** + * Verify User. Checks for existence of self signatures, revocation signatures + * and validity of self signature + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns Status of user + */ + verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Update user with new components from specified user + * @param user Source user to merge + * @param primaryKey primary key used for validation + * @returns + */ + update(user: key.User, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; +} + +/** + * Class that represents a subkey packet and the relevant signatures. + */ +export class SubKey { + constructor(); + + /** + * Transforms structured subkey data to packetlist + * @returns + */ + toPacketlist(): packet.List; + + /** + * Checks if a binding signature of a subkey is revoked + * @param primaryKey The primary key packet + * @param signature The binding signature to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the binding signature is revoked + */ + isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Verify subkey. Checks for revocation signatures, expiration time + * and valid binding signature + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns The status of the subkey + */ + verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Returns the expiration time of the subkey or Infinity if key does not expire + * Returns null if the subkey is invalid. + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns + */ + getExpirationTime(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Update subkey with new components from specified subkey + * @param subKey Source subkey to merge + * @param primaryKey primary key used for validation + * @returns + */ + update(subKey: key.SubKey, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + + /** + * Revokes the subkey + * @param primaryKey decrypted private primary key for revocation + * @param reasonForRevocation optional, object indicating the reason for revocation + * @param reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param reasonForRevocation.string optional, string explaining the reason for revocation + * @param date optional, override the creationtime of the revocation signature + * @returns new subkey with revocation signature + */ + revoke(primaryKey: packet.SecretKey, reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; +} + +/** + * @see module:keyring/keyring + * @see module:keyring/localstore + */ +export namespace keyring { namespace keyring { - namespace keyring { - class Keyring { - /** - * Initialization routine for the keyring. - * @param storeHandler class implementing loadPublic(), loadPrivate(), storePublic(), and storePrivate() methods - */ - constructor(storeHandler?: localstore.LocalStore); - - /** - * Calls the storeHandler to load the keys - */ - load(): void; - - /** - * Calls the storeHandler to save the keys - */ - store(): void; - - /** - * Clear the keyring - erase all the keys - */ - clear(): void; - - /** - * Searches the keyring for keys having the specified key id - * @param keyId provided as string of lowercase hex number - * withouth 0x prefix (can be 16-character key ID or fingerprint) - * @param deep if true search also in subkeys - * @returns keys found or null - */ - getKeysForId(keyId: string, deep: boolean): any[] | null; - - /** - * Removes keys having the specified key id from the keyring - * @param keyId provided as string of lowercase hex number - * withouth 0x prefix (can be 16-character key ID or fingerprint) - * @returns keys found or null - */ - removeKeysForId(keyId: string): any[] | null; - - /** - * Get all public and private keys - * @returns all keys - */ - getAllKeys(): any[]; - } + class Keyring { + /** + * Initialization routine for the keyring. + * @param storeHandler class implementing loadPublic(), loadPrivate(), storePublic(), and storePrivate() methods + */ + constructor(storeHandler?: localstore.LocalStore); /** - * Array of keys - * @param keys The keys to store in this array + * Calls the storeHandler to load the keys */ - function KeyArray(keys: any[]): void; + load(): void; + + /** + * Calls the storeHandler to save the keys + */ + store(): void; + + /** + * Clear the keyring - erase all the keys + */ + clear(): void; + + /** + * Searches the keyring for keys having the specified key id + * @param keyId provided as string of lowercase hex number + * withouth 0x prefix (can be 16-character key ID or fingerprint) + * @param deep if true search also in subkeys + * @returns keys found or null + */ + getKeysForId(keyId: string, deep: boolean): any[] | null; + + /** + * Removes keys having the specified key id from the keyring + * @param keyId provided as string of lowercase hex number + * withouth 0x prefix (can be 16-character key ID or fingerprint) + * @returns keys found or null + */ + removeKeysForId(keyId: string): any[] | null; + + /** + * Get all public and private keys + * @returns all keys + */ + getAllKeys(): any[]; } - namespace localstore { - class LocalStore { - /** - * The class that deals with storage of the keyring. - * Currently the only option is to use HTML5 local storage. - * @param prefix prefix for itemnames in localstore - */ - constructor(prefix: string); - - /** - * Load the public keys from HTML5 local storage. - * @returns array of keys retrieved from localstore - */ - loadPublic(): any[]; - - /** - * Load the private keys from HTML5 local storage. - * @returns array of keys retrieved from localstore - */ - loadPrivate(): any[]; - - /** - * Saves the current state of the public keys to HTML5 local storage. - * The key array gets stringified using JSON - * @param keys array of keys to save in localstore - */ - storePublic(keys: any[]): void; - - /** - * Saves the current state of the private keys to HTML5 local storage. - * The key array gets stringified using JSON - * @param keys array of keys to save in localstore - */ - storePrivate(keys: any[]): void; - } - } + /** + * Array of keys + * @param keys The keys to store in this array + */ + function KeyArray(keys: any[]): void; } - class LocalStore { - /** - * The class that deals with storage of the keyring. - * Currently the only option is to use HTML5 local storage. - * @param prefix prefix for itemnames in localstore - */ - constructor(prefix: string); - - /** - * Load the public keys from HTML5 local storage. - * @returns array of keys retrieved from localstore - */ - loadPublic(): any[]; - - /** - * Load the private keys from HTML5 local storage. - * @returns array of keys retrieved from localstore - */ - loadPrivate(): any[]; - - /** - * Saves the current state of the public keys to HTML5 local storage. - * The key array gets stringified using JSON - * @param keys array of keys to save in localstore - */ - storePublic(keys: any[]): void; - - /** - * Saves the current state of the private keys to HTML5 local storage. - * The key array gets stringified using JSON - * @param keys array of keys to save in localstore - */ - storePrivate(keys: any[]): void; - } - - namespace message { - /** - * Class that represents an OpenPGP message. - * Can be an encrypted message, signed message, compressed message or literal message - */ - class Message { - packets: packet.List; + namespace localstore { + class LocalStore { + /** + * The class that deals with storage of the keyring. + * Currently the only option is to use HTML5 local storage. + * @param prefix prefix for itemnames in localstore + */ + constructor(prefix: string); /** - * @param packetlist The packets that form this message - * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + * Load the public keys from HTML5 local storage. + * @returns array of keys retrieved from localstore */ - constructor(packetlist: packet.List); + loadPublic(): any[]; /** - * Returns the key IDs of the keys to which the session key is encrypted - * @returns array of keyid objects + * Load the private keys from HTML5 local storage. + * @returns array of keys retrieved from localstore */ - getEncryptionKeyIds(): any[]; + loadPrivate(): any[]; /** - * Returns the key IDs of the keys that signed the message - * @returns array of keyid objects + * Saves the current state of the public keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore */ - getSigningKeyIds(): any[]; + storePublic(keys: any[]): void; /** - * Decrypt the message. Either a private key, a session key, or a password must be specified. - * @param privateKeys (optional) private keys with decrypted secret data - * @param passwords (optional) passwords used to decrypt - * @param sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } - * @param streaming (optional) whether to process data as a stream - * @returns new message with decrypted content + * Saves the current state of the private keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore */ - decrypt(privateKeys?: any[], passwords?: any[], sessionKeys?: any[], streaming?: boolean): Promise; - - /** - * Decrypt encrypted session keys either with private keys or passwords. - * @param privateKeys (optional) private keys with decrypted secret data - * @param passwords (optional) passwords used to decrypt - * @returns array of object with potential sessionKey, algorithm pairs - */ - decryptSessionKeys(privateKeys?: any[], passwords?: any[]): Promise>; - - /** - * Get literal data that is the body of the message - * @returns literal body of the message as Uint8Array - */ - getLiteralData(): Uint8Array | null; - - /** - * Get filename from literal data packet - * @returns filename of literal data packet as string - */ - getFilename(): string | null; - - /** - * Get literal data as text - * @returns literal body of the message interpreted as text - */ - getText(): string | null; - - /** - * Encrypt the message either with public keys, passwords, or both at once. - * @param keys (optional) public key(s) for message encryption - * @param passwords (optional) password(s) for message encryption - * @param sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } - * @param wildcard (optional) use a key ID of 0 instead of the public key IDs - * @param date (optional) override the creation date of the literal package - * @param userIds (optional) user IDs to encrypt for, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] - * @param streaming (optional) whether to process data as a stream - * @returns new message with encrypted content - */ - encrypt(keys?: any[], passwords?: any[], sessionKey?: object, wildcard?: boolean, date?: Date, userIds?: any[], streaming?: boolean): Promise; - - /** - * Sign the message (the literal data packet of the message) - * @param privateKeys private keys with decrypted secret key data for signing - * @param signature (optional) any existing detached signature to add to the message - * @param date (optional) override the creation time of the signature - * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - * @returns new message with signed content - */ - sign(privateKeys: any[], signature?: signature.Signature, date?: Date, userIds?: any[]): Promise; - - /** - * Compresses the message (the literal and -if signed- signature data packets of the message) - * @param compression compression algorithm to be used - * @returns new message with compressed content - */ - compress(compression: enums.compression): Message; - - /** - * Create a detached signature for the message (the literal data packet of the message) - * @param privateKeys private keys with decrypted secret key data for signing - * @param signature (optional) any existing detached signature - * @param date (optional) override the creation time of the signature - * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - * @returns new detached signature of message content - */ - signDetached(privateKeys: any[], signature?: signature.Signature, date?: Date, userIds?: any[]): Promise; - - /** - * Verify message signatures - * @param keys array of keys to verify signatures - * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @param streaming (optional) whether to process data as a stream - * @returns list of signer's keyid and validity of signature - */ - verify(keys: any[], date?: Date, streaming?: boolean): Promise>; - - /** - * Verify detached message signature - * @param keys array of keys to verify signatures - * @param signature - * @param date Verify the signature against the given date, i.e. check signature creation time < date < expiration time - * @returns list of signer's keyid and validity of signature - */ - verifyDetached(keys: any[], signature: signature.Signature, date?: Date): Promise>; - - /** - * Unwrap compressed message - * @returns message Content of compressed message - */ - unwrapCompressed(): Message; - - /** - * Append signature to unencrypted message object - * @param detachedSignature The detached ASCII-armored or Uint8Array PGP signature - */ - appendSignature(detachedSignature: string | Uint8Array): void; - - /** - * Returns ASCII armored text of message - * @returns ASCII armor - */ - armor(): ReadableStream; + storePrivate(keys: any[]): void; } + } +} + +export class LocalStore { + /** + * The class that deals with storage of the keyring. + * Currently the only option is to use HTML5 local storage. + * @param prefix prefix for itemnames in localstore + */ + constructor(prefix: string); + + /** + * Load the public keys from HTML5 local storage. + * @returns array of keys retrieved from localstore + */ + loadPublic(): any[]; + + /** + * Load the private keys from HTML5 local storage. + * @returns array of keys retrieved from localstore + */ + loadPrivate(): any[]; + + /** + * Saves the current state of the public keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore + */ + storePublic(keys: any[]): void; + + /** + * Saves the current state of the private keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore + */ + storePrivate(keys: any[]): void; +} + +export namespace message { + /** + * Class that represents an OpenPGP message. + * Can be an encrypted message, signed message, compressed message or literal message + */ + class Message { + packets: packet.List; /** - * Encrypt a session key either with public keys, passwords, or both at once. - * @param sessionKey session key for encryption - * @param symAlgo session key algorithm - * @param aeadAlgo (optional) aead algorithm, e.g. 'eax' or 'ocb' - * @param publicKeys (optional) public key(s) for message encryption - * @param passwords (optional) for message encryption + * @param packetlist The packets that form this message + * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + */ + constructor(packetlist: packet.List); + + /** + * Returns the key IDs of the keys to which the session key is encrypted + * @returns array of keyid objects + */ + getEncryptionKeyIds(): any[]; + + /** + * Returns the key IDs of the keys that signed the message + * @returns array of keyid objects + */ + getSigningKeyIds(): any[]; + + /** + * Decrypt the message. Either a private key, a session key, or a password must be specified. + * @param privateKeys (optional) private keys with decrypted secret data + * @param passwords (optional) passwords used to decrypt + * @param sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param streaming (optional) whether to process data as a stream + * @returns new message with decrypted content + */ + decrypt(privateKeys?: any[], passwords?: any[], sessionKeys?: any[], streaming?: boolean): Promise; + + /** + * Decrypt encrypted session keys either with private keys or passwords. + * @param privateKeys (optional) private keys with decrypted secret data + * @param passwords (optional) passwords used to decrypt + * @returns array of object with potential sessionKey, algorithm pairs + */ + decryptSessionKeys(privateKeys?: any[], passwords?: any[]): Promise>; + + /** + * Get literal data that is the body of the message + * @returns literal body of the message as Uint8Array + */ + getLiteralData(): Uint8Array | null; + + /** + * Get filename from literal data packet + * @returns filename of literal data packet as string + */ + getFilename(): string | null; + + /** + * Get literal data as text + * @returns literal body of the message interpreted as text + */ + getText(): string | null; + + /** + * Encrypt the message either with public keys, passwords, or both at once. + * @param keys (optional) public key(s) for message encryption + * @param passwords (optional) password(s) for message encryption + * @param sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } * @param wildcard (optional) use a key ID of 0 instead of the public key IDs - * @param date (optional) override the date + * @param date (optional) override the creation date of the literal package * @param userIds (optional) user IDs to encrypt for, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param streaming (optional) whether to process data as a stream * @returns new message with encrypted content */ - function encryptSessionKey(sessionKey: Uint8Array, symAlgo: string, aeadAlgo: string, publicKeys: any[], passwords: any[], wildcard: boolean, date: Date, userIds: any[]): Promise; + encrypt(keys?: any[], passwords?: any[], sessionKey?: object, wildcard?: boolean, date?: Date, userIds?: any[], streaming?: boolean): Promise; /** - * Create signature packets for the message - * @param literalDataPacket the literal data packet to sign + * Sign the message (the literal data packet of the message) * @param privateKeys private keys with decrypted secret key data for signing - * @param signature (optional) any existing detached signature to append - * @param date (optional) override the creationtime of the signature + * @param signature (optional) any existing detached signature to add to the message + * @param date (optional) override the creation time of the signature * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - * @returns list of signature packets + * @returns new message with signed content */ - function createSignaturePackets(literalDataPacket: packet.Literal, privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; + sign(privateKeys: any[], signature?: signature.Signature, date?: Date, userIds?: any[]): Promise; /** - * Create object containing signer's keyid and validity of signature - * @param signature signature packets - * @param literalDataList array of literal data packets + * Compresses the message (the literal and -if signed- signature data packets of the message) + * @param compression compression algorithm to be used + * @returns new message with compressed content + */ + compress(compression: enums.compression): Message; + + /** + * Create a detached signature for the message (the literal data packet of the message) + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature + * @param date (optional) override the creation time of the signature + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new detached signature of message content + */ + signDetached(privateKeys: any[], signature?: signature.Signature, date?: Date, userIds?: any[]): Promise; + + /** + * Verify message signatures * @param keys array of keys to verify signatures - * @param date Verify the signature against the given date, - * i.e. check signature creation time < date < expiration time + * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param streaming (optional) whether to process data as a stream * @returns list of signer's keyid and validity of signature */ - function createVerificationObject(signature: packet.Signature, literalDataList: any[], keys: any[], date: Date): Promise>; + verify(keys: any[], date?: Date, streaming?: boolean): Promise>; /** - * Create list of objects containing signer's keyid and validity of signature - * @param signatureList array of signature packets - * @param literalDataList array of literal data packets + * Verify detached message signature * @param keys array of keys to verify signatures - * @param date Verify the signature against the given date, - * i.e. check signature creation time < date < expiration time + * @param signature + * @param date Verify the signature against the given date, i.e. check signature creation time < date < expiration time * @returns list of signer's keyid and validity of signature */ - function createVerificationObjects(signatureList: any[], literalDataList: any[], keys: any[], date: Date): Promise>; + verifyDetached(keys: any[], signature: signature.Signature, date?: Date): Promise>; /** - * reads an OpenPGP armored message and returns a message object - * @param armoredText text to be parsed - * @returns new message object + * Unwrap compressed message + * @returns message Content of compressed message */ - function readArmored(armoredText: string | ReadableStream): Promise; + unwrapCompressed(): Message; /** - * reads an OpenPGP message as byte array and returns a message object - * @param input binary message - * @param fromStream whether the message was created from a Stream - * @returns new message object + * Append signature to unencrypted message object + * @param detachedSignature The detached ASCII-armored or Uint8Array PGP signature */ - function read(input: Uint8Array | ReadableStream, fromStream?: boolean): Promise; + appendSignature(detachedSignature: string | Uint8Array): void; /** - * creates new message object from text - * @param text - * @param filename (optional) - * @param date (optional) - * @param {utf8 | binary | text | mime} type (optional) data packet type - * @returns new message object + * Returns ASCII armored text of message + * @returns ASCII armor */ - function fromText(text: string | ReadableStream, filename?: string, date?: Date, type?: any): Message; - - /** - * creates new message object from binary data - * @param bytes - * @param filename (optional) - * @param date (optional) - * @param {utf8 | binary | text | mime} type (optional) data packet type - * @returns new message object - */ - function fromBinary(bytes: Uint8Array | ReadableStream, filename?: string, date?: Date, type?: any): Message; - } - - interface revokeKey_reasonForRevocation { - /** - * (optional) flag indicating the reason for revocation - */ - flag: enums.reasonForRevocation; - /** - * (optional) string explaining the reason for revocation - */ - string: string; + armor(): ReadableStream; } /** - * @see module:packet/all_packets - * @see module:packet/clone - * @see module:packet.List + * Encrypt a session key either with public keys, passwords, or both at once. + * @param sessionKey session key for encryption + * @param symAlgo session key algorithm + * @param aeadAlgo (optional) aead algorithm, e.g. 'eax' or 'ocb' + * @param publicKeys (optional) public key(s) for message encryption + * @param passwords (optional) for message encryption + * @param wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param date (optional) override the date + * @param userIds (optional) user IDs to encrypt for, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] + * @returns new message with encrypted content */ + function encryptSessionKey(sessionKey: Uint8Array, symAlgo: string, aeadAlgo: string, publicKeys: any[], passwords: any[], wildcard: boolean, date: Date, userIds: any[]): Promise; + + /** + * Create signature packets for the message + * @param literalDataPacket the literal data packet to sign + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature to append + * @param date (optional) override the creationtime of the signature + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns list of signature packets + */ + function createSignaturePackets(literalDataPacket: packet.Literal, privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; + + /** + * Create object containing signer's keyid and validity of signature + * @param signature signature packets + * @param literalDataList array of literal data packets + * @param keys array of keys to verify signatures + * @param date Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + function createVerificationObject(signature: packet.Signature, literalDataList: any[], keys: any[], date: Date): Promise>; + + /** + * Create list of objects containing signer's keyid and validity of signature + * @param signatureList array of signature packets + * @param literalDataList array of literal data packets + * @param keys array of keys to verify signatures + * @param date Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + function createVerificationObjects(signatureList: any[], literalDataList: any[], keys: any[], date: Date): Promise>; + + /** + * reads an OpenPGP armored message and returns a message object + * @param armoredText text to be parsed + * @returns new message object + */ + function readArmored(armoredText: string | ReadableStream): Promise; + + /** + * reads an OpenPGP message as byte array and returns a message object + * @param input binary message + * @param fromStream whether the message was created from a Stream + * @returns new message object + */ + function read(input: Uint8Array | ReadableStream, fromStream?: boolean): Promise; + + /** + * creates new message object from text + * @param text + * @param filename (optional) + * @param date (optional) + * @param {utf8 | binary | text | mime} type (optional) data packet type + * @returns new message object + */ + function fromText(text: string | ReadableStream, filename?: string, date?: Date, type?: any): Message; + + /** + * creates new message object from binary data + * @param bytes + * @param filename (optional) + * @param date (optional) + * @param {utf8 | binary | text | mime} type (optional) data packet type + * @returns new message object + */ + function fromBinary(bytes: Uint8Array | ReadableStream, filename?: string, date?: Date, type?: any): Message; +} + +export interface revokeKey_reasonForRevocation { + /** + * (optional) flag indicating the reason for revocation + */ + flag: enums.reasonForRevocation; + /** + * (optional) string explaining the reason for revocation + */ + string: string; +} + +/** + * @see module:packet/all_packets + * @see module:packet/clone + * @see module:packet.List + */ +export namespace packet { + /** + * Allocate a new packet + * @param tag property name from {@link module:enums.packet} + * @returns new packet object with type based on tag + */ + function newPacketFromTag(tag: string): object; + + /** + * Allocate a new packet from structured packet clone + * @see + * @param packetClone packet clone + * @returns new packet object with data from packet clone + */ + function fromStructuredClone(packetClone: object): object; + + class Compressed { + /** + * Implementation of the Compressed Data Packet (Tag 8) + * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: + * The Compressed Data packet contains compressed data. Typically, + * this packet is found as the contents of an encrypted packet, or following + * a Signature or One-Pass Signature packet, and contains a literal data packet. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * List of packets + */ + packets: List; + + /** + * Compression algorithm + * @type {compression} + */ + algorithm: any; + + /** + * Compressed packet data + */ + compressed: Uint8Array | ReadableStream; + + /** + * Parsing function for the packet. + * @param bytes Payload of a tag 8 packet + */ + read(bytes: Uint8Array | ReadableStream): void; + + /** + * Return the compressed packet. + * @returns binary compressed packet + */ + write(): Uint8Array | ReadableStream; + + /** + * Decompression method for decompressing the compressed data + * read by read_packet + */ + decompress(): void; + + /** + * Compress the packet data (member decompressedData) + */ + compress(): void; + } + + class Literal { + /** + * Implementation of the Literal Data Packet (Tag 11) + * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: + * A Literal Data packet contains the body of a message; data that is not to be + * further interpreted. + * @param date the creation date of the literal package + */ + constructor(date: Date); + + /** + * Set the packet data to a javascript native string, end of line + * will be normalized to \r\n and by default text is converted to UTF8 + * @param text Any native javascript string + * @param {utf8 | binary | text | mime} format (optional) The format of the string of bytes + */ + setText(text: string | ReadableStream, format: any): void; + + /** + * Returns literal data packets as native JavaScript string + * with normalized end of line to \n + * @param clone (optional) Whether to return a clone so that getBytes/getText can be called again + * @returns literal data as text + */ + getText(clone: boolean): string | ReadableStream; + + /** + * Set the packet data to value represented by the provided string of bytes. + * @param bytes The string of bytes + * @param {utf8 | binary | text | mime} format The format of the string of bytes + */ + setBytes(bytes: Uint8Array | ReadableStream, format: any): void; + + /** + * Get the byte sequence representing the literal packet data + * @param clone (optional) Whether to return a clone so that getBytes/getText can be called again + * @returns A sequence of bytes + */ + getBytes(clone: boolean): Uint8Array | ReadableStream; + + /** + * Sets the filename of the literal packet data + * @param filename Any native javascript string + */ + setFilename(filename: string): void; + + /** + * Get the filename of the literal packet data + * @returns filename + */ + getFilename(): string; + + /** + * Parsing function for a literal data packet (tag 11). + * @param input Payload of a tag 11 packet + * @returns object representation + */ + read(input: Uint8Array | ReadableStream): Literal; + + /** + * Creates a string representation of the packet + * @returns Uint8Array representation of the packet + */ + write(): Uint8Array | ReadableStream; + } + + class Marker { + /** + * Implementation of the strange "Marker packet" (Tag 10) + * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: + * An experimental version of PGP used this packet as the Literal + * packet, but no released version of PGP generated Literal packets with this + * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as + * the Marker packet. + * Such a packet MUST be ignored when received. + */ + constructor(); + + /** + * Parsing function for a literal data packet (tag 10). + * @param input Payload of a tag 10 packet + * @param position Position to start reading from the input string + * @param len Length of the packet or the remaining length of + * input at position + * @returns Object representation + */ + read(input: string, position: Integer, len: Integer): Marker; + } + + class OnePassSignature { + /** + * Implementation of the One-Pass Signature Packets (Tag 4) + * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: + * The One-Pass Signature packet precedes the signed data and contains + * enough information to allow the receiver to begin calculating any + * hashes needed to verify the signature. It allows the Signature + * packet to be placed at the end of the message, so that the signer + * can compute the entire signed message in one pass. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * A one-octet version number. The current version is 3. + */ + version: any; + + /** + * A one-octet signature type. + * Signature types are described in + * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. + */ + signatureType: any; + + /** + * A one-octet number describing the hash algorithm used. + * @see + */ + hashAlgorithm: any; + + /** + * A one-octet number describing the public-key algorithm used. + * @see + */ + publicKeyAlgorithm: any; + + /** + * An eight-octet number holding the Key ID of the signing key. + */ + issuerKeyId: any; + + /** + * A one-octet number holding a flag showing whether the signature is nested. + * A zero value indicates that the next packet is another One-Pass Signature packet + * that describes another signature to be applied to the same message data. + */ + flags: any; + + /** + * parsing function for a one-pass signature packet (tag 4). + * @param bytes payload of a tag 4 packet + * @returns object representation + */ + read(bytes: Uint8Array): OnePassSignature; + + /** + * creates a string representation of a one-pass signature packet + * @returns a Uint8Array representation of a one-pass signature packet + */ + write(): Uint8Array; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class List { + /** + * This class represents a list of openpgp packets. + * Take care when iterating over it - the packets themselves + * are stored as numerical indices. + */ + constructor(); + + /** + * The number of packets contained within the list. + */ + readonly length: Integer; + + /** + * Reads a stream of binary data and interprents it as a list of packets. + * @param A Uint8Array of bytes. + */ + read(A: Uint8Array | ReadableStream): void; + + /** + * Creates a binary representation of openpgp objects contained within the + * class instance. + * @returns A Uint8Array containing valid openpgp packets. + */ + write(): Uint8Array; + + /** + * Adds a packet to the list. This is the only supported method of doing so; + * writing to packetlist[i] directly will result in an error. + * @param packet Packet to push + */ + push(packet: object): void; + + /** + * Creates a new PacketList with all packets from the given types + */ + filterByTag(): void; + + /** + * Traverses packet tree and returns first matching packet + * @param type The packet type + * @returns + */ + findPacket(type: enums.packet): List | undefined; + + /** + * Returns array of found indices by tag + */ + indexOfTag(): void; + + /** + * Concatenates packetlist or array of packets + */ + concat(): void; + + /** + * Allocate a new packetlist from structured packetlist clone + * See {@link https://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data} + * @param packetClone packetlist clone + * @returns new packetlist object with data from packetlist clone + */ + static fromStructuredClone(packetClone: object): object; + } + + class PublicKey { + /** + * Implementation of the Key Material Packet (Tag 5,6,7,14) + * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: + * A key material packet contains all the information about a public or + * private key. There are four variants of this packet type, and two + * major versions. + * A Public-Key packet starts a series of packets that forms an OpenPGP + * key (sometimes called an OpenPGP certificate). + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} + * called by read_tag<num> + * @param bytes Input array to read the packet from + * @returns This object with attributes set by the parser + */ + read(bytes: Uint8Array): object; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Same as write_private_key, but has less information because of + * public key. + * @returns OpenPGP packet body contents, + */ + write(): Uint8Array; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class PublicKeyEncryptedSessionKey { + /** + * Public-Key Encrypted Session Key Packets (Tag 1) + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + */ + constructor(); + + encrypted: any[]; + + /** + * Parsing function for a publickey encrypted session key packet (tag 1). + * @param input Payload of a tag 1 packet + * @param position Position to start reading from the input string + * @param len Length of the packet or the remaining length of + * input at position + * @returns Object representation + */ + read(input: Uint8Array, position: Integer, len: Integer): PublicKeyEncryptedSessionKey + + /** + * Create a string representation of a tag 1 packet + * @returns The Uint8Array representation + */ + write(): Uint8Array; + + /** + * Encrypt session key packet + * @param key Public key + * @returns + */ + encrypt(key: PublicKey): Promise; + + /** + * Decrypts the session key (only for public key encrypted session key + * packets (tag 1) + * @param key Private key with secret params unlocked + * @returns + */ + decrypt(key: SecretKey): Promise; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class PublicSubkey { + /** + * A Public-Subkey packet (tag 14) has exactly the same format as a + * Public-Key packet, but denotes a subkey. One or more subkeys may be + * associated with a top-level key. By convention, the top-level key + * provides signature services, and the subkeys provide encryption + * services. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} + * called by read_tag<num> + * @param bytes Input array to read the packet from + * @returns This object with attributes set by the parser + */ + read(bytes: Uint8Array): object; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Same as write_private_key, but has less information because of + * public key. + * @returns OpenPGP packet body contents, + */ + write(): Uint8Array; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class SecretKey { + /** + * A Secret-Key packet contains all the information that is found in a + * Public-Key packet, including the public-key material, but also + * includes the secret-key material after all the public-key fields. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Encrypted secret-key data + */ + encrypted: any; + + /** + * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. + */ + isEncrypted: any; + + /** + * Internal parser for private keys as specified in + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} + * @param bytes Input string to read the packet from + */ + read(bytes: string): void; + + /** + * Creates an OpenPGP key packet for the given key. + * @returns A string of bytes containing the secret key OpenPGP packet + */ + write(): string; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Encrypt the payload. By default, we use aes256 and iterated, salted string + * to key specifier. If the key is in a decrypted state (isEncrypted === false) + * and the passphrase is empty or undefined, the key will be set as not encrypted. + * This can be used to remove passphrase protection after calling decrypt(). + * @param passphrase + * @returns + */ + encrypt(passphrase: string): Promise; + + /** + * Decrypts the private key params which are needed to use the key. + * {@link module:packet.SecretKey.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param passphrase The passphrase for this private key as string + * @returns + */ + decrypt(passphrase: string): Promise; + + /** + * Clear private params, return to initial state + */ + clearPrivateParams(): void; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + } + + class SecretSubkey { + /** + * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret + * Key packet and has exactly the same format. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Encrypted secret-key data + */ + encrypted: any; + + /** + * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. + */ + isEncrypted: any; + + /** + * Internal parser for private keys as specified in + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} + * @param bytes Input string to read the packet from + */ + read(bytes: string): void; + + /** + * Creates an OpenPGP key packet for the given key. + * @returns A string of bytes containing the secret key OpenPGP packet + */ + write(): string; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Encrypt the payload. By default, we use aes256 and iterated, salted string + * to key specifier. If the key is in a decrypted state (isEncrypted === false) + * and the passphrase is empty or undefined, the key will be set as not encrypted. + * This can be used to remove passphrase protection after calling decrypt(). + * @param passphrase + * @returns + */ + encrypt(passphrase: string): Promise; + + /** + * Decrypts the private key params which are needed to use the key. + * {@link module:packet.SecretKey.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param passphrase The passphrase for this private key as string + * @returns + */ + decrypt(passphrase: string): Promise; + + /** + * Clear private params, return to initial state + */ + clearPrivateParams(): void; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + } + + class Signature { + /** + * Implementation of the Signature Packet (Tag 2) + * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: + * A Signature packet describes a binding between some public key and + * some data. The most common signatures are a signature of a file or a + * block of text, and a signature that is a certification of a User ID. + * @param date the creation date of the signature + */ + constructor(date: Date); + + /** + * parsing function for a signature packet (tag 2). + * @param bytes payload of a tag 2 packet + * @param position position to start reading from the bytes string + * @param len length of the packet or the remaining length of bytes at position + * @returns object representation + */ + read(bytes: string, position: Integer, len: Integer): Signature; + + /** + * Signs provided data. This needs to be done prior to serialization. + * @param key private key used to sign the message. + * @param data Contains packets to be signed. + * @returns + */ + sign(key: SecretKey, data: object): Promise; + + /** + * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets + * @returns subpacket data + */ + write_hashed_sub_packets(): Uint8Array; + + /** + * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets + * @returns subpacket data + */ + write_unhashed_sub_packets(): Uint8Array; + + /** + * verifys the signature packet. Note: not signature types are implemented + * @param key the public key to verify the signature + * @param signatureType expected signature type + * @param data data which on the signature applies + * @returns True if message is verified, else false. + */ + verify(key: PublicSubkey | PublicKey | SecretSubkey | SecretKey, signatureType: enums.signature, data: string | object): Promise; + + /** + * Verifies signature expiration date + * @param date (optional) use the given date for verification instead of the current time + * @returns true if expired + */ + isExpired(date: Date): boolean; + + /** + * Returns the expiration time of the signature or Infinity if signature does not expire + * @returns expiration time + */ + getExpirationTime(): Date; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class SymEncryptedAEADProtected { + /** + * Implementation of the Symmetrically Encrypted Authenticated Encryption with + * Additional Data (AEAD) Protected Data Packet + * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: + * AEAD Protected Data Packet + */ + constructor(); + + /** + * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @param bytes + */ + read(bytes: Uint8Array | ReadableStream): void; + + /** + * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @returns The encrypted payload + */ + write(): Uint8Array | ReadableStream; + + /** + * Decrypt the encrypted payload. + * @param sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' + * @param key The session key used to encrypt the payload + * @param streaming Whether the top-level function will return a stream + * @returns + */ + decrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): boolean; + + /** + * Encrypt the packet list payload. + * @param sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' + * @param key The session key used to encrypt the payload + * @param streaming Whether the top-level function will return a stream + */ + encrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): void; + + /** + * En/decrypt the payload. + * @param {encrypt | decrypt} fn Whether to encrypt or decrypt + * @param key The session key used to en/decrypt the payload + * @param data The data to en/decrypt + * @param streaming Whether the top-level function will return a stream + * @returns + */ + crypt(fn: any, key: Uint8Array, data: Uint8Array | ReadableStream, streaming: boolean): Uint8Array | ReadableStream; + } + + class SymEncryptedIntegrityProtected { + /** + * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) + * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: + * The Symmetrically Encrypted Integrity Protected Data packet is + * a variant of the Symmetrically Encrypted Data packet. It is a new feature + * created for OpenPGP that addresses the problem of detecting a modification to + * encrypted data. It is used in combination with a Modification Detection Code + * packet. + */ + constructor(); + + /** + * The encrypted payload. + */ + encrypted: any; + + /** + * If after decrypting the packet this is set to true, + * a modification has been detected and thus the contents + * should be discarded. + */ + modification: boolean; + + /** + * Encrypt the payload in the packet. + * @param sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' + * @param key The key of cipher blocksize length to be used + * @param streaming Whether to set this.encrypted to a stream + * @returns + */ + encrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): Promise; + + /** + * Decrypts the encrypted data contained in the packet. + * @param sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' + * @param key The key of cipher blocksize length to be used + * @param streaming Whether to read this.encrypted as a stream + * @returns + */ + decrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): Promise; + } + + class SymEncryptedSessionKey { + /** + * Public-Key Encrypted Session Key Packets (Tag 1) + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + */ + constructor(); + + /** + * Parsing function for a symmetric encrypted session key packet (tag 3). + * @param input Payload of a tag 1 packet + * @param position Position to start reading from the input string + * @param len Length of the packet or the remaining length of + * input at position + * @returns Object representation + */ + read(input: Uint8Array, position: Integer, len: Integer): SymEncryptedSessionKey; + + /** + * Decrypts the session key + * @param passphrase The passphrase in string form + * @returns + */ + decrypt(passphrase: string): Promise; + + /** + * Encrypts the session key + * @param passphrase The passphrase in string form + * @returns + */ + encrypt(passphrase: string): Promise; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class SymmetricallyEncrypted { + /** + * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) + * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: + * The Symmetrically Encrypted Data packet contains data encrypted with a + * symmetric-key algorithm. When it has been decrypted, it contains other + * packets (usually a literal data packet or compressed data packet, but in + * theory other Symmetrically Encrypted Data packets or sequences of packets + * that form whole OpenPGP messages). + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Encrypted secret-key data + */ + encrypted: any; + + /** + * Decrypted packets contained within. + */ + packets: List; + + /** + * When true, decrypt fails if message is not integrity protected + * @see module:config.ignore_mdc_error + */ + ignore_mdc_error: any; + + /** + * Decrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param sessionKeyAlgorithm Symmetric key algorithm to use + * @param key The key of cipher blocksize length to be used + * @returns + */ + decrypt(sessionKeyAlgorithm: enums.symmetric, key: Uint8Array): Promise; + + /** + * Encrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param sessionKeyAlgorithm Symmetric key algorithm to use + * @param key The key of cipher blocksize length to be used + * @returns + */ + encrypt(sessionKeyAlgorithm: enums.symmetric, key: Uint8Array): Promise; + } + + class Trust { + /** + * Implementation of the Trust Packet (Tag 12) + * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: + * The Trust packet is used only within keyrings and is not normally + * exported. Trust packets contain data that record the user's + * specifications of which key holders are trustworthy introducers, + * along with other information that implementing software uses for + * trust information. The format of Trust packets is defined by a given + * implementation. + * Trust packets SHOULD NOT be emitted to output streams that are + * transferred to other users, and they SHOULD be ignored on any input + * other than local keyring files. + */ + constructor(); + + /** + * Parsing function for a trust packet (tag 12). + * Currently not implemented as we ignore trust packets + * @param byptes payload of a tag 12 packet + */ + read(byptes: string): void; + } + + class UserAttribute { + /** + * Implementation of the User Attribute Packet (Tag 17) + * The User Attribute packet is a variation of the User ID packet. It + * is capable of storing more types of data than the User ID packet, + * which is limited to text. Like the User ID packet, a User Attribute + * packet may be certified by the key owner ("self-signed") or any other + * key owner who cares to certify it. Except as noted, a User Attribute + * packet may be used anywhere that a User ID packet may be used. + * While User Attribute packets are not a required part of the OpenPGP + * standard, implementations SHOULD provide at least enough + * compatibility to properly handle a certification signature on the + * User Attribute packet. A simple way to do this is by treating the + * User Attribute packet as a User ID packet with opaque contents, but + * an implementation may use any method desired. + */ + constructor(); + + /** + * parsing function for a user attribute packet (tag 17). + * @param input payload of a tag 17 packet + */ + read(input: Uint8Array): void; + + /** + * Creates a binary representation of the user attribute packet + * @returns string representation + */ + write(): Uint8Array; + + /** + * Compare for equality + * @param usrAttr + * @returns true if equal + */ + equals(usrAttr: UserAttribute): boolean; + } + + class Userid { + /** + * Implementation of the User ID Packet (Tag 13) + * A User ID packet consists of UTF-8 text that is intended to represent + * the name and email address of the key holder. By convention, it + * includes an RFC 2822 [RFC2822] mail name-addr, but there are no + * restrictions on its content. The packet length in the header + * specifies the length of the User ID. + */ + constructor(); + + /** + * A string containing the user id. Usually in the form + * John Doe + */ + userid: string; + + /** + * Parsing function for a user id packet (tag 13). + * @param input payload of a tag 13 packet + */ + read(input: Uint8Array): void; + + /** + * Parse userid string, e.g. 'John Doe ' + */ + parse(): void; + + /** + * Creates a binary representation of the user id packet + * @returns binary representation + */ + write(): Uint8Array; + + /** + * Set userid string from object, e.g. { name:'Phil Zimmermann', email:'phil@openpgp.org' } + */ + format(): void; + } + + namespace all_packets { + /** + * @see module:packet.Compressed + */ + var Compressed: any; + + /** + * @see module:packet.SymEncryptedIntegrityProtected + */ + var SymEncryptedIntegrityProtected: any; + + /** + * @see module:packet.SymEncryptedAEADProtected + */ + var SymEncryptedAEADProtected: any; + + /** + * @see module:packet.PublicKeyEncryptedSessionKey + */ + var PublicKeyEncryptedSessionKey: any; + + /** + * @see module:packet.SymEncryptedSessionKey + */ + var SymEncryptedSessionKey: any; + + /** + * @see module:packet.Literal + */ + var Literal: any; + + /** + * @see module:packet.PublicKey + */ + var PublicKey: any; + + /** + * @see module:packet.SymmetricallyEncrypted + */ + var SymmetricallyEncrypted: any; + + /** + * @see module:packet.Marker + */ + var Marker: any; + + /** + * @see module:packet.PublicSubkey + */ + var PublicSubkey: any; + + /** + * @see module:packet.UserAttribute + */ + var UserAttribute: any; + + /** + * @see module:packet.OnePassSignature + */ + var OnePassSignature: any; + + /** + * @see module:packet.SecretKey + */ + var SecretKey: any; + + /** + * @see module:packet.Userid + */ + var Userid: any; + + /** + * @see module:packet.SecretSubkey + */ + var SecretSubkey: any; + + /** + * @see module:packet.Signature + */ + var Signature: any; + + /** + * @see module:packet.Trust + */ + var Trust: any; + } + + namespace clone { + /** + * Create a packetlist from the correspoding object types. + * @param options the object passed to and from the web worker + * @returns a mutated version of the options optject + */ + function clonePackets(options: object): object; + + /** + * Creates an object with the correct prototype from a corresponding packetlist. + * @param options the object passed to and from the web worker + * @param method the public api function name to be delegated to the worker + * @returns a mutated version of the options optject + */ + function parseClonedPackets(options: object, method: string): object; + } + namespace packet { /** - * Allocate a new packet - * @param tag property name from {@link module:enums.packet} - * @returns new packet object with type based on tag + * Encodes a given integer of length to the openpgp length specifier to a + * string + * @param length The length to encode + * @returns String with openpgp length representation */ - function newPacketFromTag(tag: string): object; + function writeSimpleLength(length: Integer): Uint8Array; /** - * Allocate a new packet from structured packet clone - * @see - * @param packetClone packet clone - * @returns new packet object with data from packet clone + * Writes a packet header version 4 with the given tag_type and length to a + * string + * @param tag_type Tag type + * @param length Length of the payload + * @returns String of the header */ - function fromStructuredClone(packetClone: object): object; - - class Compressed { - /** - * Implementation of the Compressed Data Packet (Tag 8) - * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: - * The Compressed Data packet contains compressed data. Typically, - * this packet is found as the contents of an encrypted packet, or following - * a Signature or One-Pass Signature packet, and contains a literal data packet. - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * List of packets - */ - packets: List; - - /** - * Compression algorithm - * @type {compression} - */ - algorithm: any; - - /** - * Compressed packet data - */ - compressed: Uint8Array | ReadableStream; - - /** - * Parsing function for the packet. - * @param bytes Payload of a tag 8 packet - */ - read(bytes: Uint8Array | ReadableStream): void; - - /** - * Return the compressed packet. - * @returns binary compressed packet - */ - write(): Uint8Array | ReadableStream; - - /** - * Decompression method for decompressing the compressed data - * read by read_packet - */ - decompress(): void; - - /** - * Compress the packet data (member decompressedData) - */ - compress(): void; - } - - class Literal { - /** - * Implementation of the Literal Data Packet (Tag 11) - * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: - * A Literal Data packet contains the body of a message; data that is not to be - * further interpreted. - * @param date the creation date of the literal package - */ - constructor(date: Date); - - /** - * Set the packet data to a javascript native string, end of line - * will be normalized to \r\n and by default text is converted to UTF8 - * @param text Any native javascript string - * @param {utf8 | binary | text | mime} format (optional) The format of the string of bytes - */ - setText(text: string | ReadableStream, format: any): void; - - /** - * Returns literal data packets as native JavaScript string - * with normalized end of line to \n - * @param clone (optional) Whether to return a clone so that getBytes/getText can be called again - * @returns literal data as text - */ - getText(clone: boolean): string | ReadableStream; - - /** - * Set the packet data to value represented by the provided string of bytes. - * @param bytes The string of bytes - * @param {utf8 | binary | text | mime} format The format of the string of bytes - */ - setBytes(bytes: Uint8Array | ReadableStream, format: any): void; - - /** - * Get the byte sequence representing the literal packet data - * @param clone (optional) Whether to return a clone so that getBytes/getText can be called again - * @returns A sequence of bytes - */ - getBytes(clone: boolean): Uint8Array | ReadableStream; - - /** - * Sets the filename of the literal packet data - * @param filename Any native javascript string - */ - setFilename(filename: string): void; - - /** - * Get the filename of the literal packet data - * @returns filename - */ - getFilename(): string; - - /** - * Parsing function for a literal data packet (tag 11). - * @param input Payload of a tag 11 packet - * @returns object representation - */ - read(input: Uint8Array | ReadableStream): Literal; - - /** - * Creates a string representation of the packet - * @returns Uint8Array representation of the packet - */ - write(): Uint8Array | ReadableStream; - } - - class Marker { - /** - * Implementation of the strange "Marker packet" (Tag 10) - * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: - * An experimental version of PGP used this packet as the Literal - * packet, but no released version of PGP generated Literal packets with this - * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as - * the Marker packet. - * Such a packet MUST be ignored when received. - */ - constructor(); - - /** - * Parsing function for a literal data packet (tag 10). - * @param input Payload of a tag 10 packet - * @param position Position to start reading from the input string - * @param len Length of the packet or the remaining length of - * input at position - * @returns Object representation - */ - read(input: string, position: Integer, len: Integer): Marker; - } - - class OnePassSignature { - /** - * Implementation of the One-Pass Signature Packets (Tag 4) - * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: - * The One-Pass Signature packet precedes the signed data and contains - * enough information to allow the receiver to begin calculating any - * hashes needed to verify the signature. It allows the Signature - * packet to be placed at the end of the message, so that the signer - * can compute the entire signed message in one pass. - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * A one-octet version number. The current version is 3. - */ - version: any; - - /** - * A one-octet signature type. - * Signature types are described in - * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. - */ - signatureType: any; - - /** - * A one-octet number describing the hash algorithm used. - * @see - */ - hashAlgorithm: any; - - /** - * A one-octet number describing the public-key algorithm used. - * @see - */ - publicKeyAlgorithm: any; - - /** - * An eight-octet number holding the Key ID of the signing key. - */ - issuerKeyId: any; - - /** - * A one-octet number holding a flag showing whether the signature is nested. - * A zero value indicates that the next packet is another One-Pass Signature packet - * that describes another signature to be applied to the same message data. - */ - flags: any; - - /** - * parsing function for a one-pass signature packet (tag 4). - * @param bytes payload of a tag 4 packet - * @returns object representation - */ - read(bytes: Uint8Array): OnePassSignature; - - /** - * creates a string representation of a one-pass signature packet - * @returns a Uint8Array representation of a one-pass signature packet - */ - write(): Uint8Array; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - } - - class List { - /** - * This class represents a list of openpgp packets. - * Take care when iterating over it - the packets themselves - * are stored as numerical indices. - */ - constructor(); - - /** - * The number of packets contained within the list. - */ - readonly length: Integer; - - /** - * Reads a stream of binary data and interprents it as a list of packets. - * @param A Uint8Array of bytes. - */ - read(A: Uint8Array | ReadableStream): void; - - /** - * Creates a binary representation of openpgp objects contained within the - * class instance. - * @returns A Uint8Array containing valid openpgp packets. - */ - write(): Uint8Array; - - /** - * Adds a packet to the list. This is the only supported method of doing so; - * writing to packetlist[i] directly will result in an error. - * @param packet Packet to push - */ - push(packet: object): void; - - /** - * Creates a new PacketList with all packets from the given types - */ - filterByTag(): void; - - /** - * Traverses packet tree and returns first matching packet - * @param type The packet type - * @returns - */ - findPacket(type: enums.packet): List | undefined; - - /** - * Returns array of found indices by tag - */ - indexOfTag(): void; - - /** - * Concatenates packetlist or array of packets - */ - concat(): void; - - /** - * Allocate a new packetlist from structured packetlist clone - * See {@link https://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data} - * @param packetClone packetlist clone - * @returns new packetlist object with data from packetlist clone - */ - static fromStructuredClone(packetClone: object): object; - } - - class PublicKey { - /** - * Implementation of the Key Material Packet (Tag 5,6,7,14) - * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: - * A key material packet contains all the information about a public or - * private key. There are four variants of this packet type, and two - * major versions. - * A Public-Key packet starts a series of packets that forms an OpenPGP - * key (sometimes called an OpenPGP certificate). - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * Packet version - */ - version: Integer; - - /** - * Key creation date. - */ - created: Date; - - /** - * Public key algorithm. - */ - algorithm: string; - - /** - * Algorithm specific params - */ - params: object[]; - - /** - * Time until expiration in days (V3 only) - */ - expirationTimeV3: Integer; - - /** - * Fingerprint in lowercase hex - */ - fingerprint: string; - - /** - * Keyid - */ - keyid: type.keyid.Keyid; - - /** - * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} - * called by read_tag<num> - * @param bytes Input array to read the packet from - * @returns This object with attributes set by the parser - */ - read(bytes: Uint8Array): object; - - /** - * Alias of read() - * @see module:packet.PublicKey#read - */ - readPublicKey: any; - - /** - * Same as write_private_key, but has less information because of - * public key. - * @returns OpenPGP packet body contents, - */ - write(): Uint8Array; - - /** - * Alias of write() - * @see module:packet.PublicKey#write - */ - writePublicKey: any; - - /** - * Write an old version packet - it's used by some of the internal routines. - */ - writeOld(): void; - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns - */ - isDecrypted(): boolean | null; - - /** - * Returns the creation time of the key - * @returns - */ - getCreationTime(): Date; - - /** - * Calculates the key id of the key - * @returns A 8 byte key id - */ - getKeyId(): string; - - /** - * Calculates the fingerprint of the key - * @returns A Uint8Array containing the fingerprint - */ - getFingerprintBytes(): Uint8Array; - - /** - * Calculates the fingerprint of the key - * @returns A string containing the fingerprint in lowercase hex - */ - getFingerprint(): string; - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns Whether the two keys have the same version and public key data - */ - hasSameFingerprintAs(): boolean; - - /** - * Returns algorithm information - * @returns An object of the form {algorithm: string, bits:int, curve:String} - */ - getAlgorithmInfo(): object; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - } - - class PublicKeyEncryptedSessionKey { - /** - * Public-Key Encrypted Session Key Packets (Tag 1) - * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: - * A Public-Key Encrypted Session Key packet holds the session key - * used to encrypt a message. Zero or more Public-Key Encrypted Session Key - * packets and/or Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data Packet, which holds an encrypted message. The - * message is encrypted with the session key, and the session key is itself - * encrypted and stored in the Encrypted Session Key packet(s). The - * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted - * Session Key packet for each OpenPGP key to which the message is encrypted. - * The recipient of the message finds a session key that is encrypted to their - * public key, decrypts the session key, and then uses the session key to - * decrypt the message. - */ - constructor(); - - encrypted: any[]; - - /** - * Parsing function for a publickey encrypted session key packet (tag 1). - * @param input Payload of a tag 1 packet - * @param position Position to start reading from the input string - * @param len Length of the packet or the remaining length of - * input at position - * @returns Object representation - */ - read(input: Uint8Array, position: Integer, len: Integer): PublicKeyEncryptedSessionKey - - /** - * Create a string representation of a tag 1 packet - * @returns The Uint8Array representation - */ - write(): Uint8Array; - - /** - * Encrypt session key packet - * @param key Public key - * @returns - */ - encrypt(key: PublicKey): Promise; - - /** - * Decrypts the session key (only for public key encrypted session key - * packets (tag 1) - * @param key Private key with secret params unlocked - * @returns - */ - decrypt(key: SecretKey): Promise; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - } - - class PublicSubkey { - /** - * A Public-Subkey packet (tag 14) has exactly the same format as a - * Public-Key packet, but denotes a subkey. One or more subkeys may be - * associated with a top-level key. By convention, the top-level key - * provides signature services, and the subkeys provide encryption - * services. - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * Packet version - */ - version: Integer; - - /** - * Key creation date. - */ - created: Date; - - /** - * Public key algorithm. - */ - algorithm: string; - - /** - * Algorithm specific params - */ - params: object[]; - - /** - * Time until expiration in days (V3 only) - */ - expirationTimeV3: Integer; - - /** - * Fingerprint in lowercase hex - */ - fingerprint: string; - - /** - * Keyid - */ - keyid: type.keyid.Keyid; - - /** - * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} - * called by read_tag<num> - * @param bytes Input array to read the packet from - * @returns This object with attributes set by the parser - */ - read(bytes: Uint8Array): object; - - /** - * Alias of read() - * @see module:packet.PublicKey#read - */ - readPublicKey: any; - - /** - * Same as write_private_key, but has less information because of - * public key. - * @returns OpenPGP packet body contents, - */ - write(): Uint8Array; - - /** - * Alias of write() - * @see module:packet.PublicKey#write - */ - writePublicKey: any; - - /** - * Write an old version packet - it's used by some of the internal routines. - */ - writeOld(): void; - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns - */ - isDecrypted(): boolean | null; - - /** - * Returns the creation time of the key - * @returns - */ - getCreationTime(): Date; - - /** - * Calculates the key id of the key - * @returns A 8 byte key id - */ - getKeyId(): string; - - /** - * Calculates the fingerprint of the key - * @returns A Uint8Array containing the fingerprint - */ - getFingerprintBytes(): Uint8Array; - - /** - * Calculates the fingerprint of the key - * @returns A string containing the fingerprint in lowercase hex - */ - getFingerprint(): string; - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns Whether the two keys have the same version and public key data - */ - hasSameFingerprintAs(): boolean; - - /** - * Returns algorithm information - * @returns An object of the form {algorithm: string, bits:int, curve:String} - */ - getAlgorithmInfo(): object; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - } - - class SecretKey { - /** - * A Secret-Key packet contains all the information that is found in a - * Public-Key packet, including the public-key material, but also - * includes the secret-key material after all the public-key fields. - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * Encrypted secret-key data - */ - encrypted: any; - - /** - * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. - */ - isEncrypted: any; - - /** - * Internal parser for private keys as specified in - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} - * @param bytes Input string to read the packet from - */ - read(bytes: string): void; - - /** - * Creates an OpenPGP key packet for the given key. - * @returns A string of bytes containing the secret key OpenPGP packet - */ - write(): string; - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns - */ - isDecrypted(): boolean | null; - - /** - * Encrypt the payload. By default, we use aes256 and iterated, salted string - * to key specifier. If the key is in a decrypted state (isEncrypted === false) - * and the passphrase is empty or undefined, the key will be set as not encrypted. - * This can be used to remove passphrase protection after calling decrypt(). - * @param passphrase - * @returns - */ - encrypt(passphrase: string): Promise; - - /** - * Decrypts the private key params which are needed to use the key. - * {@link module:packet.SecretKey.isDecrypted} should be false, as - * otherwise calls to this function will throw an error. - * @param passphrase The passphrase for this private key as string - * @returns - */ - decrypt(passphrase: string): Promise; - - /** - * Clear private params, return to initial state - */ - clearPrivateParams(): void; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - - /** - * Packet version - */ - version: Integer; - - /** - * Key creation date. - */ - created: Date; - - /** - * Public key algorithm. - */ - algorithm: string; - - /** - * Algorithm specific params - */ - params: object[]; - - /** - * Time until expiration in days (V3 only) - */ - expirationTimeV3: Integer; - - /** - * Fingerprint in lowercase hex - */ - fingerprint: string; - - /** - * Keyid - */ - keyid: type.keyid.Keyid; - - /** - * Alias of read() - * @see module:packet.PublicKey#read - */ - readPublicKey: any; - - /** - * Alias of write() - * @see module:packet.PublicKey#write - */ - writePublicKey: any; - - /** - * Write an old version packet - it's used by some of the internal routines. - */ - writeOld(): void; - - /** - * Returns the creation time of the key - * @returns - */ - getCreationTime(): Date; - - /** - * Calculates the key id of the key - * @returns A 8 byte key id - */ - getKeyId(): string; - - /** - * Calculates the fingerprint of the key - * @returns A Uint8Array containing the fingerprint - */ - getFingerprintBytes(): Uint8Array; - - /** - * Calculates the fingerprint of the key - * @returns A string containing the fingerprint in lowercase hex - */ - getFingerprint(): string; - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns Whether the two keys have the same version and public key data - */ - hasSameFingerprintAs(): boolean; - - /** - * Returns algorithm information - * @returns An object of the form {algorithm: string, bits:int, curve:String} - */ - getAlgorithmInfo(): object; - } - - class SecretSubkey { - /** - * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret - * Key packet and has exactly the same format. - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * Encrypted secret-key data - */ - encrypted: any; - - /** - * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. - */ - isEncrypted: any; - - /** - * Internal parser for private keys as specified in - * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} - * @param bytes Input string to read the packet from - */ - read(bytes: string): void; - - /** - * Creates an OpenPGP key packet for the given key. - * @returns A string of bytes containing the secret key OpenPGP packet - */ - write(): string; - - /** - * Check whether secret-key data is available in decrypted form. Returns null for public keys. - * @returns - */ - isDecrypted(): boolean | null; - - /** - * Encrypt the payload. By default, we use aes256 and iterated, salted string - * to key specifier. If the key is in a decrypted state (isEncrypted === false) - * and the passphrase is empty or undefined, the key will be set as not encrypted. - * This can be used to remove passphrase protection after calling decrypt(). - * @param passphrase - * @returns - */ - encrypt(passphrase: string): Promise; - - /** - * Decrypts the private key params which are needed to use the key. - * {@link module:packet.SecretKey.isDecrypted} should be false, as - * otherwise calls to this function will throw an error. - * @param passphrase The passphrase for this private key as string - * @returns - */ - decrypt(passphrase: string): Promise; - - /** - * Clear private params, return to initial state - */ - clearPrivateParams(): void; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - - /** - * Packet version - */ - version: Integer; - - /** - * Key creation date. - */ - created: Date; - - /** - * Public key algorithm. - */ - algorithm: string; - - /** - * Algorithm specific params - */ - params: object[]; - - /** - * Time until expiration in days (V3 only) - */ - expirationTimeV3: Integer; - - /** - * Fingerprint in lowercase hex - */ - fingerprint: string; - - /** - * Keyid - */ - keyid: type.keyid.Keyid; - - /** - * Alias of read() - * @see module:packet.PublicKey#read - */ - readPublicKey: any; - - /** - * Alias of write() - * @see module:packet.PublicKey#write - */ - writePublicKey: any; - - /** - * Write an old version packet - it's used by some of the internal routines. - */ - writeOld(): void; - - /** - * Returns the creation time of the key - * @returns - */ - getCreationTime(): Date; - - /** - * Calculates the key id of the key - * @returns A 8 byte key id - */ - getKeyId(): string; - - /** - * Calculates the fingerprint of the key - * @returns A Uint8Array containing the fingerprint - */ - getFingerprintBytes(): Uint8Array; - - /** - * Calculates the fingerprint of the key - * @returns A string containing the fingerprint in lowercase hex - */ - getFingerprint(): string; - - /** - * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint - * @returns Whether the two keys have the same version and public key data - */ - hasSameFingerprintAs(): boolean; - - /** - * Returns algorithm information - * @returns An object of the form {algorithm: string, bits:int, curve:String} - */ - getAlgorithmInfo(): object; - } - - class Signature { - /** - * Implementation of the Signature Packet (Tag 2) - * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: - * A Signature packet describes a binding between some public key and - * some data. The most common signatures are a signature of a file or a - * block of text, and a signature that is a certification of a User ID. - * @param date the creation date of the signature - */ - constructor(date: Date); - - /** - * parsing function for a signature packet (tag 2). - * @param bytes payload of a tag 2 packet - * @param position position to start reading from the bytes string - * @param len length of the packet or the remaining length of bytes at position - * @returns object representation - */ - read(bytes: string, position: Integer, len: Integer): Signature; - - /** - * Signs provided data. This needs to be done prior to serialization. - * @param key private key used to sign the message. - * @param data Contains packets to be signed. - * @returns - */ - sign(key: SecretKey, data: object): Promise; - - /** - * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets - * @returns subpacket data - */ - write_hashed_sub_packets(): Uint8Array; - - /** - * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets - * @returns subpacket data - */ - write_unhashed_sub_packets(): Uint8Array; - - /** - * verifys the signature packet. Note: not signature types are implemented - * @param key the public key to verify the signature - * @param signatureType expected signature type - * @param data data which on the signature applies - * @returns True if message is verified, else false. - */ - verify(key: PublicSubkey | PublicKey | SecretSubkey | SecretKey, signatureType: enums.signature, data: string | object): Promise; - - /** - * Verifies signature expiration date - * @param date (optional) use the given date for verification instead of the current time - * @returns true if expired - */ - isExpired(date: Date): boolean; - - /** - * Returns the expiration time of the signature or Infinity if signature does not expire - * @returns expiration time - */ - getExpirationTime(): Date; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - } - - class SymEncryptedAEADProtected { - /** - * Implementation of the Symmetrically Encrypted Authenticated Encryption with - * Additional Data (AEAD) Protected Data Packet - * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: - * AEAD Protected Data Packet - */ - constructor(); - - /** - * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @param bytes - */ - read(bytes: Uint8Array | ReadableStream): void; - - /** - * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) - * @returns The encrypted payload - */ - write(): Uint8Array | ReadableStream; - - /** - * Decrypt the encrypted payload. - * @param sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' - * @param key The session key used to encrypt the payload - * @param streaming Whether the top-level function will return a stream - * @returns - */ - decrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): boolean; - - /** - * Encrypt the packet list payload. - * @param sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' - * @param key The session key used to encrypt the payload - * @param streaming Whether the top-level function will return a stream - */ - encrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): void; - - /** - * En/decrypt the payload. - * @param {encrypt | decrypt} fn Whether to encrypt or decrypt - * @param key The session key used to en/decrypt the payload - * @param data The data to en/decrypt - * @param streaming Whether the top-level function will return a stream - * @returns - */ - crypt(fn: any, key: Uint8Array, data: Uint8Array | ReadableStream, streaming: boolean): Uint8Array | ReadableStream; - } - - class SymEncryptedIntegrityProtected { - /** - * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) - * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: - * The Symmetrically Encrypted Integrity Protected Data packet is - * a variant of the Symmetrically Encrypted Data packet. It is a new feature - * created for OpenPGP that addresses the problem of detecting a modification to - * encrypted data. It is used in combination with a Modification Detection Code - * packet. - */ - constructor(); - - /** - * The encrypted payload. - */ - encrypted: any; - - /** - * If after decrypting the packet this is set to true, - * a modification has been detected and thus the contents - * should be discarded. - */ - modification: boolean; - - /** - * Encrypt the payload in the packet. - * @param sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' - * @param key The key of cipher blocksize length to be used - * @param streaming Whether to set this.encrypted to a stream - * @returns - */ - encrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): Promise; - - /** - * Decrypts the encrypted data contained in the packet. - * @param sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' - * @param key The key of cipher blocksize length to be used - * @param streaming Whether to read this.encrypted as a stream - * @returns - */ - decrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): Promise; - } - - class SymEncryptedSessionKey { - /** - * Public-Key Encrypted Session Key Packets (Tag 1) - * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: - * A Public-Key Encrypted Session Key packet holds the session key - * used to encrypt a message. Zero or more Public-Key Encrypted Session Key - * packets and/or Symmetric-Key Encrypted Session Key packets may precede a - * Symmetrically Encrypted Data Packet, which holds an encrypted message. The - * message is encrypted with the session key, and the session key is itself - * encrypted and stored in the Encrypted Session Key packet(s). The - * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted - * Session Key packet for each OpenPGP key to which the message is encrypted. - * The recipient of the message finds a session key that is encrypted to their - * public key, decrypts the session key, and then uses the session key to - * decrypt the message. - */ - constructor(); - - /** - * Parsing function for a symmetric encrypted session key packet (tag 3). - * @param input Payload of a tag 1 packet - * @param position Position to start reading from the input string - * @param len Length of the packet or the remaining length of - * input at position - * @returns Object representation - */ - read(input: Uint8Array, position: Integer, len: Integer): SymEncryptedSessionKey; - - /** - * Decrypts the session key - * @param passphrase The passphrase in string form - * @returns - */ - decrypt(passphrase: string): Promise; - - /** - * Encrypts the session key - * @param passphrase The passphrase in string form - * @returns - */ - encrypt(passphrase: string): Promise; - - /** - * Fix custom types after cloning - */ - postCloneTypeFix(): void; - } - - class SymmetricallyEncrypted { - /** - * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) - * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: - * The Symmetrically Encrypted Data packet contains data encrypted with a - * symmetric-key algorithm. When it has been decrypted, it contains other - * packets (usually a literal data packet or compressed data packet, but in - * theory other Symmetrically Encrypted Data packets or sequences of packets - * that form whole OpenPGP messages). - */ - constructor(); - - /** - * Packet type - */ - tag: enums.packet; - - /** - * Encrypted secret-key data - */ - encrypted: any; - - /** - * Decrypted packets contained within. - */ - packets: List; - - /** - * When true, decrypt fails if message is not integrity protected - * @see module:config.ignore_mdc_error - */ - ignore_mdc_error: any; - - /** - * Decrypt the symmetrically-encrypted packet data - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param sessionKeyAlgorithm Symmetric key algorithm to use - * @param key The key of cipher blocksize length to be used - * @returns - */ - decrypt(sessionKeyAlgorithm: enums.symmetric, key: Uint8Array): Promise; - - /** - * Encrypt the symmetrically-encrypted packet data - * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. - * @param sessionKeyAlgorithm Symmetric key algorithm to use - * @param key The key of cipher blocksize length to be used - * @returns - */ - encrypt(sessionKeyAlgorithm: enums.symmetric, key: Uint8Array): Promise; - } - - class Trust { - /** - * Implementation of the Trust Packet (Tag 12) - * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: - * The Trust packet is used only within keyrings and is not normally - * exported. Trust packets contain data that record the user's - * specifications of which key holders are trustworthy introducers, - * along with other information that implementing software uses for - * trust information. The format of Trust packets is defined by a given - * implementation. - * Trust packets SHOULD NOT be emitted to output streams that are - * transferred to other users, and they SHOULD be ignored on any input - * other than local keyring files. - */ - constructor(); - - /** - * Parsing function for a trust packet (tag 12). - * Currently not implemented as we ignore trust packets - * @param byptes payload of a tag 12 packet - */ - read(byptes: string): void; - } - - class UserAttribute { - /** - * Implementation of the User Attribute Packet (Tag 17) - * The User Attribute packet is a variation of the User ID packet. It - * is capable of storing more types of data than the User ID packet, - * which is limited to text. Like the User ID packet, a User Attribute - * packet may be certified by the key owner ("self-signed") or any other - * key owner who cares to certify it. Except as noted, a User Attribute - * packet may be used anywhere that a User ID packet may be used. - * While User Attribute packets are not a required part of the OpenPGP - * standard, implementations SHOULD provide at least enough - * compatibility to properly handle a certification signature on the - * User Attribute packet. A simple way to do this is by treating the - * User Attribute packet as a User ID packet with opaque contents, but - * an implementation may use any method desired. - */ - constructor(); - - /** - * parsing function for a user attribute packet (tag 17). - * @param input payload of a tag 17 packet - */ - read(input: Uint8Array): void; - - /** - * Creates a binary representation of the user attribute packet - * @returns string representation - */ - write(): Uint8Array; - - /** - * Compare for equality - * @param usrAttr - * @returns true if equal - */ - equals(usrAttr: UserAttribute): boolean; - } - - class Userid { - /** - * Implementation of the User ID Packet (Tag 13) - * A User ID packet consists of UTF-8 text that is intended to represent - * the name and email address of the key holder. By convention, it - * includes an RFC 2822 [RFC2822] mail name-addr, but there are no - * restrictions on its content. The packet length in the header - * specifies the length of the User ID. - */ - constructor(); - - /** - * A string containing the user id. Usually in the form - * John Doe - */ - userid: string; - - /** - * Parsing function for a user id packet (tag 13). - * @param input payload of a tag 13 packet - */ - read(input: Uint8Array): void; - - /** - * Parse userid string, e.g. 'John Doe ' - */ - parse(): void; - - /** - * Creates a binary representation of the user id packet - * @returns binary representation - */ - write(): Uint8Array; - - /** - * Set userid string from object, e.g. { name:'Phil Zimmermann', email:'phil@openpgp.org' } - */ - format(): void; - } - - namespace all_packets { - /** - * @see module:packet.Compressed - */ - var Compressed: any; - - /** - * @see module:packet.SymEncryptedIntegrityProtected - */ - var SymEncryptedIntegrityProtected: any; - - /** - * @see module:packet.SymEncryptedAEADProtected - */ - var SymEncryptedAEADProtected: any; - - /** - * @see module:packet.PublicKeyEncryptedSessionKey - */ - var PublicKeyEncryptedSessionKey: any; - - /** - * @see module:packet.SymEncryptedSessionKey - */ - var SymEncryptedSessionKey: any; - - /** - * @see module:packet.Literal - */ - var Literal: any; - - /** - * @see module:packet.PublicKey - */ - var PublicKey: any; - - /** - * @see module:packet.SymmetricallyEncrypted - */ - var SymmetricallyEncrypted: any; - - /** - * @see module:packet.Marker - */ - var Marker: any; - - /** - * @see module:packet.PublicSubkey - */ - var PublicSubkey: any; - - /** - * @see module:packet.UserAttribute - */ - var UserAttribute: any; - - /** - * @see module:packet.OnePassSignature - */ - var OnePassSignature: any; - - /** - * @see module:packet.SecretKey - */ - var SecretKey: any; - - /** - * @see module:packet.Userid - */ - var Userid: any; - - /** - * @see module:packet.SecretSubkey - */ - var SecretSubkey: any; - - /** - * @see module:packet.Signature - */ - var Signature: any; - - /** - * @see module:packet.Trust - */ - var Trust: any; - } - - namespace clone { - /** - * Create a packetlist from the correspoding object types. - * @param options the object passed to and from the web worker - * @returns a mutated version of the options optject - */ - function clonePackets(options: object): object; - - /** - * Creates an object with the correct prototype from a corresponding packetlist. - * @param options the object passed to and from the web worker - * @param method the public api function name to be delegated to the worker - * @returns a mutated version of the options optject - */ - function parseClonedPackets(options: object, method: string): object; - } - - namespace packet { - /** - * Encodes a given integer of length to the openpgp length specifier to a - * string - * @param length The length to encode - * @returns String with openpgp length representation - */ - function writeSimpleLength(length: Integer): Uint8Array; - - /** - * Writes a packet header version 4 with the given tag_type and length to a - * string - * @param tag_type Tag type - * @param length Length of the payload - * @returns String of the header - */ - function writeHeader(tag_type: Integer, length: Integer): string; - - /** - * Writes a packet header Version 3 with the given tag_type and length to a - * string - * @param tag_type Tag type - * @param length Length of the payload - * @returns String of the header - */ - function writeOldHeader(tag_type: Integer, length: Integer): string; - - /** - * Whether the packet type supports partial lengths per RFC4880 - * @param tag_type Tag type - * @returns String of the header - */ - function supportsStreaming(tag_type: Integer): boolean; - - /** - * Generic static Packet Parser function - * @param input Input stream as string - * @param callback Function to call with the parsed packet - * @returns Returns false if the stream was empty and parsing is done, and true otherwise. - */ - function read(input: Uint8Array | ReadableStream, callback: Function): boolean; - } + function writeHeader(tag_type: Integer, length: Integer): string; + + /** + * Writes a packet header Version 3 with the given tag_type and length to a + * string + * @param tag_type Tag type + * @param length Length of the payload + * @returns String of the header + */ + function writeOldHeader(tag_type: Integer, length: Integer): string; + + /** + * Whether the packet type supports partial lengths per RFC4880 + * @param tag_type Tag type + * @returns String of the header + */ + function supportsStreaming(tag_type: Integer): boolean; + + /** + * Generic static Packet Parser function + * @param input Input stream as string + * @param callback Function to call with the parsed packet + * @returns Returns false if the stream was empty and parsing is done, and true otherwise. + */ + function read(input: Uint8Array | ReadableStream, callback: Function): boolean; } +} - namespace polyfills { - } +export namespace polyfills { +} - namespace signature { - /** - * Class that represents an OpenPGP signature. - */ - class Signature { - /** - * @param packetlist The signature packets - */ - constructor(packetlist: packet.List); - - /** - * Returns ASCII armored text of signature - * @returns ASCII armor - */ - armor(): ReadableStream; - } - - /** - * reads an OpenPGP armored signature and returns a signature object - * @param armoredText text to be parsed - * @returns new signature object - */ - function readArmored(armoredText: string | ReadableStream): Signature; - - /** - * reads an OpenPGP signature as byte array and returns a signature object - * @param input binary signature - * @returns new signature object - */ - function read(input: Uint8Array | ReadableStream): Signature; - } - - namespace type { - /** - * Encoded symmetric key for ECDH - */ - namespace ecdh_symkey { - class ECDHSymmetricKey { - constructor(); - - /** - * Read an ECDHSymmetricKey from an Uint8Array - * @param input Where to read the encoded symmetric key from - * @returns Number of read bytes - */ - read(input: Uint8Array): number; - - /** - * Write an ECDHSymmetricKey as an Uint8Array - * @returns An array containing the value - */ - write(): Uint8Array; - } - } - - /** - * Implementation of type KDF parameters - * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: - * A key derivation function (KDF) is necessary to implement the EC - * encryption. The Concatenation Key Derivation Function (Approved - * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is - * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. - */ - namespace kdf_params { - class KDFParams { - /** - * @param hash Hash algorithm - * @param cipher Symmetric algorithm - */ - constructor(hash: enums.hash, cipher: enums.symmetric); - - /** - * Read KDFParams from an Uint8Array - * @param input Where to read the KDFParams from - * @returns Number of read bytes - */ - read(input: Uint8Array): number; - - /** - * Write KDFParams to an Uint8Array - * @returns Array with the KDFParams value - */ - write(): Uint8Array; - } - } - - /** - * Implementation of type key id - * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: - * A Key ID is an eight-octet scalar that identifies a key. - * Implementations SHOULD NOT assume that Key IDs are unique. The - * section "Enhanced Key Formats" below describes how Key IDs are - * formed. - */ - namespace keyid { - class Keyid { - constructor(); - - /** - * Parsing method for a key id - * @param input Input to read the key id from - */ - read(input: Uint8Array): void; - - /** - * Checks equality of Key ID's - * @param keyid - * @param matchWildcard Indicates whether to check if either keyid is a wildcard - */ - equals(keyid: Keyid, matchWildcard: boolean): void; - } - } - - /** - * Implementation of type MPI ( {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2}) - * Multiprecision integers (also called MPIs) are unsigned integers used - * to hold large integers such as the ones used in cryptographic - * calculations. - * An MPI consists of two pieces: a two-octet scalar that is the length - * of the MPI in bits followed by a string of octets that contain the - * actual integer. - */ - namespace mpi { - class MPI { - constructor(); - - /** - * Parsing function for a MPI ( {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC 4880 3.2}). - * @param input Payload of MPI data - * @param endian Endianness of the data; 'be' for big-endian or 'le' for little-endian - * @returns Length of data read - */ - read(input: Uint8Array, endian: string): Integer; - - /** - * Converts the mpi object to a bytes as specified in - * {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2} - * @param endian Endianness of the payload; 'be' for big-endian or 'le' for little-endian - * @param length Length of the data part of the MPI - * @returns mpi Byte representation - */ - write(endian: string, length: Integer): Uint8Array; - } - } - - /** - * Wrapper to an OID value - * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}: - * The sequence of octets in the third column is the result of applying - * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier - * with subsequent truncation. The truncation removes the two fields of - * encoded Object Identifier. The first omitted field is one octet - * representing the Object Identifier tag, and the second omitted field - * is the length of the Object Identifier body. For example, the - * complete ASN.1 DER encoding for the NIST P-256 curve OID is "06 08 2A - * 86 48 CE 3D 03 01 07", from which the first entry in the table above - * is constructed by omitting the first two octets. Only the truncated - * sequence of octets is the valid representation of a curve OID. - */ - namespace oid { - class OID { - constructor(); - - /** - * Method to read an OID object - * @param input Where to read the OID from - * @returns Number of read bytes - */ - read(input: Uint8Array): number; - - /** - * Serialize an OID object - * @returns Array with the serialized value the OID - */ - write(): Uint8Array; - - /** - * Serialize an OID object as a hex string - * @returns String with the hex value of the OID - */ - toHex(): string; - - /** - * If a known curve object identifier, return the canonical name of the curve - * @returns String with the canonical name of the curve - */ - getName(): string; - } - } - - /** - * Implementation of the String-to-key specifier - * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}: - * String-to-key (S2K) specifiers are used to convert passphrase strings - * into symmetric-key encryption/decryption keys. They are used in two - * places, currently: to encrypt the secret part of private keys in the - * private keyring, and to convert passphrases to encryption keys for - * symmetrically encrypted messages. +export namespace signature { + /** + * Class that represents an OpenPGP signature. */ - namespace s2k { - class S2K { - constructor(); + class Signature { + /** + * @param packetlist The signature packets + */ + constructor(packetlist: packet.List); - algorithm: enums.hash; + /** + * Returns ASCII armored text of signature + * @returns ASCII armor + */ + armor(): ReadableStream; - type: enums.s2k; + packets: packet.List; + } - c: Integer; + /** + * reads an OpenPGP armored signature and returns a signature object + * @param armoredText text to be parsed + * @returns new signature object + */ + function readArmored(armoredText: string | ReadableStream): Signature; - /** - * Eight bytes of salt in a binary string. - */ - salt: string; + /** + * reads an OpenPGP signature as byte array and returns a signature object + * @param input binary signature + * @returns new signature object + */ + function read(input: Uint8Array | ReadableStream): Signature; +} - /** - * Parsing function for a string-to-key specifier ( {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). - * @param input Payload of string-to-key specifier - * @returns Actual length of the object - */ - read(input: string): Integer; +export namespace type { + /** + * Encoded symmetric key for ECDH + */ + namespace ecdh_symkey { + class ECDHSymmetricKey { + constructor(); - /** - * Serializes s2k information - * @returns binary representation of s2k - */ - write(): Uint8Array; + /** + * Read an ECDHSymmetricKey from an Uint8Array + * @param input Where to read the encoded symmetric key from + * @returns Number of read bytes + */ + read(input: Uint8Array): number; - /** - * Produces a key using the specified passphrase and the defined - * hashAlgorithm - * @param passphrase Passphrase containing user input - * @returns Produced key with a length corresponding to - * hashAlgorithm hash length - */ - produce_key(passphrase: string): Uint8Array; - } + /** + * Write an ECDHSymmetricKey as an Uint8Array + * @returns An array containing the value + */ + write(): Uint8Array; } } /** - * This object contains utility functions + * Implementation of type KDF parameters + * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: + * A key derivation function (KDF) is necessary to implement the EC + * encryption. The Concatenation Key Derivation Function (Approved + * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is + * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. */ - namespace util { - /** - * Get transferable objects to pass buffers with zero copy (similar to "pass by reference" in C++) - * See: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage - * Also, convert ReadableStreams to MessagePorts - * @param obj the options object to be passed to the web worker - * @returns an array of binary data to be passed - */ - function getTransferables(obj: object): any[]; + namespace kdf_params { + class KDFParams { + /** + * @param hash Hash algorithm + * @param cipher Symmetric algorithm + */ + constructor(hash: enums.hash, cipher: enums.symmetric); - /** - * Convert MessagePorts back to ReadableStreams - * @param obj - * @returns - */ - function restoreStreams(obj: object): object; + /** + * Read KDFParams from an Uint8Array + * @param input Where to read the KDFParams from + * @returns Number of read bytes + */ + read(input: Uint8Array): number; - /** - * Create hex string from a binary - * @param str String to convert - * @returns String containing the hexadecimal values - */ - function str_to_hex(str: string): string; - - /** - * Create binary string from a hex encoded string - * @param str Hex string to convert - * @returns - */ - function hex_to_str(str: string): string; - - /** - * Convert a Uint8Array to an MPI-formatted Uint8Array. - * Note: the output is **not** an MPI object. - * @see - * @see - * @param bin An array of 8-bit integers to convert - * @returns MPI-formatted Uint8Array - */ - function Uint8Array_to_MPI(bin: Uint8Array): Uint8Array; - - /** - * Convert a Base-64 encoded string an array of 8-bit integer - * Note: accepts both Radix-64 and URL-safe strings - * @param base64 Base-64 encoded string to convert - * @returns An array of 8-bit integers - */ - function b64_to_Uint8Array(base64: string): Uint8Array; - - /** - * Convert an array of 8-bit integer to a Base-64 encoded string - * @param bytes An array of 8-bit integers to convert - * @param url If true, output is URL-safe - * @returns Base-64 encoded string - */ - function Uint8Array_to_b64(bytes: Uint8Array, url: boolean): string; - - /** - * Convert a hex string to an array of 8-bit integers - * @param hex A hex string to convert - * @returns An array of 8-bit integers - */ - function hex_to_Uint8Array(hex: string): Uint8Array; - - /** - * Convert an array of 8-bit integers to a hex string - * @param bytes Array of 8-bit integers to convert - * @returns Hexadecimal representation of the array - */ - function Uint8Array_to_hex(bytes: Uint8Array): string; - - /** - * Convert a string to an array of 8-bit integers - * @param str String to convert - * @returns An array of 8-bit integers - */ - function str_to_Uint8Array(str: string): Uint8Array; - - /** - * Convert an array of 8-bit integers to a string - * @param bytes An array of 8-bit integers to convert - * @returns String representation of the array - */ - function Uint8Array_to_str(bytes: Uint8Array): string; - - /** - * Convert a native javascript string to a Uint8Array of utf8 bytes - * @param str The string to convert - * @returns A valid squence of utf8 bytes - */ - function encode_utf8(str: string | ReadableStream): Uint8Array | ReadableStream; - - /** - * Convert a Uint8Array of utf8 bytes to a native javascript string - * @param utf8 A valid squence of utf8 bytes - * @returns A native javascript string - */ - function decode_utf8(utf8: Uint8Array | ReadableStream): string | ReadableStream; - - /** - * Concat a list of Uint8Arrays, Strings or Streams - * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams. - * @param Array of Uint8Arrays/Strings/Streams to concatenate - * @returns Concatenated array - */ - var concat: any; - - /** - * Concat Uint8Arrays - * @param Array of Uint8Arrays to concatenate - * @returns Concatenated array - */ - var concatUint8Array: any; - - /** - * Check Uint8Array equality - * @param first array - * @param second array - * @returns equality - */ - function equalsUint8Array(first: Uint8Array, second: Uint8Array): boolean; - - /** - * Calculates a 16bit sum of a Uint8Array by adding each character - * codes modulus 65535 - * @param Uint8Array to create a sum of - * @returns 2 bytes containing the sum of all charcodes % 65535 - */ - function write_checksum(Uint8Array: Uint8Array): Uint8Array; - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug(str: string): void; - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug_hexarray_dump(str: string): void; - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug_hexstr_dump(str: string): void; - - /** - * Helper function to print a debug error. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug_error(str: string): void; - - /** - * Read a stream to the end and print it to the console when it's closed. - * @param str String of the debug message - * @param input Stream to print - * @param concat Function to concatenate chunks of the stream (defaults to util.concat). - */ - function print_entire_stream(str: string, input: ReadableStream | Uint8Array | string, concat: Function): void; - - /** - * If S[1] == 0, then double(S) == (S[2..128] || 0); - * otherwise, double(S) == (S[2..128] || 0) xor - * (zeros(120) || 10000111). - * Both OCB and EAX (through CMAC) require this function to be constant-time. - * @param data - */ - /* Illegal function name 'double' can't be used here - function double(data: Uint8Array): void; - */ - - /** - * Shift a Uint8Array to the right by n bits - * @param array The array to shift - * @param bits Amount of bits to shift (MUST be smaller - * than 8) - * @returns Resulting array. - */ - function shiftRight(array: Uint8Array, bits: Integer): string; - - /** - * Get native Web Cryptography api, only the current version of the spec. - * The default configuration is to use the api when available. But it can - * be deactivated with config.use_native - * @returns The SubtleCrypto api or 'undefined' - */ - function getWebCrypto(): object; - - /** - * Get native Web Cryptography api for all browsers, including legacy - * implementations of the spec e.g IE11 and Safari 8/9. The default - * configuration is to use the api when available. But it can be deactivated - * with config.use_native - * @returns The SubtleCrypto api or 'undefined' - */ - function getWebCryptoAll(): object; - - /** - * Detect Node.js runtime. - */ - function detectNode(): void; - - /** - * Get native Node.js module - * @param The module to require - * @returns The required module or 'undefined' - */ - function nodeRequire(The: string): object; - - /** - * Get native Node.js crypto api. The default configuration is to use - * the api when available. But it can also be deactivated with config.use_native - * @returns The crypto module or 'undefined' - */ - function getNodeCrypto(): object; - - /** - * Get native Node.js Buffer constructor. This should be used since - * Buffer is not available under browserify. - * @returns The Buffer constructor or 'undefined' - */ - function getNodeBuffer(): Function; - - /** - * Format user id for internal use. - */ - function formatUserId(): void; - - /** - * Parse user id. - */ - function parseUserId(): void; - - /** - * Normalize line endings to \r\n - */ - function canonicalizeEOL(): void; - - /** - * Convert line endings from canonicalized \r\n to native \n - */ - function nativeEOL(): void; - - /** - * Remove trailing spaces and tabs from each line - */ - function removeTrailingSpaces(): void; - - /** - * Encode input buffer using Z-Base32 encoding. - * See: https://tools.ietf.org/html/rfc6189#section-5.1.6 - * @param data The binary data to encode - * @returns Binary data encoded using Z-Base32 - */ - function encodeZBase32(data: Uint8Array): string; + /** + * Write KDFParams to an Uint8Array + * @returns Array with the KDFParams value + */ + write(): Uint8Array; + } } - namespace wkd { - class WKD { - /** - * Initialize the WKD client - */ + /** + * Implementation of type key id + * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: + * A Key ID is an eight-octet scalar that identifies a key. + * Implementations SHOULD NOT assume that Key IDs are unique. The + * section "Enhanced Key Formats" below describes how Key IDs are + * formed. + */ + namespace keyid { + class Keyid { constructor(); /** - * Search for a public key using Web Key Directory protocol. - * @param options.email User's email. - * @param options.rawBytes Returns Uint8Array instead of parsed key. - * @returns The public key. + * Parsing method for a key id + * @param input Input to read the key id from */ - lookup(): Promise, err: Array | null }>; + read(input: Uint8Array): void; + + /** + * Checks equality of Key ID's + * @param keyid + * @param matchWildcard Indicates whether to check if either keyid is a wildcard + */ + equals(keyid: Keyid, matchWildcard: boolean): void; } } - namespace worker { - /** - * @see module:openpgp.initWorker - * @see module:openpgp.getWorker - * @see module:openpgp.destroyWorker - * @see module:worker/worker + /** + * Implementation of type MPI ( {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2}) + * Multiprecision integers (also called MPIs) are unsigned integers used + * to hold large integers such as the ones used in cryptographic + * calculations. + * An MPI consists of two pieces: a two-octet scalar that is the length + * of the MPI in bits followed by a string of octets that contain the + * actual integer. */ - namespace async_proxy { - class AsyncProxy { - /** - * Initializes a new proxy and loads the web worker - * @param path The path to the worker or 'openpgp.worker.js' by default - * @param n number of workers to initialize if path given - * @param config config The worker configuration - * @param worker alternative to path parameter: web worker initialized with 'openpgp.worker.js' - */ - constructor(path: string, n: number, config: object, worker: any[]); + namespace mpi { + class MPI { + constructor(); - /** - * Message handling - */ - handleMessage(): void; + /** + * Parsing function for a MPI ( {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC 4880 3.2}). + * @param input Payload of MPI data + * @param endian Endianness of the data; 'be' for big-endian or 'le' for little-endian + * @returns Length of data read + */ + read(input: Uint8Array, endian: string): Integer; - /** - * Get new request ID - * @returns New unique request ID - */ - getID(): Integer; - - /** - * Send message to worker with random data - * @param size Number of bytes to send - */ - seedRandom(size: Integer): void; - - /** - * Terminates the workers - */ - terminate(): void; - - /** - * Generic proxy function that handles all commands from the public api. - * @param method the public api function to be delegated to the worker thread - * @param options the api function's options - * @returns see the corresponding public api functions for their return types - */ - delegate(method: string, options: object): Promise; - } + /** + * Converts the mpi object to a bytes as specified in + * {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2} + * @param endian Endianness of the payload; 'be' for big-endian or 'le' for little-endian + * @param length Length of the data part of the MPI + * @returns mpi Byte representation + */ + write(endian: string, length: Integer): Uint8Array; } + } + + /** + * Wrapper to an OID value + * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}: + * The sequence of octets in the third column is the result of applying + * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier + * with subsequent truncation. The truncation removes the two fields of + * encoded Object Identifier. The first omitted field is one octet + * representing the Object Identifier tag, and the second omitted field + * is the length of the Object Identifier body. For example, the + * complete ASN.1 DER encoding for the NIST P-256 curve OID is "06 08 2A + * 86 48 CE 3D 03 01 07", from which the first entry in the table above + * is constructed by omitting the first two octets. Only the truncated + * sequence of octets is the valid representation of a curve OID. + */ + namespace oid { + class OID { + constructor(); + + /** + * Method to read an OID object + * @param input Where to read the OID from + * @returns Number of read bytes + */ + read(input: Uint8Array): number; + + /** + * Serialize an OID object + * @returns Array with the serialized value the OID + */ + write(): Uint8Array; + + /** + * Serialize an OID object as a hex string + * @returns String with the hex value of the OID + */ + toHex(): string; + + /** + * If a known curve object identifier, return the canonical name of the curve + * @returns String with the canonical name of the curve + */ + getName(): string; + } + } + + /** + * Implementation of the String-to-key specifier + * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}: + * String-to-key (S2K) specifiers are used to convert passphrase strings + * into symmetric-key encryption/decryption keys. They are used in two + * places, currently: to encrypt the secret part of private keys in the + * private keyring, and to convert passphrases to encryption keys for + * symmetrically encrypted messages. + */ + namespace s2k { + class S2K { + constructor(); + + algorithm: enums.hash; + + type: enums.s2k; + + c: Integer; + + /** + * Eight bytes of salt in a binary string. + */ + salt: string; + + /** + * Parsing function for a string-to-key specifier ( {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). + * @param input Payload of string-to-key specifier + * @returns Actual length of the object + */ + read(input: string): Integer; + + /** + * Serializes s2k information + * @returns binary representation of s2k + */ + write(): Uint8Array; + + /** + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param passphrase Passphrase containing user input + * @returns Produced key with a length corresponding to + * hashAlgorithm hash length + */ + produce_key(passphrase: string): Uint8Array; + } + } +} + +/** + * This object contains utility functions + */ +export namespace util { + /** + * Get transferable objects to pass buffers with zero copy (similar to "pass by reference" in C++) + * See: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage + * Also, convert ReadableStreams to MessagePorts + * @param obj the options object to be passed to the web worker + * @returns an array of binary data to be passed + */ + function getTransferables(obj: object): any[]; + + /** + * Convert MessagePorts back to ReadableStreams + * @param obj + * @returns + */ + function restoreStreams(obj: object): object; + + /** + * Create hex string from a binary + * @param str String to convert + * @returns String containing the hexadecimal values + */ + function str_to_hex(str: string): string; + + /** + * Create binary string from a hex encoded string + * @param str Hex string to convert + * @returns + */ + function hex_to_str(str: string): string; + + /** + * Convert a Uint8Array to an MPI-formatted Uint8Array. + * Note: the output is **not** an MPI object. + * @see + * @see + * @param bin An array of 8-bit integers to convert + * @returns MPI-formatted Uint8Array + */ + function Uint8Array_to_MPI(bin: Uint8Array): Uint8Array; + + /** + * Convert a Base-64 encoded string an array of 8-bit integer + * Note: accepts both Radix-64 and URL-safe strings + * @param base64 Base-64 encoded string to convert + * @returns An array of 8-bit integers + */ + function b64_to_Uint8Array(base64: string): Uint8Array; + + /** + * Convert an array of 8-bit integer to a Base-64 encoded string + * @param bytes An array of 8-bit integers to convert + * @param url If true, output is URL-safe + * @returns Base-64 encoded string + */ + function Uint8Array_to_b64(bytes: Uint8Array, url: boolean): string; + + /** + * Convert a hex string to an array of 8-bit integers + * @param hex A hex string to convert + * @returns An array of 8-bit integers + */ + function hex_to_Uint8Array(hex: string): Uint8Array; + + /** + * Convert an array of 8-bit integers to a hex string + * @param bytes Array of 8-bit integers to convert + * @returns Hexadecimal representation of the array + */ + function Uint8Array_to_hex(bytes: Uint8Array): string; + + /** + * Convert a string to an array of 8-bit integers + * @param str String to convert + * @returns An array of 8-bit integers + */ + function str_to_Uint8Array(str: string): Uint8Array; + + /** + * Convert an array of 8-bit integers to a string + * @param bytes An array of 8-bit integers to convert + * @returns String representation of the array + */ + function Uint8Array_to_str(bytes: Uint8Array): string; + + /** + * Convert a native javascript string to a Uint8Array of utf8 bytes + * @param str The string to convert + * @returns A valid squence of utf8 bytes + */ + function encode_utf8(str: string | ReadableStream): Uint8Array | ReadableStream; + + /** + * Convert a Uint8Array of utf8 bytes to a native javascript string + * @param utf8 A valid squence of utf8 bytes + * @returns A native javascript string + */ + function decode_utf8(utf8: Uint8Array | ReadableStream): string | ReadableStream; + + /** + * Concat a list of Uint8Arrays, Strings or Streams + * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams. + * @param Array of Uint8Arrays/Strings/Streams to concatenate + * @returns Concatenated array + */ + var concat: any; + + /** + * Concat Uint8Arrays + * @param Array of Uint8Arrays to concatenate + * @returns Concatenated array + */ + var concatUint8Array: any; + + /** + * Check Uint8Array equality + * @param first array + * @param second array + * @returns equality + */ + function equalsUint8Array(first: Uint8Array, second: Uint8Array): boolean; + + /** + * Calculates a 16bit sum of a Uint8Array by adding each character + * codes modulus 65535 + * @param Uint8Array to create a sum of + * @returns 2 bytes containing the sum of all charcodes % 65535 + */ + function write_checksum(Uint8Array: Uint8Array): Uint8Array; + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug(str: string): void; + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug_hexarray_dump(str: string): void; + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug_hexstr_dump(str: string): void; + + /** + * Helper function to print a debug error. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug_error(str: string): void; + + /** + * Read a stream to the end and print it to the console when it's closed. + * @param str String of the debug message + * @param input Stream to print + * @param concat Function to concatenate chunks of the stream (defaults to util.concat). + */ + function print_entire_stream(str: string, input: ReadableStream | Uint8Array | string, concat: Function): void; + + /** + * If S[1] == 0, then double(S) == (S[2..128] || 0); + * otherwise, double(S) == (S[2..128] || 0) xor + * (zeros(120) || 10000111). + * Both OCB and EAX (through CMAC) require this function to be constant-time. + * @param data + */ + /* Illegal function name 'double' can't be used here + function double(data: Uint8Array): void; + */ + + /** + * Shift a Uint8Array to the right by n bits + * @param array The array to shift + * @param bits Amount of bits to shift (MUST be smaller + * than 8) + * @returns Resulting array. + */ + function shiftRight(array: Uint8Array, bits: Integer): string; + + /** + * Get native Web Cryptography api, only the current version of the spec. + * The default configuration is to use the api when available. But it can + * be deactivated with config.use_native + * @returns The SubtleCrypto api or 'undefined' + */ + function getWebCrypto(): object; + + /** + * Get native Web Cryptography api for all browsers, including legacy + * implementations of the spec e.g IE11 and Safari 8/9. The default + * configuration is to use the api when available. But it can be deactivated + * with config.use_native + * @returns The SubtleCrypto api or 'undefined' + */ + function getWebCryptoAll(): object; + + /** + * Detect Node.js runtime. + */ + function detectNode(): void; + + /** + * Get native Node.js module + * @param The module to require + * @returns The required module or 'undefined' + */ + function nodeRequire(The: string): object; + + /** + * Get native Node.js crypto api. The default configuration is to use + * the api when available. But it can also be deactivated with config.use_native + * @returns The crypto module or 'undefined' + */ + function getNodeCrypto(): object; + + /** + * Get native Node.js Buffer constructor. This should be used since + * Buffer is not available under browserify. + * @returns The Buffer constructor or 'undefined' + */ + function getNodeBuffer(): Function; + + /** + * Format user id for internal use. + */ + function formatUserId(): void; + + /** + * Parse user id. + */ + function parseUserId(): void; + + /** + * Normalize line endings to \r\n + */ + function canonicalizeEOL(): void; + + /** + * Convert line endings from canonicalized \r\n to native \n + */ + function nativeEOL(): void; + + /** + * Remove trailing spaces and tabs from each line + */ + function removeTrailingSpaces(): void; + + /** + * Encode input buffer using Z-Base32 encoding. + * See: https://tools.ietf.org/html/rfc6189#section-5.1.6 + * @param data The binary data to encode + * @returns Binary data encoded using Z-Base32 + */ + function encodeZBase32(data: Uint8Array): string; +} + +export namespace wkd { + class WKD { + /** + * Initialize the WKD client + */ + constructor(); /** - * @see module:openpgp.initWorker - * @see module:openpgp.getWorker - * @see module:openpgp.destroyWorker - * @see module:worker/async_proxy - */ - namespace worker { + * Search for a public key using Web Key Directory protocol. + * @param options.email User's email. + * @param options.rawBytes Returns Uint8Array instead of parsed key. + * @returns The public key. + */ + lookup(): Promise, err: Array | null }>; + } +} + +export namespace worker { + /** + * @see module:openpgp.initWorker + * @see module:openpgp.getWorker + * @see module:openpgp.destroyWorker + * @see module:worker/worker + */ + namespace async_proxy { + class AsyncProxy { /** - * Handle random buffer exhaustion by requesting more random bytes from the main window - * @returns Empty Promise whose resolution indicates that the buffer has been refilled + * Initializes a new proxy and loads the web worker + * @param path The path to the worker or 'openpgp.worker.js' by default + * @param n number of workers to initialize if path given + * @param config config The worker configuration + * @param worker alternative to path parameter: web worker initialized with 'openpgp.worker.js' */ - function randomCallback(): Promise; + constructor(path: string, n: number, config: object, worker: any[]); /** - * Set config from main context to worker context. - * @param config The openpgp configuration + * Message handling */ - function configure(config: object): void; + handleMessage(): void; /** - * Seed the library with entropy gathered window.crypto.getRandomValues - * as this api is only avalible in the main window. - * @param buffer Some random bytes + * Get new request ID + * @returns New unique request ID */ - function seedRandom(buffer: any[]): void; + getID(): Integer; + + /** + * Send message to worker with random data + * @param size Number of bytes to send + */ + seedRandom(size: Integer): void; + + /** + * Terminates the workers + */ + terminate(): void; /** * Generic proxy function that handles all commands from the public api. - * @param method The public api function to be delegated to the worker thread - * @param options The api function's options + * @param method the public api function to be delegated to the worker thread + * @param options the api function's options + * @returns see the corresponding public api functions for their return types */ - function delegate(method: string, options: object): void; - - /** - * Respond to the main window. - * @param event Contains event type and data - */ - function response(event: object): void; + delegate(method: string, options: object): Promise; } } - /** - * Set the path for the web worker script and create an instance of the async proxy - * @param path relative path to the worker scripts, default: 'openpgp.worker.js' - * @param n number of workers to initialize - * @param workers alternative to path parameter: web workers initialized with 'openpgp.worker.js' - */ - function initWorker(path: string, n?: number, workers?: any[]): void; + * @see module:openpgp.initWorker + * @see module:openpgp.getWorker + * @see module:openpgp.destroyWorker + * @see module:worker/async_proxy + */ + namespace worker { + /** + * Handle random buffer exhaustion by requesting more random bytes from the main window + * @returns Empty Promise whose resolution indicates that the buffer has been refilled + */ + function randomCallback(): Promise; - /** - * Returns a reference to the async proxy if the worker was initialized with openpgp.initWorker() - * @returns the async proxy or null if not initialized - */ - function getWorker(): worker.async_proxy.AsyncProxy | null; + /** + * Set config from main context to worker context. + * @param config The openpgp configuration + */ + function configure(config: object): void; - /** - * Cleanup the current instance of the web worker. - */ - function destroyWorker(): void; + /** + * Seed the library with entropy gathered window.crypto.getRandomValues + * as this api is only avalible in the main window. + * @param buffer Some random bytes + */ + function seedRandom(buffer: any[]): void; - interface UserID { - name: string; - email: string; + /** + * Generic proxy function that handles all commands from the public api. + * @param method The public api function to be delegated to the worker thread + * @param options The api function's options + */ + function delegate(method: string, options: object): void; + + /** + * Respond to the main window. + * @param event Contains event type and data + */ + function response(event: object): void; } - - interface KeyOptions { - /** - * array of user IDs e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] - */ - userIds: UserID[]; - /** - * (optional) The passphrase used to encrypt the resulting private key - */ - passphrase?: string; - /** - * (optional) number of bits for RSA keys: 2048 or 4096. - */ - numBits?: number; - /** - * (optional) The number of seconds after the key creation time that the key expires - */ - keyExpirationTime?: number; - /** - * (optional) elliptic curve for ECC keys: elliptic curve for ECC keys: - * curve25519, p256, p384, p521, secp256k1, - * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1. - */ - curve?: string; - /** - * (optional) override the creation date of the key and the key signatures - */ - date?: Date; - /** - * (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] - * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt - */ - subkeys?: { sign: true, passphrase: "string" }[]; - } - - /** - * Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type. - * @param options - * @returns The generated key object in the form: - * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } - */ - function generateKey(option: KeyOptions): Promise<{ key: key.Key, privateKeyArmored: string, publicKeyArmored: string, revocationCertificate: string }>; - - /** - * Reformats signature packets for a key and rewraps key object. - * @param privateKey private key to reformat - * @param userIds array of user IDs e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] - * @param passphrase (optional) The passphrase used to encrypt the resulting private key - * @param keyExpirationTime (optional) The number of seconds after the key creation time that the key expires - * @param revocationCertificate (optional) Whether the returned object should include a revocation certificate to revoke the public key - * @returns The generated key object in the form: - * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } - */ - function reformatKey(privateKey: key.Key, userIds: any[], passphrase?: string, keyExpirationTime?: number, revocationCertificate?: boolean): Promise; - - /** - * Revokes a key. Requires either a private key or a revocation certificate. - * If a revocation certificate is passed, the reasonForRevocation parameters will be ignored. - * @param key (optional) public or private key to revoke - * @param revocationCertificate (optional) revocation certificate to revoke the key with - * @param reasonForRevocation (optional) object indicating the reason for revocation - * @param reasonForRevocation.flag (optional) flag indicating the reason for revocation - * @param reasonForRevocation.string (optional) string explaining the reason for revocation - * @returns The revoked key object in the form: - * { privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String } - * (if private key is passed) or { publicKey:Key, publicKeyArmored:String } (otherwise) - */ - function revokeKey(key?: key.Key, revocationCertificate?: string, reasonForRevocation?: revokeKey_reasonForRevocation): Promise<{ - privateKey: key.Key, - privateKeyArmored: string, - publicKey: key.Key, - publicKeyArmored: string - } | { - publicKey: key.Key, - publicKeyArmored: string - }>; - - /** - * Unlock a private key with your passphrase. - * @param privateKey the private key that is to be decrypted - * @param passphrase the user's passphrase(s) chosen during key generation - * @returns the unlocked key object in the form: { key:Key } - */ - function decryptKey(privateKey: key.Key, passphrase: string | any[]): Promise<{ key: key.Key }>; - - /** - * Lock a private key with your passphrase. - * @param privateKey the private key that is to be decrypted - * @param passphrase the user's passphrase(s) chosen during key generation - * @returns the locked key object in the form: { key:Key } - */ - function encryptKey(privateKey: key.Key, passphrase: string | any[]): Promise<{ key: key.Key }>; - - interface EncryptOptions { - /** - * message to be encrypted as created by openpgp.message.fromText or openpgp.message.fromBinary - */ - message: message.Message; - /** - * (optional) array of keys or single key, used to encrypt the message - */ - publicKeys?: key.Key | any[]; - /** - * (optional) private keys for signing. If omitted message will not be signed - */ - privateKeys?: key.Key | any[]; - /** - * (optional) array of passwords or a single password to encrypt the message - */ - passwords?: string | any[]; - /** - * (optional) session key in the form: { data:Uint8Array, algorithm:String } - */ - sessionKey?: { data: Uint8Array, algorithm: string }; - /** - * (optional) which compression algorithm to compress the message with, defaults to what is specified in config - */ - compression?: enums.compression; - /** - * (optional) if the return values should be ascii armored or the message/signature objects - */ - armor?: boolean; - /** - * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - */ - streaming?: 'web' | 'node' | false; - /** - * (optional) if the signature should be detached (if true, signature will be added to returned object) - */ - detached?: boolean; - /** - * (optional) a detached signature to add to the encrypted message - */ - signature?: signature.Signature; - /** - * (optional) if the unencrypted session key should be added to returned object - */ - returnSessionKey?: boolean; - /** - * (optional) use a key ID of 0 instead of the public key IDs - */ - wildcard?: boolean; - /** - * (optional) override the creation date of the message signature - */ - date?: Date; - /** - * (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - */ - fromUserIds?: UserID[]; - /** - * (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] - */ - toUserIds?: UserID[] - } - - interface EncryptResult { - data: string | ReadableStream; - message: message.Message; - signature: string | ReadableStream | signature.Signature; - sessionKey: { data: Uint8Array, algorithm: string, aeadAlgorithm: string }; - } - - /** - * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords - * must be specified. If private keys are specified, those will be used to sign the message. - * @param options - * @returns Object containing encrypted (and optionally signed) message in the form: - * { - * data: string|ReadableStream|NodeStream, (if `armor` was true, the default) - * message: Message, (if `armor` was false) - * signature: string|ReadableStream|NodeStream, (if `detached` was true and `armor` was true) - * signature: Signature (if `detached` was true and `armor` was false) - * sessionKey: { data, algorithm, aeadAlgorithm } (if `returnSessionKey` was true) - * } - */ - function encrypt(options: EncryptOptions): Promise; - - interface DecryptOptions { - /** - * the message object with the encrypted data - */ - message: message.Message; - /** - * (optional) private keys with decrypted secret key data or session key - */ - privateKeys?: key.Key | key.Key[]; - /** - * (optional) passwords to decrypt the message - */ - passwords?: string | string[]; - /** - * (optional) session keys in the form: { data:Uint8Array, algorithm:String } - */ - sessionKeys?: { data: Uint8Array, algorithm: string } | { data: Uint8Array, algorithm: string }[]; - /** - * (optional) array of public keys or single key, to verify signatures - */ - publicKeys?: key.Key | key.Key[]; - /** - * (optional) whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. - */ - format?: 'utf8' | 'binary'; - /** - * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - */ - streaming?: 'web' | 'node' | false; - /** - * (optional) detached signature for verification - */ - signature?: signature.Signature; - /** - * (optional) use the given date for verification instead of the current time - */ - date?: Date - } - - interface DecryptResult { - data: string | ReadableStream | NodeStream | Uint8Array | ReadableStream, - filename: string, - signatures: { - keyid: type.keyid.Keyid, - verified: Promise, - valid: boolean - }[] - } - - /** - * Decrypts a message with the user's private key, a session key or a password. Either a private key, - * a session key or a password must be specified. - * @param options - * @returns Object containing decrypted and verified message in the form: - * { - * data: string|ReadableStream|NodeStream, (if format was 'utf8', the default) - * data: Uint8Array|ReadableStream|NodeStream, (if format was 'binary') - * filename: string, - * signatures: [ - * { - * keyid: module:type/keyid, - * verified: Promise, - * valid: boolean (if streaming was false) - * }, ... - * ] - * } - */ - function decrypt(options: DecryptOptions): Promise; - - interface SignOptions { - /** - * (cleartext) message to be signed - */ - message: cleartext.CleartextMessage | message.Message; - /** - * array of keys or single key with decrypted secret key data to sign cleartext - */ - privateKeys: key.Key | any[]; - /** - * (optional) if the return value should be ascii armored or the message object - */ - armor?: boolean; - /** - * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - */ - streaming?: 'web' | 'node' | false; - /** - * (optional) if the return value should contain a detached signature - */ - detached?: boolean; - /** - * (optional) override the creation date of the signature - */ - date?: Date; - /** - * (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] - */ - fromUserIds?: UserID[] - } - - interface SignResult { - data: string | ReadableStream | NodeStream, - message: message.Message, - signature: string | ReadableStream | NodeStream | signature.Signature - } - - /** - * Signs a cleartext message. - * @param options - * @returns Object containing signed message in the form: - * { - * data: string|ReadableStream|NodeStream, (if `armor` was true, the default) - * message: Message (if `armor` was false) - * } - * Or, if `detached` was true: - * { - * signature: string|ReadableStream|NodeStream, (if `armor` was true, the default) - * signature: Signature (if `armor` was false) - * } - */ - function sign(options: SignOptions): Promise; - - interface VerifyOptions { - /** - * array of publicKeys or single key, to verify signatures - */ - publicKeys: key.Key | any[]; - /** - * (cleartext) message object with signatures - */ - message: cleartext.CleartextMessage | message.Message; - /** - * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - */ - streaming?: 'web' | 'node' | false; - /** - * (optional) detached signature for verification - */ - signature?: signature.Signature; - /** - * (optional) use the given date for verification instead of the current time - */ - date?: Date - } - - interface VerifyResult { - data: string | ReadableStream | NodeStream | Uint8Array | ReadableStream | NodeStream, - signatures: { - keyid: type.keyid.Keyid, - verified: Promise, - valid: boolean - }[] - } - - /** - * Verifies signatures of cleartext signed message - * @param options - * @returns Object containing verified message in the form: - * { - * data: string|ReadableStream|NodeStream, (if `message` was a CleartextMessage) - * data: Uint8Array|ReadableStream|NodeStream, (if `message` was a Message) - * signatures: [ - * { - * keyid: module:type/keyid, - * verified: Promise, - * valid: boolean (if `streaming` was false) - * }, ... - * ] - * } - */ - function verify(options: VerifyOptions): Promise; - - /** - * Encrypt a symmetric session key with public keys, passwords, or both at once. At least either public keys - * or passwords must be specified. - * @param data the session key to be encrypted e.g. 16 random bytes (for aes128) - * @param algorithm algorithm of the symmetric session key e.g. 'aes128' or 'aes256' - * @param aeadAlgorithm (optional) aead algorithm, e.g. 'eax' or 'ocb' - * @param publicKeys (optional) array of public keys or single key, used to encrypt the key - * @param passwords (optional) passwords for the message - * @param wildcard (optional) use a key ID of 0 instead of the public key IDs - * @param date (optional) override the date - * @param toUserIds (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] - * @returns the encrypted session key packets contained in a message object - */ - function encryptSessionKey(data: Uint8Array, algorithm: string, aeadAlgorithm?: string, publicKeys?: key.Key | key.Key[], passwords?: string | string[], wildcard?: boolean, date?: Date, toUserIds?: any[]): Promise; - - /** - * Decrypt symmetric session keys with a private key or password. Either a private key or - * a password must be specified. - * @param message a message object containing the encrypted session key packets - * @param privateKeys (optional) private keys with decrypted secret key data - * @param passwords (optional) passwords to decrypt the session key - * @returns Array of decrypted session key, algorithm pairs in form: - * { data:Uint8Array, algorithm:String } - * or 'undefined' if no key packets found - */ - function decryptSessionKeys(message: message.Message, privateKeys?: key.Key | key.Key[], passwords?: string | string[]): Promise<{ data: Uint8Array, algorithm: string }[] | undefined>; - - /** - * Input validation - */ - function checkString(): void; - - /** - * Normalize parameter to an array if it is not undefined. - * @param param the parameter to be normalized - * @returns the resulting array or undefined - */ - function toArray(param: object): any[] | undefined; - - /** - * Convert data to or from Stream - * @param data the data to convert - * @param streaming (optional) whether to return a ReadableStream - * @returns the data in the respective format - */ - function convertStream(data: object, streaming?: 'web' | 'node' | false): object; - - /** - * Convert object properties from Stream - * @param obj the data to convert - * @param streaming (optional) whether to return ReadableStreams - * @param keys (optional) which keys to return as streams, if possible - * @returns the data in the respective format - */ - function convertStreams(obj: object, streaming: 'web' | 'node' | false, keys: any[]): object; - - /** - * Link result.data to the message stream for cancellation. - * Also, forward errors in the message to result.data. - * @param result the data to convert - * @param message message object - * @param erroringStream (optional) stream which either errors or gets closed without data - * @returns - */ - function linkStreams(result: object, message: message.Message, erroringStream: ReadableStream): object; - - /** - * Wait until signature objects have been verified - * @param signatures list of signatures - */ - function prepareSignatures(signatures: object): void; - - /** - * Global error handler that logs the stack trace and rethrows a high lvl error message. - * @param message A human readable high level error Message - * @param error The internal error that caused the failure - */ - function onError(message: string, error: Error): void; - - /** - * Check for native AEAD support and configuration by the user. Only - * browsers that implement the current WebCrypto specification support - * native GCM. Native EAX is built on CTR and CBC, which current - * browsers support. OCB and CFB are not natively supported. - * @returns If authenticated encryption should be used - */ - function nativeAEAD(): boolean; } + + +/** + * Set the path for the web worker script and create an instance of the async proxy + * @param path relative path to the worker scripts, default: 'openpgp.worker.js' + * @param n number of workers to initialize + * @param workers alternative to path parameter: web workers initialized with 'openpgp.worker.js' + */ +export function initWorker(path: string, n?: number, workers?: any[]): void; + +/** + * Returns a reference to the async proxy if the worker was initialized with openpgp.initWorker() + * @returns the async proxy or null if not initialized + */ +export function getWorker(): worker.async_proxy.AsyncProxy | null; + +/** + * Cleanup the current instance of the web worker. + */ +export function destroyWorker(): void; + +export interface UserID { + name: string; + email: string; +} + +export interface KeyOptions { + /** + * array of user IDs e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] + */ + userIds: UserID[]; + /** + * (optional) The passphrase used to encrypt the resulting private key + */ + passphrase?: string; + /** + * (optional) number of bits for RSA keys: 2048 or 4096. + */ + numBits?: number; + /** + * (optional) The number of seconds after the key creation time that the key expires + */ + keyExpirationTime?: number; + /** + * (optional) elliptic curve for ECC keys: elliptic curve for ECC keys: + * curve25519, p256, p384, p521, secp256k1, + * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1. + */ + curve?: string; + /** + * (optional) override the creation date of the key and the key signatures + */ + date?: Date; + /** + * (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + */ + subkeys?: { sign: true, passphrase: "string" }[]; +} + +/** + * Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type. + * @param options + * @returns The generated key object in the form: + * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } + */ +export function generateKey(option: KeyOptions): Promise<{ key: key.Key, privateKeyArmored: string, publicKeyArmored: string, revocationCertificate: string }>; + +/** + * Reformats signature packets for a key and rewraps key object. + * @param privateKey private key to reformat + * @param userIds array of user IDs e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] + * @param passphrase (optional) The passphrase used to encrypt the resulting private key + * @param keyExpirationTime (optional) The number of seconds after the key creation time that the key expires + * @param revocationCertificate (optional) Whether the returned object should include a revocation certificate to revoke the public key + * @returns The generated key object in the form: + * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } + */ +export function reformatKey(privateKey: key.Key, userIds: any[], passphrase?: string, keyExpirationTime?: number, revocationCertificate?: boolean): Promise; + +/** + * Revokes a key. Requires either a private key or a revocation certificate. + * If a revocation certificate is passed, the reasonForRevocation parameters will be ignored. + * @param key (optional) public or private key to revoke + * @param revocationCertificate (optional) revocation certificate to revoke the key with + * @param reasonForRevocation (optional) object indicating the reason for revocation + * @param reasonForRevocation.flag (optional) flag indicating the reason for revocation + * @param reasonForRevocation.string (optional) string explaining the reason for revocation + * @returns The revoked key object in the form: + * { privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String } + * (if private key is passed) or { publicKey:Key, publicKeyArmored:String } (otherwise) + */ +export function revokeKey(key?: key.Key, revocationCertificate?: string, reasonForRevocation?: revokeKey_reasonForRevocation): Promise<{ + privateKey: key.Key, + privateKeyArmored: string, + publicKey: key.Key, + publicKeyArmored: string +} | { + publicKey: key.Key, + publicKeyArmored: string +}>; + +/** + * Unlock a private key with your passphrase. + * @param privateKey the private key that is to be decrypted + * @param passphrase the user's passphrase(s) chosen during key generation + * @returns the unlocked key object in the form: { key:Key } + */ +export function decryptKey(privateKey: key.Key, passphrase: string | any[]): Promise<{ key: key.Key }>; + +/** + * Lock a private key with your passphrase. + * @param privateKey the private key that is to be decrypted + * @param passphrase the user's passphrase(s) chosen during key generation + * @returns the locked key object in the form: { key:Key } + */ +export function encryptKey(privateKey: key.Key, passphrase: string | any[]): Promise<{ key: key.Key }>; + +export interface EncryptOptions { + /** + * message to be encrypted as created by openpgp.message.fromText or openpgp.message.fromBinary + */ + message: message.Message; + /** + * (optional) array of keys or single key, used to encrypt the message + */ + publicKeys?: key.Key | any[]; + /** + * (optional) private keys for signing. If omitted message will not be signed + */ + privateKeys?: key.Key | any[]; + /** + * (optional) array of passwords or a single password to encrypt the message + */ + passwords?: string | any[]; + /** + * (optional) session key in the form: { data:Uint8Array, algorithm:String } + */ + sessionKey?: { data: Uint8Array, algorithm: string }; + /** + * (optional) which compression algorithm to compress the message with, defaults to what is specified in config + */ + compression?: enums.compression; + /** + * (optional) if the return values should be ascii armored or the message/signature objects + */ + armor?: boolean; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) if the signature should be detached (if true, signature will be added to returned object) + */ + detached?: boolean; + /** + * (optional) a detached signature to add to the encrypted message + */ + signature?: signature.Signature; + /** + * (optional) if the unencrypted session key should be added to returned object + */ + returnSessionKey?: boolean; + /** + * (optional) use a key ID of 0 instead of the public key IDs + */ + wildcard?: boolean; + /** + * (optional) override the creation date of the message signature + */ + date?: Date; + /** + * (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + */ + fromUserIds?: UserID[]; + /** + * (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] + */ + toUserIds?: UserID[] +} + +export interface EncryptResult { + data: string | ReadableStream; + message: message.Message; + signature: string | ReadableStream | signature.Signature; + sessionKey: { data: Uint8Array, algorithm: string, aeadAlgorithm: string }; +} + +/** + * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords + * must be specified. If private keys are specified, those will be used to sign the message. + * @param options + * @returns Object containing encrypted (and optionally signed) message in the form: + * { + * data: string|ReadableStream|NodeStream, (if `armor` was true, the default) + * message: Message, (if `armor` was false) + * signature: string|ReadableStream|NodeStream, (if `detached` was true and `armor` was true) + * signature: Signature (if `detached` was true and `armor` was false) + * sessionKey: { data, algorithm, aeadAlgorithm } (if `returnSessionKey` was true) + * } + */ +export function encrypt(options: EncryptOptions): Promise; + +export interface DecryptOptions { + /** + * the message object with the encrypted data + */ + message: message.Message; + /** + * (optional) private keys with decrypted secret key data or session key + */ + privateKeys?: key.Key | key.Key[]; + /** + * (optional) passwords to decrypt the message + */ + passwords?: string | string[]; + /** + * (optional) session keys in the form: { data:Uint8Array, algorithm:String } + */ + sessionKeys?: { data: Uint8Array, algorithm: string } | { data: Uint8Array, algorithm: string }[]; + /** + * (optional) array of public keys or single key, to verify signatures + */ + publicKeys?: key.Key | key.Key[]; + /** + * (optional) whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. + */ + format?: 'utf8' | 'binary'; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) detached signature for verification + */ + signature?: signature.Signature; + /** + * (optional) use the given date for verification instead of the current time + */ + date?: Date +} + +export interface DecryptResult { + data: string | ReadableStream | NodeStream | Uint8Array | ReadableStream, + filename: string, + signatures: { + keyid: type.keyid.Keyid, + verified: Promise, + valid: boolean + }[] +} + +/** + * Decrypts a message with the user's private key, a session key or a password. Either a private key, + * a session key or a password must be specified. + * @param options + * @returns Object containing decrypted and verified message in the form: + * { + * data: string|ReadableStream|NodeStream, (if format was 'utf8', the default) + * data: Uint8Array|ReadableStream|NodeStream, (if format was 'binary') + * filename: string, + * signatures: [ + * { + * keyid: module:type/keyid, + * verified: Promise, + * valid: boolean (if streaming was false) + * }, ... + * ] + * } + */ +export function decrypt(options: DecryptOptions): Promise; + +export interface SignOptions { + /** + * (cleartext) message to be signed + */ + message: cleartext.CleartextMessage | message.Message; + /** + * array of keys or single key with decrypted secret key data to sign cleartext + */ + privateKeys: key.Key | any[]; + /** + * (optional) if the return value should be ascii armored or the message object + */ + armor?: boolean; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) if the return value should contain a detached signature + */ + detached?: boolean; + /** + * (optional) override the creation date of the signature + */ + date?: Date; + /** + * (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + */ + fromUserIds?: UserID[] +} + +export interface SignResult { + data: string | ReadableStream | NodeStream, + message: message.Message, + signature: string | ReadableStream | NodeStream | signature.Signature +} + +/** + * Signs a cleartext message. + * @param options + * @returns Object containing signed message in the form: + * { + * data: string|ReadableStream|NodeStream, (if `armor` was true, the default) + * message: Message (if `armor` was false) + * } + * Or, if `detached` was true: + * { + * signature: string|ReadableStream|NodeStream, (if `armor` was true, the default) + * signature: Signature (if `armor` was false) + * } + */ +export function sign(options: SignOptions): Promise; + +export interface VerifyOptions { + /** + * array of publicKeys or single key, to verify signatures + */ + publicKeys: key.Key | any[]; + /** + * (cleartext) message object with signatures + */ + message: cleartext.CleartextMessage | message.Message; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) detached signature for verification + */ + signature?: signature.Signature; + /** + * (optional) use the given date for verification instead of the current time + */ + date?: Date +} + +export interface VerifyResult { + data: string | ReadableStream | NodeStream | Uint8Array | ReadableStream | NodeStream, + signatures: { + keyid: type.keyid.Keyid, + verified: Promise, + valid: boolean + }[] +} + +/** + * Verifies signatures of cleartext signed message + * @param options + * @returns Object containing verified message in the form: + * { + * data: string|ReadableStream|NodeStream, (if `message` was a CleartextMessage) + * data: Uint8Array|ReadableStream|NodeStream, (if `message` was a Message) + * signatures: [ + * { + * keyid: module:type/keyid, + * verified: Promise, + * valid: boolean (if `streaming` was false) + * }, ... + * ] + * } + */ +export function verify(options: VerifyOptions): Promise; + +/** + * Encrypt a symmetric session key with public keys, passwords, or both at once. At least either public keys + * or passwords must be specified. + * @param data the session key to be encrypted e.g. 16 random bytes (for aes128) + * @param algorithm algorithm of the symmetric session key e.g. 'aes128' or 'aes256' + * @param aeadAlgorithm (optional) aead algorithm, e.g. 'eax' or 'ocb' + * @param publicKeys (optional) array of public keys or single key, used to encrypt the key + * @param passwords (optional) passwords for the message + * @param wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param date (optional) override the date + * @param toUserIds (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] + * @returns the encrypted session key packets contained in a message object + */ +export function encryptSessionKey(data: Uint8Array, algorithm: string, aeadAlgorithm?: string, publicKeys?: key.Key | key.Key[], passwords?: string | string[], wildcard?: boolean, date?: Date, toUserIds?: any[]): Promise; + +/** + * Decrypt symmetric session keys with a private key or password. Either a private key or + * a password must be specified. + * @param message a message object containing the encrypted session key packets + * @param privateKeys (optional) private keys with decrypted secret key data + * @param passwords (optional) passwords to decrypt the session key + * @returns Array of decrypted session key, algorithm pairs in form: + * { data:Uint8Array, algorithm:String } + * or 'undefined' if no key packets found + */ +export function decryptSessionKeys(message: message.Message, privateKeys?: key.Key | key.Key[], passwords?: string | string[]): Promise<{ data: Uint8Array, algorithm: string }[] | undefined>; + +/** + * Input validation + */ +export function checkString(): void; + +/** + * Normalize parameter to an array if it is not undefined. + * @param param the parameter to be normalized + * @returns the resulting array or undefined + */ +export function toArray(param: object): any[] | undefined; + +/** + * Convert data to or from Stream + * @param data the data to convert + * @param streaming (optional) whether to return a ReadableStream + * @returns the data in the respective format + */ +export function convertStream(data: object, streaming?: 'web' | 'node' | false): object; + +/** + * Convert object properties from Stream + * @param obj the data to convert + * @param streaming (optional) whether to return ReadableStreams + * @param keys (optional) which keys to return as streams, if possible + * @returns the data in the respective format + */ +export function convertStreams(obj: object, streaming: 'web' | 'node' | false, keys: any[]): object; + +/** + * Link result.data to the message stream for cancellation. + * Also, forward errors in the message to result.data. + * @param result the data to convert + * @param message message object + * @param erroringStream (optional) stream which either errors or gets closed without data + * @returns + */ +export function linkStreams(result: object, message: message.Message, erroringStream: ReadableStream): object; + +/** + * Wait until signature objects have been verified + * @param signatures list of signatures + */ +export function prepareSignatures(signatures: object): void; + +/** + * Global error handler that logs the stack trace and rethrows a high lvl error message. + * @param message A human readable high level error Message + * @param error The internal error that caused the failure + */ +export function onError(message: string, error: Error): void; + +/** + * Check for native AEAD support and configuration by the user. Only + * browsers that implement the current WebCrypto specification support + * native GCM. Native EAX is built on CTR and CBC, which current + * browsers support. OCB and CFB are not natively supported. + * @returns If authenticated encryption should be used + */ +export function nativeAEAD(): boolean; diff --git a/types/openpgp/ts3.2/openpgp-tests.ts b/types/openpgp/ts3.2/openpgp-tests.ts index fc3efeeda0..62e580fd4b 100644 --- a/types/openpgp/ts3.2/openpgp-tests.ts +++ b/types/openpgp/ts3.2/openpgp-tests.ts @@ -1,4 +1,4 @@ -import { openpgp } from "openpgp"; +import openpgp from "openpgp"; // Open PGP Sample codes From 7dc49fe63c4d2615d8788566a41a8efacd7740b5 Mon Sep 17 00:00:00 2001 From: Muhammet Ozturk Date: Thu, 21 Mar 2019 05:54:46 +0300 Subject: [PATCH 095/337] delete unnecessary newlines --- types/pako/index.d.ts | 8 -------- 1 file changed, 8 deletions(-) diff --git a/types/pako/index.d.ts b/types/pako/index.d.ts index 26cc24a25c..9a51f87c39 100644 --- a/types/pako/index.d.ts +++ b/types/pako/index.d.ts @@ -121,28 +121,20 @@ export function ungzip(data: Data, options?: InflateFunctionOptions): Uint8Array export class Deflate { constructor(options?: DeflateOptions); - err: ReturnCodes; msg: string; result: Uint8Array | number[]; - onData(chunk: Data): void; - onEnd(status: number): void; - push(data: Data | ArrayBuffer, mode?: FlushValues | boolean): boolean; } export class Inflate { constructor(options?: InflateOptions); - err: ReturnCodes; msg: string; result: Data; - onData(chunk: Data): void; - onEnd(status: number): void; - push(data: Data | ArrayBuffer, mode?: FlushValues | boolean): boolean; } From d34d93bb572363cd479496bd48ab9ac15e67e19f Mon Sep 17 00:00:00 2001 From: Muhammet Ozturk Date: Thu, 21 Mar 2019 06:22:29 +0300 Subject: [PATCH 096/337] with namespace --- types/pako/index.d.ts | 269 +++++++++++++++++++++-------------------- types/pako/tslint.json | 2 +- 2 files changed, 138 insertions(+), 133 deletions(-) diff --git a/types/pako/index.d.ts b/types/pako/index.d.ts index 9a51f87c39..69c4feaf01 100644 --- a/types/pako/index.d.ts +++ b/types/pako/index.d.ts @@ -5,136 +5,141 @@ // Muhammet Öztürk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export enum FlushValues { - Z_NO_FLUSH = 0, - Z_PARTIAL_FLUSH = 1, - Z_SYNC_FLUSH = 2, - Z_FULL_FLUSH = 3, - Z_FINISH = 4, - Z_BLOCK = 5, - Z_TREES = 6, -} - -export enum StrategyValues { - Z_FILTERED = 1, - Z_HUFFMAN_ONLY = 2, - Z_RLE = 3, - Z_FIXED = 4, - Z_DEFAULT_STRATEGY = 0, -} - -export enum ReturnCodes { - Z_OK = 0, - Z_STREAM_END = 1, - Z_NEED_DICT = 2, - Z_ERRNO = -1, - Z_STREAM_ERROR = -2, - Z_DATA_ERROR = -3, - Z_BUF_ERROR = -5, -} - -export interface DeflateOptions { - level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; - windowBits?: number; - memLevel?: number; - strategy?: StrategyValues; - dictionary?: any; - raw?: boolean; - to?: 'string'; - chunkSize?: number; - gzip?: boolean; - header?: Header; -} - -export interface DeflateFunctionOptions { - level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; - windowBits?: number; - memLevel?: number; - strategy?: StrategyValues; - dictionary?: any; - raw?: boolean; - to?: 'string'; -} - -export interface InflateOptions { - windowBits?: number; - dictionary?: any; - raw?: boolean; - to?: 'string'; - chunkSize?: number; -} - -export interface InflateFunctionOptions { - windowBits?: number; - raw?: boolean; - to?: 'string'; -} - -export interface Header { - text?: boolean; - time?: number; - os?: number; - extra?: number[]; - name?: string; - comment?: string; - hcrc?: boolean; -} - -export type Data = Uint8Array | number[] | string; - -/** - * Compress data with deflate algorithm and options. - */ -export function deflate(data: Data, options: DeflateFunctionOptions & { to: 'string' }): string; -export function deflate(data: Data, options?: DeflateFunctionOptions): Uint8Array; - -/** - * The same as deflate, but creates raw data, without wrapper (header and adler32 crc). - */ -export function deflateRaw(data: Data, options: DeflateFunctionOptions & { to: 'string' }): string; -export function deflateRaw(data: Data, options?: DeflateFunctionOptions): Uint8Array; - -/** - * The same as deflate, but create gzip wrapper instead of deflate one. - */ -export function gzip(data: Data, options: DeflateFunctionOptions & { to: 'string' }): string; -export function gzip(data: Data, options?: DeflateFunctionOptions): Uint8Array; - -/** - * Decompress data with inflate/ungzip and options. Autodetect format via wrapper header - * by default. That's why we don't provide separate ungzip method. - */ -export function inflate(data: Data, options: InflateFunctionOptions & { to: 'string' }): string; -export function inflate(data: Data, options?: InflateFunctionOptions): Uint8Array; - -/** - * The same as inflate, but creates raw data, without wrapper (header and adler32 crc). - */ -export function inflateRaw(data: Data, options: InflateFunctionOptions & { to: 'string' }): string; -export function inflateRaw(data: Data, options?: InflateFunctionOptions): Uint8Array; - -/** - * Just shortcut to inflate, because it autodetects format by header.content. Done for convenience. - */ -export function ungzip(data: Data, options: InflateFunctionOptions & { to: 'string' }): string; -export function ungzip(data: Data, options?: InflateFunctionOptions): Uint8Array; - -export class Deflate { - constructor(options?: DeflateOptions); - err: ReturnCodes; - msg: string; - result: Uint8Array | number[]; - onData(chunk: Data): void; - onEnd(status: number): void; - push(data: Data | ArrayBuffer, mode?: FlushValues | boolean): boolean; -} - -export class Inflate { - constructor(options?: InflateOptions); - err: ReturnCodes; - msg: string; - result: Data; - onData(chunk: Data): void; - onEnd(status: number): void; - push(data: Data | ArrayBuffer, mode?: FlushValues | boolean): boolean; +export = Pako; +export as namespace pako; + +declare namespace Pako { + enum FlushValues { + Z_NO_FLUSH = 0, + Z_PARTIAL_FLUSH = 1, + Z_SYNC_FLUSH = 2, + Z_FULL_FLUSH = 3, + Z_FINISH = 4, + Z_BLOCK = 5, + Z_TREES = 6, + } + + enum StrategyValues { + Z_FILTERED = 1, + Z_HUFFMAN_ONLY = 2, + Z_RLE = 3, + Z_FIXED = 4, + Z_DEFAULT_STRATEGY = 0, + } + + enum ReturnCodes { + Z_OK = 0, + Z_STREAM_END = 1, + Z_NEED_DICT = 2, + Z_ERRNO = -1, + Z_STREAM_ERROR = -2, + Z_DATA_ERROR = -3, + Z_BUF_ERROR = -5, + } + + interface DeflateOptions { + level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + windowBits?: number; + memLevel?: number; + strategy?: StrategyValues; + dictionary?: any; + raw?: boolean; + to?: 'string'; + chunkSize?: number; + gzip?: boolean; + header?: Header; + } + + interface DeflateFunctionOptions { + level?: -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + windowBits?: number; + memLevel?: number; + strategy?: StrategyValues; + dictionary?: any; + raw?: boolean; + to?: 'string'; + } + + interface InflateOptions { + windowBits?: number; + dictionary?: any; + raw?: boolean; + to?: 'string'; + chunkSize?: number; + } + + interface InflateFunctionOptions { + windowBits?: number; + raw?: boolean; + to?: 'string'; + } + + interface Header { + text?: boolean; + time?: number; + os?: number; + extra?: number[]; + name?: string; + comment?: string; + hcrc?: boolean; + } + + type Data = Uint8Array | number[] | string; + + /** + * Compress data with deflate algorithm and options. + */ + function deflate(data: Data, options: DeflateFunctionOptions & { to: 'string' }): string; + function deflate(data: Data, options?: DeflateFunctionOptions): Uint8Array; + + /** + * The same as deflate, but creates raw data, without wrapper (header and adler32 crc). + */ + function deflateRaw(data: Data, options: DeflateFunctionOptions & { to: 'string' }): string; + function deflateRaw(data: Data, options?: DeflateFunctionOptions): Uint8Array; + + /** + * The same as deflate, but create gzip wrapper instead of deflate one. + */ + function gzip(data: Data, options: DeflateFunctionOptions & { to: 'string' }): string; + function gzip(data: Data, options?: DeflateFunctionOptions): Uint8Array; + + /** + * Decompress data with inflate/ungzip and options. Autodetect format via wrapper header + * by default. That's why we don't provide separate ungzip method. + */ + function inflate(data: Data, options: InflateFunctionOptions & { to: 'string' }): string; + function inflate(data: Data, options?: InflateFunctionOptions): Uint8Array; + + /** + * The same as inflate, but creates raw data, without wrapper (header and adler32 crc). + */ + function inflateRaw(data: Data, options: InflateFunctionOptions & { to: 'string' }): string; + function inflateRaw(data: Data, options?: InflateFunctionOptions): Uint8Array; + + /** + * Just shortcut to inflate, because it autodetects format by header.content. Done for convenience. + */ + function ungzip(data: Data, options: InflateFunctionOptions & { to: 'string' }): string; + function ungzip(data: Data, options?: InflateFunctionOptions): Uint8Array; + + class Deflate { + constructor(options?: DeflateOptions); + err: ReturnCodes; + msg: string; + result: Uint8Array | number[]; + onData(chunk: Data): void; + onEnd(status: number): void; + push(data: Data | ArrayBuffer, mode?: FlushValues | boolean): boolean; + } + + class Inflate { + constructor(options?: InflateOptions); + err: ReturnCodes; + msg: string; + result: Data; + onData(chunk: Data): void; + onEnd(status: number): void; + push(data: Data | ArrayBuffer, mode?: FlushValues | boolean): boolean; + } } diff --git a/types/pako/tslint.json b/types/pako/tslint.json index 2ff396e742..adaee1b55f 100644 --- a/types/pako/tslint.json +++ b/types/pako/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - + "export-just-namespace": false } } From e3e77eb0cdfa0286a4e2acbc0c279972b2b5eaf5 Mon Sep 17 00:00:00 2001 From: Ziyu Wang Date: Thu, 21 Mar 2019 16:22:26 +1100 Subject: [PATCH 097/337] rename ReduxReducer --- types/redux-actions/index.d.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/types/redux-actions/index.d.ts b/types/redux-actions/index.d.ts index f0654eab08..fd92441573 100644 --- a/types/redux-actions/index.d.ts +++ b/types/redux-actions/index.d.ts @@ -67,9 +67,9 @@ export type Reducer = (state: State, action: Action) => export type ReducerMeta = (state: State, action: ActionMeta) => State; -export type ReduxReducer = (state: State | undefined, action: Action) => State; +export type ReduxCompatibleReducer = (state: State | undefined, action: Action) => State; -export type ReduxReducerMeta = (state: State | undefined, action: ActionMeta) => State; +export type ReduxCompatibleReducerMeta = (state: State | undefined, action: ActionMeta) => State; /** argument inferring borrowed from lodash definitions */ export type ActionFunction0 = () => R; @@ -153,13 +153,13 @@ export function handleAction( actionType: string | ActionFunctions | CombinedActionType, reducer: Reducer | ReducerNextThrow, initialState: State -): ReduxReducer; +): ReduxCompatibleReducer; export function handleAction( actionType: string | ActionWithMetaFunctions | CombinedActionType, reducer: ReducerMeta | ReducerNextThrowMeta, initialState: State -): ReduxReducerMeta; +): ReduxCompatibleReducerMeta; export interface Options { prefix?: string; @@ -170,19 +170,19 @@ export function handleActions( reducerMap: ReducerMap, initialState: StateAndPayload, options?: Options -): ReduxReducer; +): ReduxCompatibleReducer; export function handleActions( reducerMap: ReducerMap, initialState: State, options?: Options -): ReduxReducer; +): ReduxCompatibleReducer; export function handleActions( reducerMap: ReducerMapMeta, initialState: State, options?: Options -): ReduxReducerMeta; +): ReduxCompatibleReducerMeta; // https://github.com/redux-utilities/redux-actions/blob/v2.3.0/src/combineActions.js#L21 export function combineActions(...actionTypes: Array | string | symbol>): CombinedActionType; From 99658451404bd2558817acfa469500632120ffbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miika=20H=C3=A4nninen?= Date: Tue, 12 Mar 2019 10:08:36 +0200 Subject: [PATCH 098/337] (ramda) Fix traverse types in the all-arrays case The traverse function is not properly typeable at this moment since we lack higher-kinded types. Specific cases are doable though, like the array-array case I've typed here. Users can add their own specific cases in their own typings, to extend this. --- types/ramda/index.d.ts | 6 +++--- types/ramda/ramda-tests.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 917715c3e7..1078d9a51a 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -2686,9 +2686,9 @@ declare namespace R { * sequence to transform the resulting Traversable of Applicative into * an Applicative of Traversable. */ - traverse(of: (a: U[]) => A, fn: (t: T) => U, list: ReadonlyArray): A; - traverse(of: (a: U[]) => A, fn: (t: T) => U): (list: ReadonlyArray) => A; - traverse(of: (a: U[]) => A): (fn: (t: T) => U, list: ReadonlyArray) => A; + traverse(of: (a: B) => ReadonlyArray, fn: (t: A) => ReadonlyArray, list: ReadonlyArray): B[][]; + traverse(of: (a: B) => ReadonlyArray, fn: (t: A) => ReadonlyArray): (list: ReadonlyArray) => B[][]; + traverse(of: (a: B) => ReadonlyArray): (fn: (t: A) => ReadonlyArray, list: ReadonlyArray) => B[][]; /** * Removes (strips) whitespace from both ends of the string. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 2d8b00ba6a..6f88d82200 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1460,7 +1460,7 @@ type Pair = KeyValuePair; const list = [1, 2, 3]; R.traverse(of, fn, list); R.traverse(of, fn)(list); - R.traverse(of)(fn, list); + R.traverse(of)(fn, list); }; () => { From 8d9d42cfe6432a959afb471562cca05cf0d471a9 Mon Sep 17 00:00:00 2001 From: Konrad Klockgether Date: Thu, 21 Mar 2019 10:40:30 +0100 Subject: [PATCH 099/337] [polygons-intersect] created types --- types/polygons-intersect/index.d.ts | 14 +++++++++++ .../polygons-intersect-tests.ts | 5 ++++ types/polygons-intersect/tsconfig.json | 23 +++++++++++++++++++ types/polygons-intersect/tslint.json | 1 + 4 files changed, 43 insertions(+) create mode 100644 types/polygons-intersect/index.d.ts create mode 100644 types/polygons-intersect/polygons-intersect-tests.ts create mode 100644 types/polygons-intersect/tsconfig.json create mode 100644 types/polygons-intersect/tslint.json diff --git a/types/polygons-intersect/index.d.ts b/types/polygons-intersect/index.d.ts new file mode 100644 index 0000000000..87fd174e69 --- /dev/null +++ b/types/polygons-intersect/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for polygons-intersect 1.0 +// Project: https://github.com/DudaGod/polygons-intersect#readme +// Definitions by: Konrad Klockgether +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Finds all points where the polygons intersect each other. + */ +declare function intersection( + poly1: Array<{ x: number, y: number }>, + poly2: Array<{ x: number, y: number }> +): Array<{ x: number, y: number }>; + +export = intersection; diff --git a/types/polygons-intersect/polygons-intersect-tests.ts b/types/polygons-intersect/polygons-intersect-tests.ts new file mode 100644 index 0000000000..104c93c788 --- /dev/null +++ b/types/polygons-intersect/polygons-intersect-tests.ts @@ -0,0 +1,5 @@ +import polygonsIntersect = require('polygons-intersect'); + +const poly1 = [{x: 10, y: 10}, {x: 10, y: 30}, {x: 30, y: 30}, {x: 30, y: 10}]; +const poly2 = [{x: 20, y: 20}, {x: 20, y: 40}, {x: 40, y: 40}, {x: 40, y: 20}]; +polygonsIntersect(poly1, poly2); diff --git a/types/polygons-intersect/tsconfig.json b/types/polygons-intersect/tsconfig.json new file mode 100644 index 0000000000..20c8856f07 --- /dev/null +++ b/types/polygons-intersect/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "polygons-intersect-tests.ts" + ] +} diff --git a/types/polygons-intersect/tslint.json b/types/polygons-intersect/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/polygons-intersect/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 4cdeff6bd611ff5cfdd428c84592d950813bf30e Mon Sep 17 00:00:00 2001 From: Luis Date: Thu, 21 Mar 2019 11:22:56 +0000 Subject: [PATCH 100/337] added the correct GitHub repo on the header of the "child-process-promise"'s definition file --- types/child-process-promise/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/child-process-promise/index.d.ts b/types/child-process-promise/index.d.ts index 2740c8e197..ddc627ae9a 100644 --- a/types/child-process-promise/index.d.ts +++ b/types/child-process-promise/index.d.ts @@ -1,12 +1,11 @@ // Type definitions for child-process-promise 2.2.1 -// Project: https://github.com/TheDSCPL/types_child-process-promise +// Project: https://github.com/patrick-steele-idem/child-process-promise // Definitions by: Luis Paulo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.3.3 /// -// import child_process = require('child_process'); import { ChildProcess, ExecFileOptionsWithBufferEncoding, ExecFileOptionsWithOtherEncoding, @@ -111,3 +110,4 @@ declare namespace cpp { options?: Readonly ): ChildProcessPromise; } + From 972c8c30322b2fb367dc147cfe40749b3c06eb4f Mon Sep 17 00:00:00 2001 From: Luis Date: Thu, 21 Mar 2019 11:30:22 +0000 Subject: [PATCH 101/337] removed TypeScript version from the header of the "child-process-promise"'s definition file --- types/child-process-promise/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/child-process-promise/index.d.ts b/types/child-process-promise/index.d.ts index ddc627ae9a..ac0e06a6a8 100644 --- a/types/child-process-promise/index.d.ts +++ b/types/child-process-promise/index.d.ts @@ -2,7 +2,6 @@ // Project: https://github.com/patrick-steele-idem/child-process-promise // Definitions by: Luis Paulo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.3.3 /// From 7ca55fe3788d79cb863934bfd1c5677a59a89283 Mon Sep 17 00:00:00 2001 From: Luis Date: Thu, 21 Mar 2019 11:44:03 +0000 Subject: [PATCH 102/337] added "strictFunctionTypes" to "child-process-promise"'s tsconfig --- types/child-process-promise/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/types/child-process-promise/tsconfig.json b/types/child-process-promise/tsconfig.json index 0f3bf72033..b0f60c39eb 100644 --- a/types/child-process-promise/tsconfig.json +++ b/types/child-process-promise/tsconfig.json @@ -7,6 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From 623762f7ad6a00687ba58bbdd26f69242ea18555 Mon Sep 17 00:00:00 2001 From: Luis Date: Thu, 21 Mar 2019 12:00:00 +0000 Subject: [PATCH 103/337] implemented several of the fixes suggested by the travic bot on "child-process-promise"'s definition file --- types/child-process-promise/index.d.ts | 176 ++++++++++++------------- 1 file changed, 86 insertions(+), 90 deletions(-) diff --git a/types/child-process-promise/index.d.ts b/types/child-process-promise/index.d.ts index ac0e06a6a8..533d00c4ea 100644 --- a/types/child-process-promise/index.d.ts +++ b/types/child-process-promise/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/patrick-steele-idem/child-process-promise // Definitions by: Luis Paulo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 /// @@ -14,99 +15,94 @@ import { SpawnOptions } from 'child_process'; -export = cpp; -export as namespace cpp; - /** * Simple wrapper around the child_process module that makes use of promises */ -declare namespace cpp { - interface PromiseResult { - childProcess: ChildProcess, - stdout: Enc, - stderr: Enc - } - interface SpawnPromiseResult extends PromiseResult { - code: number - } - - interface ChildProcessPromise extends Promise { - childProcess: ChildProcess - } - - export interface Options { - /** - * Pass an additional capture option to buffer the result of stdout and/or stderr - * Default: [] - */ - capture?: []|['stdout']|['stderr']|['stdout'|'stderr']|['stderr'|'stdout'], - /** - * Array of the numbers that should be interpreted as successful execution codes - * Default: [0] - */ - successfulExitCodes?: number[] - } - - export function exec( - command: Readonly, - options: Readonly - ): ChildProcessPromise>; - export function exec( - command: Readonly, - options: Readonly - ): ChildProcessPromise>; - export function exec( - command: Readonly, - options: Readonly - ): ChildProcessPromise>; - export function exec( - command: Readonly, - options?: Readonly - ): ChildProcessPromise>; - - export function execFile( - file: Readonly, - options: Readonly - ): ChildProcessPromise>; - export function execFile( - file: Readonly, - args: ReadonlyArray | null, - options: Readonly - ): ChildProcessPromise>; - export function execFile( - file: Readonly, - options: Readonly - ): ChildProcessPromise>; - export function execFile( - file: Readonly, - args: ReadonlyArray | null, - options: Readonly - ): ChildProcessPromise>; - export function execFile( - file: Readonly, - options: Readonly - ): ChildProcessPromise>; - export function execFile( - file: Readonly, - args: ReadonlyArray | null, - options: Readonly - ): ChildProcessPromise>; - export function execFile( - file: Readonly, - args?: ReadonlyArray | null - ): ChildProcessPromise>; - - export function spawn( - command: Readonly, - args?: ReadonlyArray | null, - options?: Readonly - ): ChildProcessPromise; - - export function fork( - modulePath: string, - args?: ReadonlyArray, - options?: Readonly - ): ChildProcessPromise; +interface PromiseResult { + childProcess: ChildProcess; + stdout: Enc; + stderr: Enc; } +interface SpawnPromiseResult extends PromiseResult { + code: number; +} + +interface ChildProcessPromise extends Promise { + childProcess: ChildProcess; +} + +export interface Options { + /** + * Pass an additional capture option to buffer the result of stdout and/or stderr + * Default: [] + */ + capture?: []|['stdout']|['stderr']|['stdout'|'stderr']|['stderr'|'stdout']; + /** + * Array of the numbers that should be interpreted as successful execution codes + * Default: [0] + */ + successfulExitCodes?: number[]; +} + +export function exec( + command: Readonly, + options: Readonly +): ChildProcessPromise>; +export function exec( + command: Readonly, + options: Readonly +): ChildProcessPromise>; +export function exec( + command: Readonly, + options: Readonly +): ChildProcessPromise>; +export function exec( + command: Readonly, + options?: Readonly +): ChildProcessPromise>; + +export function execFile( + file: Readonly, + options: Readonly +): ChildProcessPromise>; +export function execFile( + file: Readonly, + args: ReadonlyArray | null, + options: Readonly +): ChildProcessPromise>; +export function execFile( + file: Readonly, + options: Readonly +): ChildProcessPromise>; +export function execFile( + file: Readonly, + args: ReadonlyArray | null, + options: Readonly +): ChildProcessPromise>; +export function execFile( + file: Readonly, + options: Readonly +): ChildProcessPromise>; +export function execFile( + file: Readonly, + args: ReadonlyArray | null, + options: Readonly +): ChildProcessPromise>; +export function execFile( + file: Readonly, + args?: ReadonlyArray | null +): ChildProcessPromise>; + +export function spawn( + command: Readonly, + args?: ReadonlyArray | null, + options?: Readonly +): ChildProcessPromise; + +export function fork( + modulePath: string, + args?: ReadonlyArray, + options?: Readonly +): ChildProcessPromise; \ No newline at end of file From 91b6d10a9d27e0ec686b722cec8acb1906ba1a72 Mon Sep 17 00:00:00 2001 From: Fabio Berta Date: Thu, 21 Mar 2019 13:02:10 +0100 Subject: [PATCH 104/337] add geolocate control --- types/react-map-gl/index.d.ts | 12 ++++++++++++ types/react-map-gl/react-map-gl-tests.tsx | 2 ++ 2 files changed, 14 insertions(+) diff --git a/types/react-map-gl/index.d.ts b/types/react-map-gl/index.d.ts index 23b723a594..e0b25765de 100644 --- a/types/react-map-gl/index.d.ts +++ b/types/react-map-gl/index.d.ts @@ -317,6 +317,18 @@ export interface FullscreenControlProps extends BaseControlProps { export class FullscreenControl extends BaseControl {} +export interface GeolocateControlProps extends BaseControlProps { + className?: string; + positionOptions?: MapboxGL.PositionOptions; + fitBoundsOptions?: MapboxGL.FitBoundsOptions; + trackUserLocation?: boolean; + showUserLocation?: boolean; + onViewStateChange?: (info: ViewStateChangeInfo) => void; + onViewportChange?: (viewState: ViewState) => void; +} + +export class GeolocateControl extends BaseControl {} + export interface DraggableControlProps extends BaseControlProps { draggable?: boolean; onDrag?: (event: DragEvent) => void; diff --git a/types/react-map-gl/react-map-gl-tests.tsx b/types/react-map-gl/react-map-gl-tests.tsx index 6740ad0eb4..17179fb0d6 100644 --- a/types/react-map-gl/react-map-gl-tests.tsx +++ b/types/react-map-gl/react-map-gl-tests.tsx @@ -6,6 +6,7 @@ import { SVGOverlay, HTMLOverlay, FullscreenControl, + GeolocateControl, CanvasRedrawOptions, HTMLRedrawOptions, SVGRedrawOptions, @@ -39,6 +40,7 @@ class MyMap extends React.Component<{}, State> { ref={this.setRefInteractive} > + { const { From c63dff33a24de9e8635abc0e21b86a50f8bf3a4b Mon Sep 17 00:00:00 2001 From: Andrew Haines Date: Thu, 21 Mar 2019 12:23:28 +0000 Subject: [PATCH 105/337] node-forge: Allow byte buffer or byte array for IV --- types/node-forge/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index 4a366deab7..47a601fc32 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -639,7 +639,7 @@ declare module "node-forge" { function createDecipher(algorithm: Algorithm, payload: util.ByteBuffer | Bytes): BlockCipher; interface StartOptions { - iv?: Bytes; + iv?: util.ByteBuffer | Byte[] | Bytes; tag?: util.ByteStringBuffer; tagLength?: number; additionalData?: string; From a45e83be1b4e1d9b4ac167515540bada1600e785 Mon Sep 17 00:00:00 2001 From: Luis Date: Thu, 21 Mar 2019 13:10:14 +0000 Subject: [PATCH 106/337] implemented several other of the fixes suggested by the travic bot on "child-process-promise"'s definition file --- types/child-process-promise/child-process-promise-tests.ts | 2 +- types/child-process-promise/index.d.ts | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/types/child-process-promise/child-process-promise-tests.ts b/types/child-process-promise/child-process-promise-tests.ts index c76f0c9a49..365e7e8f60 100644 --- a/types/child-process-promise/child-process-promise-tests.ts +++ b/types/child-process-promise/child-process-promise-tests.ts @@ -12,4 +12,4 @@ a.childProcess; // $ExpectType ChildProcess at.childProcess; // $ExpectType ChildProcess at.stdout; // $ExpectType string at.stderr; // $ExpectType string -})(); \ No newline at end of file +})(); diff --git a/types/child-process-promise/index.d.ts b/types/child-process-promise/index.d.ts index 533d00c4ea..7e4069cc03 100644 --- a/types/child-process-promise/index.d.ts +++ b/types/child-process-promise/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for child-process-promise 2.2.1 +// Type definitions for child-process-promise 2.2 // Project: https://github.com/patrick-steele-idem/child-process-promise // Definitions by: Luis Paulo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -19,6 +19,9 @@ import { * Simple wrapper around the child_process module that makes use of promises */ +// stop exporting everything by default +export {} + interface PromiseResult { childProcess: ChildProcess; stdout: Enc; @@ -105,4 +108,4 @@ export function fork( modulePath: string, args?: ReadonlyArray, options?: Readonly -): ChildProcessPromise; \ No newline at end of file +): ChildProcessPromise; From 99531b2ca0460648e3cedeaf22b487f4d7e42df9 Mon Sep 17 00:00:00 2001 From: Luis Date: Thu, 21 Mar 2019 13:18:06 +0000 Subject: [PATCH 107/337] implemented several other other of the fixes suggested by the travic bot on "child-process-promise"'s definition file --- types/child-process-promise/index.d.ts | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/types/child-process-promise/index.d.ts b/types/child-process-promise/index.d.ts index 7e4069cc03..de47199ab5 100644 --- a/types/child-process-promise/index.d.ts +++ b/types/child-process-promise/index.d.ts @@ -20,7 +20,7 @@ import { */ // stop exporting everything by default -export {} +export {}; interface PromiseResult { childProcess: ChildProcess; @@ -79,11 +79,6 @@ export function execFile( file: Readonly, options: Readonly ): ChildProcessPromise>; -export function execFile( - file: Readonly, - args: ReadonlyArray | null, - options: Readonly -): ChildProcessPromise>; export function execFile( file: Readonly, options: Readonly @@ -95,7 +90,8 @@ export function execFile( ): ChildProcessPromise>; export function execFile( file: Readonly, - args?: ReadonlyArray | null + args?: ReadonlyArray | null, + options?: Readonly ): ChildProcessPromise>; export function spawn( From 3824ecd0531e100bf877cf2350156fe2b92eb35e Mon Sep 17 00:00:00 2001 From: Hussein Ebrahimi Date: Thu, 21 Mar 2019 14:21:55 +0100 Subject: [PATCH 108/337] Chart.js Fixing issue in steppedLine inside ChartDataSets ChartDataSets.steppedLine is missing 'middle' value --- types/chart.js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 5a3116618d..8fa3a42ef9 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -512,7 +512,7 @@ declare namespace Chart { hoverBorderWidth?: number | number[]; label?: string; lineTension?: number; - steppedLine?: 'before' | 'after' | boolean; + steppedLine?: 'before' | 'after' | 'middle' | boolean; pointBorderColor?: ChartColor | ChartColor[]; pointBackgroundColor?: ChartColor | ChartColor[]; pointBorderWidth?: number | number[]; From a5dce4de6a3bc8f7bc6556bf3484c6ddd5d1e9ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Baumeyer?= Date: Thu, 21 Mar 2019 14:29:22 +0100 Subject: [PATCH 109/337] Update sharp types for 0.22.0 --- types/sharp/index.d.ts | 27 +++++++++++++++++++++++---- types/sharp/sharp-tests.ts | 2 +- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/types/sharp/index.d.ts b/types/sharp/index.d.ts index 5fcc47a26d..a8d51f4257 100644 --- a/types/sharp/index.d.ts +++ b/types/sharp/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for sharp 0.21 +// Type definitions for sharp 0.22 // Project: https://github.com/lovell/sharp // Definitions by: François Nguyen // Wooseop Kim @@ -138,7 +138,7 @@ declare namespace sharp { * @throws {Error} Invalid parameters * @returns A sharp instance that can be used to chain operations */ - joinChannel(images: string | Buffer | ArrayLike, options?: SharpOptions): Sharp; + joinChannel(images: string | Buffer | ArrayLike, options?: SharpOptions): Sharp; /** * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image. @@ -211,9 +211,21 @@ declare namespace sharp { * @param options overlay options * @throws {Error} Invalid parameters * @returns A sharp instance that can be used to chain operations + * @deprecated */ overlayWith(image?: string | Buffer, options?: OverlayOptions): Sharp; + /** + * Composite image(s) over the processed (resized, extracted etc.) image. + * + * The images to composite must be the same size or smaller than the processed image. + * If both `top` and `left` options are provided, they take precedence over `gravity`. + * @param images - Ordered list of images to composite + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + composite(images: Array<{ input: string | Buffer } & OverlayOptions>): Sharp; + //#endregion //#region Input functions @@ -570,7 +582,7 @@ declare namespace sharp { * @throws {Error} Invalid parameters * @returns A sharp instance that can be used to chain operations */ - resize(width?: number|null, height?: number|null, options?: ResizeOptions): Sharp; + resize(width?: number | null, height?: number | null, options?: ResizeOptions): Sharp; /** * Extends/pads the edges of the image with the provided background colour. @@ -615,7 +627,9 @@ declare namespace sharp { failOnError?: boolean; /** Number representing the DPI for vector images. (optional, default 72) */ density?: number; - /** Page number to extract for multi-page input (GIF, TIFF). (optional, default 0) */ + /** Number of pages to extract for multi-page input (GIF, TIFF, PDF), use -1 for all pages */ + pages?: number; + /** Page number to start extracting from for multi-page input (GIF, TIFF, PDF), zero based. (optional, default 0) */ page?: number; /** Describes raw pixel input image data. See raw() for pixel ordering. */ raw?: Raw; @@ -883,6 +897,8 @@ declare namespace sharp { } interface OverlayOptions { + /** how to blend this image with the image below. (optional, default `'over'`) */ + blend?: Blend; /** gravity at which to place the overlay. (optional, default 'centre') */ gravity?: Gravity; /** the pixel offset from the top edge. */ @@ -966,6 +982,9 @@ declare namespace sharp { srgb: string; } + type Blend = 'clear' | 'source' | 'over' | 'in' | 'out' | 'atop' | 'dest' | 'dest-over' | 'dest-in' | 'dest-out' | 'dest-atop' | 'xor' | 'add' | 'saturate' | 'multiply' | 'screen' | 'overlay' + | 'darken' | 'lighten' | 'colour-dodge' | 'colour-dodge' | 'colour-burn' | 'colour-burn' | 'hard-light' | 'soft-light' | 'difference' | 'exclusion'; + type Gravity = number | string; interface GravityEnum { diff --git a/types/sharp/sharp-tests.ts b/types/sharp/sharp-tests.ts index 8c02e8c98f..84e1d33f4b 100644 --- a/types/sharp/sharp-tests.ts +++ b/types/sharp/sharp-tests.ts @@ -26,7 +26,7 @@ sharp('input.png') .rotate(180) .resize(300) .flatten({ background: "#ff6600" }) - .overlayWith('overlay.png', { gravity: sharp.gravity.southeast }) + .composite([{ input: 'overlay.png', gravity: sharp.gravity.southeast }]) .sharpen() .withMetadata() .webp({ From ae3c3069065b59646fcc9040662fde41c7f81339 Mon Sep 17 00:00:00 2001 From: error Date: Thu, 21 Mar 2019 11:03:58 -0500 Subject: [PATCH 110/337] add isScheduled --- types/three/three-core.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index f39d28b565..d018d3241d 100755 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -239,6 +239,7 @@ export class AnimationAction { stop(): AnimationAction; reset(): AnimationAction; isRunning(): boolean; + isScheduled(): boolean; startAt(time: number): AnimationAction; setLoop(mode: AnimationActionLoopStyles, repetitions: number): AnimationAction; setEffectiveWeight(weight: number): AnimationAction; From 44ae9e2201ec7bae42e9d58c60a747c28ba9f90b Mon Sep 17 00:00:00 2001 From: Federico Bond Date: Thu, 21 Mar 2019 00:15:45 -0300 Subject: [PATCH 111/337] trezor-connect: Update signTransaction params --- types/trezor-connect/index.d.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/types/trezor-connect/index.d.ts b/types/trezor-connect/index.d.ts index 282117efda..daa19b2a02 100644 --- a/types/trezor-connect/index.d.ts +++ b/types/trezor-connect/index.d.ts @@ -270,10 +270,31 @@ export interface OpReturnOutput { export type Output = RegularOutput | InternalOutput | SendMaxOutput | OpReturnOutput; +export interface BinOutput { + amount: number; + script_pubkey: string; +} + +export interface RefTransaction { + hash: string; + version?: number; + inputs: Input[]; + bin_outputs: BinOutput[]; + lock_time?: number; + extra_data?: string; + timestamp?: number; + version_group_id?: number; +} + export interface SignTransactionParams extends CommonParams { inputs: Input[]; outputs: Output[]; + refTxs: RefTransaction[]; coin: string; + locktime?: number; + version?: number; + expiry?: number; + branchId?: number; push?: boolean; } From c877577f2786e471839d8f4764a09b6461d4891e Mon Sep 17 00:00:00 2001 From: Federico Bond Date: Thu, 21 Mar 2019 12:16:18 -0300 Subject: [PATCH 112/337] trezor-connect: Add optional iv to CipherKeyValueParams interface --- types/trezor-connect/index.d.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/types/trezor-connect/index.d.ts b/types/trezor-connect/index.d.ts index daa19b2a02..3c55ead363 100644 --- a/types/trezor-connect/index.d.ts +++ b/types/trezor-connect/index.d.ts @@ -126,8 +126,9 @@ export interface CipherKeyValueParams extends CommonParams { path: string | number[]; key?: string; value?: string; - askOnEncrypt?: true; - askOnDecrypt?: true; + askOnEncrypt?: boolean; + askOnDecrypt?: boolean; + iv?: string; } export interface CipherKeyValue extends CommonParams { @@ -334,6 +335,11 @@ export namespace TrezorConnect { */ function getFeatures(params?: CommonParams): Promise>; + /** + * Retrieves the settings that TrezorConnect was initialized with. + */ + function getSettings(): Promise>; + /** * Asks device to encrypt value using the private key derived by given BIP32 * path and the given key. IV is always computed automatically. From 5c86d99b2928e41703f3371ed7c830ad21744ba8 Mon Sep 17 00:00:00 2001 From: Federico Bond Date: Thu, 21 Mar 2019 12:16:41 -0300 Subject: [PATCH 113/337] trezor-connect: Add optional address to GetAddressParams --- types/trezor-connect/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/trezor-connect/index.d.ts b/types/trezor-connect/index.d.ts index 3c55ead363..1c17b29ecd 100644 --- a/types/trezor-connect/index.d.ts +++ b/types/trezor-connect/index.d.ts @@ -147,6 +147,7 @@ export interface ResetDeviceParams extends CommonParams { export interface GetAddressParams extends CommonParams { path: string | number[]; + address?: string; showOnTrezor?: boolean; coin?: string; crossChain?: boolean; From 4d9614319163ce1ba0bb72edcf12a62c66dd9973 Mon Sep 17 00:00:00 2001 From: Federico Bond Date: Thu, 21 Mar 2019 12:25:16 -0300 Subject: [PATCH 114/337] trezor-connect: Add firmwareRelease to Device params --- types/trezor-connect/index.d.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/types/trezor-connect/index.d.ts b/types/trezor-connect/index.d.ts index 1c17b29ecd..24fc6b9e6b 100644 --- a/types/trezor-connect/index.d.ts +++ b/types/trezor-connect/index.d.ts @@ -195,11 +195,25 @@ export type DeviceMode = 'normal' | 'bootloader' | 'initialize' | 'seedless'; export type DeviceFirmwareStatus = 'valid' | 'outdated' | 'required'; +export interface FirmwareRelease { + required: boolean; + version: number[]; + min_bridge_version: number[]; + min_firmware_version: number[]; + bootloader_version: number[]; + min_bootloader_version: number[]; + url: string; + channel: string; + fingerprint: string; + changelog: string; +} + export type Device = { type: 'acquired', path: string, label: string, firmware: DeviceFirmwareStatus, + firmwareRelease: FirmwareRelease, status: DeviceStatus, mode: DeviceMode, state: string | null, From c46607a0a42cc0d8812fad97dc45b0175eedcafe Mon Sep 17 00:00:00 2001 From: Federico Bond Date: Thu, 21 Mar 2019 12:42:55 -0300 Subject: [PATCH 115/337] trezor-connect: Update type definition for AccountInfo interface --- types/trezor-connect/index.d.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/types/trezor-connect/index.d.ts b/types/trezor-connect/index.d.ts index 24fc6b9e6b..540fad6459 100644 --- a/types/trezor-connect/index.d.ts +++ b/types/trezor-connect/index.d.ts @@ -54,6 +54,18 @@ export interface PublicKey { depth: number; // BIP32 serialization format } +export interface Utxo { + index: number; // index of output IN THE TRANSACTION + transactionHash: string; // hash of the transaction + value: number; // how much money sent + addressPath: [number, number]; // path + height: number | null; // null == unconfirmed + coinbase: boolean; + tsize: number; // total size - in case of segwit, total, with segwit data + vsize: number; // virtual size - segwit concept - same as size in non-segwit + own: boolean; +} + export interface GetAccountInfoParams extends CommonParams { path?: number[]; // NOTE: xpub?: string; // if both these fields are missing, the user will select an account @@ -70,6 +82,11 @@ export interface AccountInfo { balance: number; confirmed: number; + transactions: number; + utxo: Utxo[]; + usedAddresses: Array<{ address: string, received: number }>; + unusedAddresses: string[]; + // These fields are returned, presumably, to save further calls when the use case requires // a usable address: address: string; From 0200fee41489ef58ec97f78a063ee5cdce87865c Mon Sep 17 00:00:00 2001 From: Federico Bond Date: Thu, 21 Mar 2019 13:21:44 -0300 Subject: [PATCH 116/337] trezor-connect: Add optional CommonParams to wipeDevice --- types/trezor-connect/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/trezor-connect/index.d.ts b/types/trezor-connect/index.d.ts index 540fad6459..099e0ef37c 100644 --- a/types/trezor-connect/index.d.ts +++ b/types/trezor-connect/index.d.ts @@ -382,7 +382,7 @@ export namespace TrezorConnect { /** * Resets device to factory defaults and removes all private data. */ - function wipeDevice(): Promise>; + function wipeDevice(params?: CommonParams): Promise>; /** * Performs device setup and generates a new seed. From e346a41f6e13975eaac2ba115b7a0f17dff671ed Mon Sep 17 00:00:00 2001 From: Leon Thorne Date: Thu, 21 Mar 2019 12:27:45 -0400 Subject: [PATCH 117/337] Add types for @zeit/next-source-maps --- types/zeit__next-source-maps/index.d.ts | 14 ++++++++++ types/zeit__next-source-maps/tsconfig.json | 26 +++++++++++++++++++ types/zeit__next-source-maps/tslint.json | 3 +++ .../zeit__next-source-maps-tests.ts | 3 +++ 4 files changed, 46 insertions(+) create mode 100644 types/zeit__next-source-maps/index.d.ts create mode 100644 types/zeit__next-source-maps/tsconfig.json create mode 100644 types/zeit__next-source-maps/tslint.json create mode 100644 types/zeit__next-source-maps/zeit__next-source-maps-tests.ts diff --git a/types/zeit__next-source-maps/index.d.ts b/types/zeit__next-source-maps/index.d.ts new file mode 100644 index 0000000000..9a044b8038 --- /dev/null +++ b/types/zeit__next-source-maps/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for @zeit/next-typescript 0.0.4-canary.1 +// Project: https://github.com/zeit/next-plugins/tree/master/packages/next-source-maps, https://github.com/zeit/next-plugins +// Definitions by: ldthorne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.3 + +import { ServerConfig } from 'next'; + +declare function withSourceMaps( + /** @default {} */ + nextConfig?: ServerConfig +): ServerConfig; + +export = withSourceMaps; diff --git a/types/zeit__next-source-maps/tsconfig.json b/types/zeit__next-source-maps/tsconfig.json new file mode 100644 index 0000000000..1e1cd7db5e --- /dev/null +++ b/types/zeit__next-source-maps/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@zeit/next-source-maps": ["zeit__next-source-maps"] + } + }, + "files": [ + "index.d.ts", + "zeit__next-source-maps-tests.ts" + ] +} diff --git a/types/zeit__next-source-maps/tslint.json b/types/zeit__next-source-maps/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/zeit__next-source-maps/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/zeit__next-source-maps/zeit__next-source-maps-tests.ts b/types/zeit__next-source-maps/zeit__next-source-maps-tests.ts new file mode 100644 index 0000000000..dbf775dcfc --- /dev/null +++ b/types/zeit__next-source-maps/zeit__next-source-maps-tests.ts @@ -0,0 +1,3 @@ +import withSourceMaps = require('@zeit/next-source-maps'); + +withSourceMaps({}); // $ExpectType NextConfig From f15103b30d6ba2c02d76a35ac2fb64a598e32407 Mon Sep 17 00:00:00 2001 From: Ian Sanders Date: Thu, 21 Mar 2019 12:45:42 -0400 Subject: [PATCH 118/337] Add linedelimiters property to diff Hunk --- types/diff/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/diff/index.d.ts b/types/diff/index.d.ts index 5afb72192e..15fda0d409 100644 --- a/types/diff/index.d.ts +++ b/types/diff/index.d.ts @@ -142,6 +142,7 @@ export interface Hunk { newStart: number; newLines: number; lines: string[]; + linedelimiters?: string[]; } export interface BestPath { From a1e7a31846386ce5f0483fd7c27b8679361c998c Mon Sep 17 00:00:00 2001 From: Jake Boone Date: Thu, 21 Mar 2019 10:00:34 -0700 Subject: [PATCH 119/337] removed screenfull which provides its own types --- notNeededPackages.json | 6 ++ types/screenfull/index.d.ts | 85 ------------------ types/screenfull/screenfull-tests.ts | 46 ---------- types/screenfull/tsconfig.json | 24 ----- types/screenfull/tslint.json | 3 - types/screenfull/v3/index.d.ts | 36 -------- types/screenfull/v3/screenfull-tests.ts | 112 ------------------------ types/screenfull/v3/tsconfig.json | 29 ------ types/screenfull/v3/tslint.json | 79 ----------------- 9 files changed, 6 insertions(+), 414 deletions(-) delete mode 100644 types/screenfull/index.d.ts delete mode 100644 types/screenfull/screenfull-tests.ts delete mode 100644 types/screenfull/tsconfig.json delete mode 100644 types/screenfull/tslint.json delete mode 100644 types/screenfull/v3/index.d.ts delete mode 100644 types/screenfull/v3/screenfull-tests.ts delete mode 100644 types/screenfull/v3/tsconfig.json delete mode 100644 types/screenfull/v3/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index 7efe76e0d7..cf61daf58d 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -2010,6 +2010,12 @@ "sourceRepoURL": "https://github.com/Lellansin/node-scanf", "asOfVersion": "0.7.3" }, + { + "libraryName": "screenfull", + "typingsPackageName": "screenfull", + "sourceRepoURL": "https://github.com/sindresorhus/screenfull.js", + "asOfVersion": "4.1.0" + }, { "libraryName": "sendgrid", "typingsPackageName": "sendgrid", diff --git a/types/screenfull/index.d.ts b/types/screenfull/index.d.ts deleted file mode 100644 index 2c7b93e453..0000000000 --- a/types/screenfull/index.d.ts +++ /dev/null @@ -1,85 +0,0 @@ -// Type definitions for screenfull.js 4.0 -// Project: https://github.com/sindresorhus/screenfull.js -// Definitions by: Ilia Choly -// lionelb -// Joel Shepherd -// BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.5 - -export = screenfull; -export as namespace screenfull; - -declare const screenfull: screenfull.Screenfull | false; - -declare namespace screenfull { - interface Screenfull { - /** - * Returns a boolean whether fullscreen is active. - */ - readonly isFullscreen: boolean; - /** - * Returns the element currently in fullscreen, otherwise `null`. - */ - readonly element: Element | null; - /** - * Returns a boolean whether you are allowed to enter fullscreen. If your page is inside an `