diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index a38c928333..f2cc95105c 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -812,6 +812,8 @@ export interface AuthorizeOptions { login_hint?: string; prompt?: string; mode?: "login" | "signUp"; + acccessType?: string; + approvalPrompt?: string; } export interface CheckSessionOptions extends AuthorizeOptions { diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 92f0a6999b..ba6ebdc5ac 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -1056,3 +1056,113 @@ const firehoseEventHandler: AWSLambda.FirehoseTransformationHandler = ( ] }); }; + +declare let lexEvent: AWSLambda.LexEvent; +lexEvent = { + currentIntent: { + name: 'intent-name', + slots: { + slot1: null, + slot2: 'value2', + }, + slotDetails: { + slot1: { + resolutions: [ + { value: 'value1' }, + ], + originalValue: 'originalValue', + } + }, + confirmationStatus: 'None', + }, + bot: { + name: 'bot name', + alias: 'bot alias', + version: 'bot version', + }, + userId: 'User ID specified in the POST request to Amazon Lex.', + inputTranscript: 'Text used to process the request', + invocationSource: 'FulfillmentCodeHook', + outputDialogMode: 'Text', + messageVersion: '1.0', + sessionAttributes: { + key1: 'value1', + key2: 'value2', + }, + requestAttributes: { + key1: 'value1', + key2: 'value2', + } +}; + +declare let lexResult: AWSLambda.LexResult; +declare let lexDialogAction: AWSLambda.LexDialogAction; +declare let lexDialogActionBase: AWSLambda.LexDialogActionBase; +declare let lexDialogActionClose: AWSLambda.LexDialogActionClose; +declare let lexDialogActionConfirmIntent: AWSLambda.LexDialogActionConfirmIntent; +declare let lexDialogActionDelegate: AWSLambda.LexDialogActionDelegate; +declare let lexDialogActionElicitIntent: AWSLambda.LexDialogActionElicitIntent; +declare let lexDialogActionElicitSlot: AWSLambda.LexDialogActionElicitSlot; +declare let lexGenericAttachment: AWSLambda.LexGenericAttachment; + +lexResult = { + sessionAttributes: { + attrib1: 'Value One', + }, + dialogAction: { + type: 'Close', + fulfillmentState: 'Failed', + }, +}; + +str = lexGenericAttachment.title; +str = lexGenericAttachment.subTitle; +str = lexGenericAttachment.imageUrl; +str = lexGenericAttachment.attachmentLinkUrl; +str = lexGenericAttachment.buttons[0].text; +str = lexGenericAttachment.buttons[0].value; + +lexDialogAction.type === 'Close'; +lexDialogAction.type === 'ConfirmIntent'; +lexDialogAction.type === 'Delegate'; +lexDialogAction.type === 'ElicitIntent'; +lexDialogAction.type === 'ElicitSlot'; + +lexDialogActionBase.message!.contentType === 'CustomPayload'; +lexDialogActionBase.message!.contentType === 'PlainText'; +lexDialogActionBase.message!.contentType === 'SSML'; +str = lexDialogActionBase.message!.content; +num = lexDialogActionBase.responseCard!.version; +lexDialogActionBase.responseCard!.contentType === 'application/vnd.amazonaws.card.generic'; +// $ExpectType LexGenericAttachment +lexDialogActionBase.responseCard!.genericAttachments[0]; + +lexDialogActionClose.type === 'Close'; +lexDialogActionClose.fulfillmentState === 'Failed'; +lexDialogActionClose.fulfillmentState === 'Fulfilled'; + +lexDialogActionConfirmIntent.type === 'ConfirmIntent'; +str = lexDialogActionConfirmIntent.intentName; +strOrNull = lexDialogActionConfirmIntent.slots['example']; + +lexDialogActionDelegate.type === 'Delegate'; +strOrNull = lexDialogActionDelegate.slots['example']; + +lexDialogActionElicitIntent.type === 'ElicitIntent'; +lexDialogActionElicitSlot.type === 'ElicitSlot'; +strOrNull = lexDialogActionElicitSlot.slots['example']; +str = lexDialogActionElicitSlot.slotToElicit; +str = lexDialogActionElicitSlot.intentName; + +const lexEventHandler: AWSLambda.LexHandler = async ( + event: AWSLambda.LexEvent, + context: AWSLambda.Context, +) => { + // $ExpectType LexEvent + event; + + // $ExpectType Context + context; + str = context.functionName; + return lexResult; +}; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 4cafe3d2da..52314529bc 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -876,6 +876,100 @@ export interface SQSMessageAttributes { [name: string]: SQSMessageAttribute; } +// Lex +// https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html#supported-event-source-lex +export interface LexEvent { + currentIntent: { + name: string; + slots: { [name: string]: string | null }; + slotDetails: LexSlotDetails; + confirmationStatus: 'None' | 'Confirmed' | 'Denied'; + }; + bot: { + name: string; + alias: string; + version: string; + }; + userId: string; + inputTranscript: string; + invocationSource: 'DialogCodeHook' | 'FulfillmentCodeHook'; + outputDialogMode: 'Text' | 'Voice'; + messageVersion: '1.0'; + sessionAttributes: { [key: string]: string }; + requestAttributes: { [key: string]: string } | null; +} + +export interface LexSlotResolution { + value: string; +} + +export interface LexSlotDetails { + [name: string]: { + // The following line only works in TypeScript Version: 3.0, The array should have at least 1 and no more than 5 items + // resolutions: [LexSlotResolution, LexSlotResolution?, LexSlotResolution?, LexSlotResolution?, LexSlotResolution?]; + resolutions: LexSlotResolution[] + originalValue: string; + }; +} + +export interface LexGenericAttachment { + title: string; + subTitle: string; + imageUrl: string; + attachmentLinkUrl: string; + buttons: Array<{ + text: string; + value: string; + }>; +} + +export interface LexDialogActionBase { + type: 'Close' | 'ElicitIntent' | 'ElicitSlot' | 'ConfirmIntent'; + message?: { + contentType: 'PlainText' | 'SSML' | 'CustomPayload'; + content: string; + }; + responseCard?: { + version: number; + contentType: 'application/vnd.amazonaws.card.generic'; + genericAttachments: LexGenericAttachment[]; + }; +} + +export interface LexDialogActionClose extends LexDialogActionBase { + type: 'Close'; + fulfillmentState: 'Fulfilled' | 'Failed'; +} + +export interface LexDialogActionElicitIntent extends LexDialogActionBase { + type: 'ElicitIntent'; +} + +export interface LexDialogActionElicitSlot extends LexDialogActionBase { + type: 'ElicitSlot'; + intentName: string; + slots: { [name: string]: string | null }; + slotToElicit: string; +} + +export interface LexDialogActionConfirmIntent extends LexDialogActionBase { + type: 'ConfirmIntent'; + intentName: string; + slots: { [name: string]: string | null }; +} + +export interface LexDialogActionDelegate { + type: 'Delegate'; + slots: { [name: string]: string | null }; +} + +export type LexDialogAction = LexDialogActionClose | LexDialogActionElicitIntent | LexDialogActionElicitSlot | LexDialogActionConfirmIntent | LexDialogActionDelegate; + +export interface LexResult { + sessionAttributes?: { [key: string]: string }; + dialogAction: LexDialogAction; +} + /** * AWS Lambda handler function. * http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html @@ -938,6 +1032,9 @@ export type ScheduledHandler = Handler; // TODO: Alexa +export type LexHandler = Handler; +export type LexCallback = Callback; + export type APIGatewayProxyHandler = Handler; export type APIGatewayProxyCallback = Callback; export type ProxyHandler = APIGatewayProxyHandler; // Old name diff --git a/types/babel__traverse/babel__traverse-tests.ts b/types/babel__traverse/babel__traverse-tests.ts index 70f8c5f0b6..98a0338021 100644 --- a/types/babel__traverse/babel__traverse-tests.ts +++ b/types/babel__traverse/babel__traverse-tests.ts @@ -150,3 +150,8 @@ const VisitorStateTest: Visitor = { } } }; + +const VisitorAliasTest: Visitor = { + Function() {}, + Expression() {}, +}; diff --git a/types/babel__traverse/index.d.ts b/types/babel__traverse/index.d.ts index 89e242129b..fe817d5daf 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -145,6 +145,8 @@ export class Binding { export type Visitor = VisitNodeObject & { [Type in Node["type"]]?: VisitNode>; +} & { + [K in keyof t.Aliases]?: VisitNode }; export type VisitNode = VisitNodeFunction | VisitNodeObject; diff --git a/types/babel__traverse/package.json b/types/babel__traverse/package.json index 2442a952db..47a2d3dc48 100644 --- a/types/babel__traverse/package.json +++ b/types/babel__traverse/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.3.0" } } diff --git a/types/better-sqlite3/better-sqlite3-tests.ts b/types/better-sqlite3/better-sqlite3-tests.ts index dddd69bea8..f5a6c0e070 100644 --- a/types/better-sqlite3/better-sqlite3-tests.ts +++ b/types/better-sqlite3/better-sqlite3-tests.ts @@ -69,3 +69,12 @@ trans.default('name'); trans.deferred('name'); trans.immediate('name'); trans.exclusive('name'); + +const transTyped = db.transaction((param: number) => stmt.all(param)); +transTyped(1); +trans.default(1); +trans.deferred(1); +trans.immediate(1); +trans.exclusive(1); +// $ExpectError +transTyped('name'); diff --git a/types/better-sqlite3/index.d.ts b/types/better-sqlite3/index.d.ts index 2c027ff6e6..32a71d96af 100644 --- a/types/better-sqlite3/index.d.ts +++ b/types/better-sqlite3/index.d.ts @@ -4,10 +4,17 @@ // Mathew Rumsey // Santiago Aguilar // Alessandro Vergani +// Andrew Kaiser // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 import Integer = require("integer"); +type VariableArgFunction = (...params: any[]) => any; +type ArgumentTypes = F extends (...args: infer A) => any + ? A + : never; + declare namespace BetterSqlite3 { interface Statement { database: Database; @@ -34,12 +41,12 @@ declare namespace BetterSqlite3 { type: string | null; } - interface Transaction { - (...params: any[]): any; - default(...params: any[]): any; - deferred(...params: any[]): any; - immediate(...params: any[]): any; - exclusive(...params: any[]): any; + interface Transaction { + (...params: ArgumentTypes): any; + default(...params: ArgumentTypes): any; + deferred(...params: ArgumentTypes): any; + immediate(...params: ArgumentTypes): any; + exclusive(...params: ArgumentTypes): any; } interface Database { @@ -50,7 +57,7 @@ declare namespace BetterSqlite3 { inTransaction: boolean; prepare(source: string): Statement; - transaction(fn: (...params: any[]) => any): Transaction; + transaction(fn: F): Transaction; exec(source: string): this; pragma(source: string, options?: Database.PragmaOptions): any; checkpoint(databaseName?: string): this; @@ -113,7 +120,7 @@ declare namespace Database { type SqliteError = typeof SqliteError; type Statement = BetterSqlite3.Statement; type ColumnDefinition = BetterSqlite3.ColumnDefinition; - type Transaction = BetterSqlite3.Transaction; + type Transaction = BetterSqlite3.Transaction; type Database = BetterSqlite3.Database; } diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index b2fb68d4d7..bbafa0301c 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -585,6 +585,11 @@ declare namespace Bull { */ getJobCounts(): Promise; + /** + * Returns a promise that resolves with the job counts for the given queue of the given types. + */ + getJobCountByTypes(types: string[] | string): Promise; + /** * Returns a promise that resolves with the quantity of completed jobs. */ diff --git a/types/bytebuffer/index.d.ts b/types/bytebuffer/index.d.ts index bafed6edf8..eaa1a509d5 100644 --- a/types/bytebuffer/index.d.ts +++ b/types/bytebuffer/index.d.ts @@ -127,7 +127,7 @@ declare class ByteBuffer * Calculates the number of UTF8 characters of a string.JavaScript itself uses UTF- 16, so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF. */ static calculateUTF8Chars( str: string ): number; - + /** * Calculates the number of UTF8 bytes of a string. This is an alias of ByteBuffer#calculateUTF8Bytes. */ @@ -574,6 +574,11 @@ declare class ByteBuffer */ writeInt8( value: number, offset?: number ): ByteBuffer; + /** + * Write a 64bit signed integer. This is an alias of ByteBuffer#writeInt64. + */ + writeLong( value: number | Long, offset?: number ): ByteBuffer; + /** * Writes a 16bit signed integer. This is an alias of ByteBuffer#writeInt16. */ diff --git a/types/diff/diff-tests.ts b/types/diff/diff-tests.ts index 2f640da490..845b307132 100644 --- a/types/diff/diff-tests.ts +++ b/types/diff/diff-tests.ts @@ -1,47 +1,55 @@ -import jsdiff = require('diff'); +import * as diff from 'diff'; + const one = 'beep boop'; const other = 'beep boob blah'; -let diff = jsdiff.diffChars(one, other); -printDiff(diff); +let changes = diff.diffChars(one, other); +examineChanges(changes); -const diffArraysResult = jsdiff.diffArrays(['a', 'b', 'c'], ['a', 'c', 'd']); +// $ExpectType void +diff.diffChars(one, other, { + callback: (err, value) => { + err; // $ExpectType undefined + value; // $ExpectType Change[] | undefined + }, +}); +// $ExpectType void +diff.diffChars(one, other, (err, value) => { + err; // $ExpectType undefined + value; // $ExpectType Change[] | undefined +}); + +const diffArraysResult = diff.diffArrays(['a', 'b', 'c'], ['a', 'c', 'd']); diffArraysResult.forEach(result => { - if (result.added) { - console.log(`added ${result.value.length} line(s):`, ...result.value); - } else if (result.removed) { - console.log(`removed ${result.value.length} line(s):`, ...result.value); - } else { - console.log(`no changes`); - } + result.added; // $ExpectType boolean | undefined + result.removed; // $ExpectType boolean | undefined + result.value; // $ExpectType string[] + result.count; // $ExpectType number | undefined }); interface DiffObj { value: number; } -const a: DiffObj = {value: 0}; -const b: DiffObj = {value: 1}; -const c: DiffObj = {value: 2}; -const d: DiffObj = {value: 3}; -const arrayOptions: jsdiff.IArrayOptions = { - comparator: (left: DiffObj, right: DiffObj) => { - return left.value === right.value; - } +const a: DiffObj = { value: 0 }; +const b: DiffObj = { value: 1 }; +const c: DiffObj = { value: 2 }; +const d: DiffObj = { value: 3 }; +const arrayOptions: diff.ArrayOptions = { + comparator: (left, right) => { + return left.value === right.value; + }, }; -const diffResult = jsdiff.diffArrays([a, b, c], [a, b, d], arrayOptions); -diffResult.forEach(result => { - if (result.added) { - console.log(`added ${result.value.length} line(s):`, ...result.value); - } else if (result.removed) { - console.log(`removed ${result.value.length} line(s):`, ...result.value); - } else { - console.log(`no changes`); - } +const arrayChanges = diff.diffArrays([a, b, c], [a, b, d], arrayOptions); +arrayChanges.forEach(result => { + result.added; // $ExpectType boolean | undefined + result.removed; // $ExpectType boolean | undefined + result.value; // $ExpectType DiffObj[] + result.count; // $ExpectType number | undefined }); // -------------------------- -class LineDiffWithoutWhitespace extends jsdiff.Diff { +class LineDiffWithoutWhitespace extends diff.Diff { tokenize(value: string): any { return value.split(/^/m); } @@ -52,71 +60,62 @@ class LineDiffWithoutWhitespace extends jsdiff.Diff { } const obj = new LineDiffWithoutWhitespace(); -diff = obj.diff(one, other); -printDiff(diff); +changes = obj.diff(one, other); +examineChanges(changes); -function printDiff(diff: jsdiff.IDiffResult[]) { - function addLineHeader(decorator: string, str: string | string[]) { - return (typeof str === 'string' ? str.split("\n") : str).map((line, index, array) => { - if (index === array.length - 1 && line === "") { - return line; - } else { - return decorator + line; - } - }).join("\n"); - } - - diff.forEach((part) => { - if (part.added) { - console.log(addLineHeader("+", part.value)); - } else if (part.removed) { - console.log(addLineHeader("-", part.value)); - } else { - console.log(addLineHeader(" ", part.value)); - } +function examineChanges(diff: diff.Change[]) { + diff.forEach(part => { + part.added; // $ExpectType boolean | undefined + part.removed; // $ExpectType boolean | undefined + part.value; // $ExpectType string + part.count; // $ExpectType number | undefined }); } -function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { - const verifyPatch = jsdiff.parsePatch( - jsdiff.createTwoFilesPatch("oldFile.ts", "newFile.ts", oldStr, newStr, - "old", "new", { context: 1 })); +function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: diff.ParsedDiff) { + const verifyPatch = diff.parsePatch( + diff.createTwoFilesPatch('oldFile.ts', 'newFile.ts', oldStr, newStr, 'old', 'new', { + context: 1, + }) + ); - if (JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !== JSON.stringify(uniDiff, Object.keys(uniDiff).sort())) { - console.error("Patch did not match uniDiff"); + if ( + JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !== + JSON.stringify(uniDiff, Object.keys(uniDiff).sort()) + ) { + throw new Error('Patch did not match uniDiff'); } } -function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { - const verifyApply = [ - jsdiff.applyPatch(oldStr, uniDiff), - jsdiff.applyPatch(oldStr, [uniDiff]) - ]; - jsdiff.applyPatches([uniDiff], { - loadFile: (index: number, callback: (err: Error, data: string) => void) => { +function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: diff.ParsedDiff) { + const verifyApply = [diff.applyPatch(oldStr, uniDiff), diff.applyPatch(oldStr, [uniDiff])]; + diff.applyPatches([uniDiff], { + loadFile: (index, callback) => { + index; // $ExpectType ParsedDiff callback(undefined, one); }, - patched: (index: number, content: string) => { + patched: (index, content) => { + index; // $ExpectType ParsedDiff verifyApply.push(content); }, complete: (err?: Error) => { if (err) { - console.error(err); + throw err; } verifyApply.forEach(result => { if (result !== newStr) { - console.error("Result did not match newStr"); + throw new Error('Result did not match newStr'); } }); - } + }, }); } -const uniDiffPatch = jsdiff.structuredPatch("oldFile.ts", "newFile.ts", one, other, - "old", "new", { context: 1 }); +const uniDiffPatch = diff.structuredPatch('oldFile.ts', 'newFile.ts', one, other, 'old', 'new', { + context: 1, +}); verifyPatchMethods(one, other, uniDiffPatch); -const uniDiffStr = jsdiff.createPatch("file.ts", one, other, "old", "new", - { context: 1 }); -const uniDiffApply = jsdiff.parsePatch(uniDiffStr)[0]; +const uniDiffStr = diff.createPatch('file.ts', one, other, 'old', 'new', { context: 1 }); +const uniDiffApply = diff.parsePatch(uniDiffStr)[0]; verifyApplyMethods(one, other, uniDiffApply); diff --git a/types/diff/index.d.ts b/types/diff/index.d.ts index 760aee4e61..fa0e4e2e3d 100644 --- a/types/diff/index.d.ts +++ b/types/diff/index.d.ts @@ -1,121 +1,402 @@ -// Type definitions for diff 3.5 +// Type definitions for diff 4.0 // Project: https://github.com/kpdecker/jsdiff // Definitions by: vvakame // szdc // moc-yuto +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -export = JsDiff; -export as namespace JsDiff; +export as namespace Diff; -declare namespace JsDiff { - interface IOptions { - ignoreCase: boolean; - } +export type Callback = (err: undefined, value?: Change[]) => void; - interface ILinesOptions extends IOptions { - ignoreWhitespace?: boolean; - newlineIsToken?: boolean; - } - - interface IArrayOptions { - comparator?: (left: any, right: any) => boolean; - } - - interface IDiffResult { - value: string; - count?: number; - added?: boolean; - removed?: boolean; - } - - interface IDiffArraysResult { - value: T[]; - count?: number; - added?: boolean; - removed?: boolean; - } - - interface IBestPath { - newPos: number; - componenets: IDiffResult[]; - } - - interface IHunk { - oldStart: number; - oldLines: number; - newStart: number; - newLines: number; - lines: string[]; - } - - interface IUniDiff { - oldFileName: string; - newFileName: string; - oldHeader: string; - newHeader: string; - index: string; - hunks: IHunk[]; - } - - class Diff { - diff(oldString: string, newString: string, options?: IOptions): IDiffResult[]; - - pushComponent(components: IDiffResult[], added: boolean, removed: boolean): void; - - extractCommon(basePath: IBestPath, newString: string, oldString: string, diagonalPath: number): number; - - equals(left: string, right: string): boolean; - - removeEmpty(array: any[]): any[]; - - castInput(value: any): any; - - join(chars: string[]): string; - - tokenize(value: string): any; // return types are string or string[] - } - - function diffChars(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffWords(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffWordsWithSpace(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffJson(oldObj: object, newObj: object, options?: IOptions): IDiffResult[]; - - function diffLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[]; - - function diffCss(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffTrimmedLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[]; - - function diffSentences(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffArrays(oldArr: T[], newArr: T[], options?: IArrayOptions): Array>; - - function createPatch(fileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; - - function createTwoFilesPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; - - function structuredPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): IUniDiff; - - function applyPatch(oldStr: string, uniDiff: string | IUniDiff | IUniDiff[]): string; - - function applyPatches(uniDiff: IUniDiff[], options: { - loadFile(index: number, callback: (err: Error, data: string) => void): void, - patched(index: number, content: string): void, - complete(err?: Error): void - }): void; - - function parsePatch(diffStr: string, options?: {strict: boolean}): IUniDiff[]; - - function convertChangesToXML(changes: IDiffResult[]): string; - - function convertChangesToDMP(changes: IDiffResult[]): Array<{0: number; 1: string; }>; - - function merge(mine: string, theirs: string, base: string): IUniDiff; - - function canonicalize(obj: any, stack: any[], replacementStack: any[]): any; +export interface CallbackOptions { + /** + * Callback to call with the result instead of returning the result directly. + */ + callback: Callback; } + +export interface BaseOptions { + /** + * `true` to ignore casing difference. + * @default false + */ + ignoreCase?: boolean; +} + +export interface WordsOptions extends BaseOptions { + /** + * `true` to ignore leading and trailing whitespace. This is the same as `diffWords()`. + */ + ignoreWhitespace?: boolean; +} + +export interface LinesOptions extends BaseOptions { + /** + * `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines()`. + */ + ignoreWhitespace?: boolean; + + /** + * `true` to treat newline characters as separate tokens. This allows for changes to the newline structure + * to occur independently of the line content and to be treated as such. In general this is the more + * human friendly form of `diffLines()` and `diffLines()` is better suited for patches and other computer + * friendly output. + */ + newlineIsToken?: boolean; +} + +export interface JsonOptions extends LinesOptions { + /** + * Replacer used to stringify the properties of the passed objects. + */ + stringifyReplacer?: (key: string, value: any) => any; + + /** + * The value to use when `undefined` values in the passed objects are encountered during stringification. + * Will only be used if `stringifyReplacer` option wasn't specified. + * @default undefined + */ + undefinedReplacement?: any; +} + +export interface ArrayOptions extends BaseOptions { + /** + * Comparator for custom equality checks. + */ + comparator?: (left: TLeft, right: TRight) => boolean; +} + +export interface PatchOptions extends LinesOptions { + /** + * Describes how many lines of context should be included. + * @default 4 + */ + context?: number; +} + +export interface ApplyPatchOptions { + /** + * Number of lines that are allowed to differ before rejecting a patch. + * @default 0 + */ + fuzzFactor?: number; + + /** + * Callback used to compare to given lines to determine if they should be considered equal when patching. + * Should return `false` if the lines should be rejected. + * + * @default strict equality + */ + compareLine?: ( + lineNumber: number, + line: string, + operation: '-' | ' ', + patchContent: string + ) => boolean; +} + +export interface ApplyPatchesOptions { + loadFile(index: ParsedDiff, callback: (err: any, data: string) => void): void; + patched(index: ParsedDiff, content: string, callback: (err: any) => void): void; + complete(err: any): void; +} + +export interface Change { + count?: number; + /** + * Text content. + */ + value: string; + /** + * `true` if the value was inserted into the new string. + */ + added?: boolean; + /** + * `true` if the value was removed from the old string. + */ + removed?: boolean; +} + +export interface ArrayChange { + value: T[]; + count?: number; + added?: boolean; + removed?: boolean; +} + +export interface ParsedDiff { + index?: string; + oldFileName?: string; + newFileName?: string; + oldHeader?: string; + newHeader?: string; + hunks: Hunk[]; +} + +export interface Hunk { + oldStart: number; + oldLines: number; + newStart: number; + newLines: number; + lines: string[]; +} + +export interface BestPath { + newPos: number; + componenets: Change[]; +} + +export class Diff { + diff( + oldString: string, + newString: string, + options?: Callback | (ArrayOptions & Partial) + ): Change[]; + + pushComponent(components: Change[], added: boolean, removed: boolean): void; + + extractCommon( + basePath: BestPath, + newString: string, + oldString: string, + diagonalPath: number + ): number; + + equals(left: any, right: any): boolean; + + removeEmpty(array: any[]): any[]; + + castInput(value: any): any; + + join(chars: string[]): string; + + tokenize(value: string): any; // return types are string or string[] +} + +/** + * Diffs two blocks of text, comparing character by character. + * + * @returns A list of change objects. + */ +export function diffChars(oldStr: string, newStr: string, options?: BaseOptions): Change[]; +export function diffChars( + oldStr: string, + newStr: string, + options: Callback | (BaseOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing word by word, ignoring whitespace. + * + * @returns A list of change objects. + */ +export function diffWords(oldStr: string, newStr: string, options?: WordsOptions): Change[]; +export function diffWords( + oldStr: string, + newStr: string, + options: Callback | (WordsOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing word by word, treating whitespace as significant. + * + * @returns A list of change objects. + */ +export function diffWordsWithSpace( + oldStr: string, + newStr: string, + options?: WordsOptions +): Change[]; +export function diffWordsWithSpace( + oldStr: string, + newStr: string, + options: Callback | (WordsOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing line by line. + * + * @returns A list of change objects. + */ +export function diffLines(oldStr: string, newStr: string, options?: LinesOptions): Change[]; +export function diffLines( + oldStr: string, + newStr: string, + options: Callback | (LinesOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. + * + * @returns A list of change objects. + */ +export function diffTrimmedLines(oldStr: string, newStr: string, options?: LinesOptions): Change[]; +export function diffTrimmedLines( + oldStr: string, + newStr: string, + options: Callback | (LinesOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing sentence by sentence. + * + * @returns A list of change objects. + */ +export function diffSentences(oldStr: string, newStr: string, options?: BaseOptions): Change[]; +export function diffSentences( + oldStr: string, + newStr: string, + options: Callback | (BaseOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing CSS tokens. + * + * @returns A list of change objects. + */ +export function diffCss(oldStr: string, newStr: string, options?: BaseOptions): Change[]; +export function diffCss( + oldStr: string, + newStr: string, + options: Callback | (BaseOptions & CallbackOptions) +): void; + +/** + * Diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter + * in this comparison. + * + * @returns A list of change objects. + */ +export function diffJson( + oldObj: string | object, + newObj: string | object, + options?: JsonOptions +): Change[]; +export function diffJson( + oldObj: string | object, + newObj: string | object, + options: Callback | (JsonOptions & CallbackOptions) +): void; + +/** + * Diffs two arrays, comparing each item for strict equality (`===`). + * + * @returns A list of change objects. + */ +export function diffArrays( + oldArr: TOld[], + newArr: TNew[], + options?: ArrayOptions +): Array>; + +/** + * Creates a unified diff patch. + * + * @param oldFileName String to be output in the filename section of the patch for the removals. + * @param newFileName String to be output in the filename section of the patch for the additions. + * @param oldStr Original string value. + * @param newStr New string value. + * @param oldHeader Additional information to include in the old file header. + * @param newHeader Additional information to include in the new file header. + */ +export function createTwoFilesPatch( + oldFileName: string, + newFileName: string, + oldStr: string, + newStr: string, + oldHeader?: string, + newHeader?: string, + options?: PatchOptions +): string; + +/** + * Creates a unified diff patch. + * Just like `createTwoFilesPatch()`, but with `oldFileName` being equal to `newFileName`. + * + * @param fileName String to be output in the filename section. + * @param oldStr Original string value. + * @param newStr New string value. + * @param oldHeader Additional information to include in the old file header. + * @param newHeader Additional information to include in the new file header. + */ +export function createPatch( + fileName: string, + oldStr: string, + newStr: string, + oldHeader?: string, + newHeader?: string, + options?: PatchOptions +): string; + +/** + * This method is similar to `createTwoFilesPatch()`, but returns a data structure suitable for further processing. + * Parameters are the same as `createTwoFilesPatch()`. + * + * @param oldFileName String to be output in the `oldFileName` hunk property. + * @param newFileName String to be output in the `newFileName` hunk property. + * @param oldStr Original string value. + * @param newStr New string value. + * @param oldHeader Additional information to include in the `oldHeader` hunk property. + * @param newHeader Additional information to include in the `newHeader` hunk property. + * @returns An object with an array of hunk objects. + */ +export function structuredPatch( + oldFileName: string, + newFileName: string, + oldStr: string, + newStr: string, + oldHeader?: string, + newHeader?: string, + options?: PatchOptions +): ParsedDiff; + +/** + * Applies a unified diff patch. + * + * @param patch May be a string diff or the output from the `parsePatch()` or `structuredPatch()` methods. + * @returns A string containing new version of provided data. + */ +export function applyPatch( + source: string, + patch: string | ParsedDiff | [ParsedDiff], + options?: ApplyPatchOptions +): string; + +/** + * Applies one or more patches. + * This method will iterate over the contents of the patch and apply to data provided through callbacks. + * + * The general flow for each patch index is: + * + * 1. `options.loadFile(index, callback)` is called. The caller should then load the contents of the file + * and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. + * 2. `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be + * the return value from `applyPatch()`. When it's ready, the caller should call `callback(err)` callback. + * Passing an `err` will terminate further patch execution. + * 3. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. + */ +export function applyPatches(patch: string | ParsedDiff[], options: ApplyPatchesOptions): void; + +/** + * Parses a patch into structured data. + * + * @returns A JSON object representation of the a patch, suitable for use with the `applyPatch()` method. + */ +export function parsePatch(diffStr: string, options?: { strict?: boolean }): ParsedDiff[]; + +/** + * Converts a list of changes to a serialized XML format. + */ +export function convertChangesToXML(changes: Change[]): string; + +/** + * Converts a list of changes to [DMP](http://code.google.com/p/google-diff-match-patch/wiki/API) format. + */ +export function convertChangesToDMP(changes: Change[]): Array<[1 | 0 | -1, string]>; + +export function merge(mine: string, theirs: string, base: string): ParsedDiff; + +export function canonicalize(obj: any, stack: any[], replacementStack: any[]): any; diff --git a/types/diff/tsconfig.json b/types/diff/tsconfig.json index 9a1fdba840..b32089d091 100644 --- a/types/diff/tsconfig.json +++ b/types/diff/tsconfig.json @@ -2,12 +2,11 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +20,4 @@ "index.d.ts", "diff-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/diff/tslint.json b/types/diff/tslint.json index 1b7b2672e6..3db14f85ea 100644 --- a/types/diff/tslint.json +++ b/types/diff/tslint.json @@ -1,7 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "interface-name": false, - "export-just-namespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/diff/v3/diff-tests.ts b/types/diff/v3/diff-tests.ts new file mode 100644 index 0000000000..2f640da490 --- /dev/null +++ b/types/diff/v3/diff-tests.ts @@ -0,0 +1,122 @@ +import jsdiff = require('diff'); +const one = 'beep boop'; +const other = 'beep boob blah'; + +let diff = jsdiff.diffChars(one, other); +printDiff(diff); + +const diffArraysResult = jsdiff.diffArrays(['a', 'b', 'c'], ['a', 'c', 'd']); +diffArraysResult.forEach(result => { + if (result.added) { + console.log(`added ${result.value.length} line(s):`, ...result.value); + } else if (result.removed) { + console.log(`removed ${result.value.length} line(s):`, ...result.value); + } else { + console.log(`no changes`); + } +}); + +interface DiffObj { + value: number; +} +const a: DiffObj = {value: 0}; +const b: DiffObj = {value: 1}; +const c: DiffObj = {value: 2}; +const d: DiffObj = {value: 3}; +const arrayOptions: jsdiff.IArrayOptions = { + comparator: (left: DiffObj, right: DiffObj) => { + return left.value === right.value; + } +}; +const diffResult = jsdiff.diffArrays([a, b, c], [a, b, d], arrayOptions); +diffResult.forEach(result => { + if (result.added) { + console.log(`added ${result.value.length} line(s):`, ...result.value); + } else if (result.removed) { + console.log(`removed ${result.value.length} line(s):`, ...result.value); + } else { + console.log(`no changes`); + } +}); + +// -------------------------- + +class LineDiffWithoutWhitespace extends jsdiff.Diff { + tokenize(value: string): any { + return value.split(/^/m); + } + + equals(left: string, right: string): boolean { + return left.trim() === right.trim(); + } +} + +const obj = new LineDiffWithoutWhitespace(); +diff = obj.diff(one, other); +printDiff(diff); + +function printDiff(diff: jsdiff.IDiffResult[]) { + function addLineHeader(decorator: string, str: string | string[]) { + return (typeof str === 'string' ? str.split("\n") : str).map((line, index, array) => { + if (index === array.length - 1 && line === "") { + return line; + } else { + return decorator + line; + } + }).join("\n"); + } + + diff.forEach((part) => { + if (part.added) { + console.log(addLineHeader("+", part.value)); + } else if (part.removed) { + console.log(addLineHeader("-", part.value)); + } else { + console.log(addLineHeader(" ", part.value)); + } + }); +} + +function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { + const verifyPatch = jsdiff.parsePatch( + jsdiff.createTwoFilesPatch("oldFile.ts", "newFile.ts", oldStr, newStr, + "old", "new", { context: 1 })); + + if (JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !== JSON.stringify(uniDiff, Object.keys(uniDiff).sort())) { + console.error("Patch did not match uniDiff"); + } +} +function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { + const verifyApply = [ + jsdiff.applyPatch(oldStr, uniDiff), + jsdiff.applyPatch(oldStr, [uniDiff]) + ]; + jsdiff.applyPatches([uniDiff], { + loadFile: (index: number, callback: (err: Error, data: string) => void) => { + callback(undefined, one); + }, + patched: (index: number, content: string) => { + verifyApply.push(content); + }, + complete: (err?: Error) => { + if (err) { + console.error(err); + } + + verifyApply.forEach(result => { + if (result !== newStr) { + console.error("Result did not match newStr"); + } + }); + } + }); +} + +const uniDiffPatch = jsdiff.structuredPatch("oldFile.ts", "newFile.ts", one, other, + "old", "new", { context: 1 }); +verifyPatchMethods(one, other, uniDiffPatch); + +const uniDiffStr = jsdiff.createPatch("file.ts", one, other, "old", "new", + { context: 1 }); +const uniDiffApply = jsdiff.parsePatch(uniDiffStr)[0]; +verifyApplyMethods(one, other, uniDiffApply); diff --git a/types/diff/v3/index.d.ts b/types/diff/v3/index.d.ts new file mode 100644 index 0000000000..760aee4e61 --- /dev/null +++ b/types/diff/v3/index.d.ts @@ -0,0 +1,121 @@ +// Type definitions for diff 3.5 +// Project: https://github.com/kpdecker/jsdiff +// Definitions by: vvakame +// szdc +// moc-yuto +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = JsDiff; +export as namespace JsDiff; + +declare namespace JsDiff { + interface IOptions { + ignoreCase: boolean; + } + + interface ILinesOptions extends IOptions { + ignoreWhitespace?: boolean; + newlineIsToken?: boolean; + } + + interface IArrayOptions { + comparator?: (left: any, right: any) => boolean; + } + + interface IDiffResult { + value: string; + count?: number; + added?: boolean; + removed?: boolean; + } + + interface IDiffArraysResult { + value: T[]; + count?: number; + added?: boolean; + removed?: boolean; + } + + interface IBestPath { + newPos: number; + componenets: IDiffResult[]; + } + + interface IHunk { + oldStart: number; + oldLines: number; + newStart: number; + newLines: number; + lines: string[]; + } + + interface IUniDiff { + oldFileName: string; + newFileName: string; + oldHeader: string; + newHeader: string; + index: string; + hunks: IHunk[]; + } + + class Diff { + diff(oldString: string, newString: string, options?: IOptions): IDiffResult[]; + + pushComponent(components: IDiffResult[], added: boolean, removed: boolean): void; + + extractCommon(basePath: IBestPath, newString: string, oldString: string, diagonalPath: number): number; + + equals(left: string, right: string): boolean; + + removeEmpty(array: any[]): any[]; + + castInput(value: any): any; + + join(chars: string[]): string; + + tokenize(value: string): any; // return types are string or string[] + } + + function diffChars(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffWords(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffWordsWithSpace(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffJson(oldObj: object, newObj: object, options?: IOptions): IDiffResult[]; + + function diffLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[]; + + function diffCss(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffTrimmedLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[]; + + function diffSentences(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffArrays(oldArr: T[], newArr: T[], options?: IArrayOptions): Array>; + + function createPatch(fileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; + + function createTwoFilesPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; + + function structuredPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): IUniDiff; + + function applyPatch(oldStr: string, uniDiff: string | IUniDiff | IUniDiff[]): string; + + function applyPatches(uniDiff: IUniDiff[], options: { + loadFile(index: number, callback: (err: Error, data: string) => void): void, + patched(index: number, content: string): void, + complete(err?: Error): void + }): void; + + function parsePatch(diffStr: string, options?: {strict: boolean}): IUniDiff[]; + + function convertChangesToXML(changes: IDiffResult[]): string; + + function convertChangesToDMP(changes: IDiffResult[]): Array<{0: number; 1: string; }>; + + function merge(mine: string, theirs: string, base: string): IUniDiff; + + function canonicalize(obj: any, stack: any[], replacementStack: any[]): any; +} diff --git a/types/diff/v3/tsconfig.json b/types/diff/v3/tsconfig.json new file mode 100644 index 0000000000..92e1861ec8 --- /dev/null +++ b/types/diff/v3/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "diff": [ + "diff/v3" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "diff-tests.ts" + ] +} diff --git a/types/diff/v3/tslint.json b/types/diff/v3/tslint.json new file mode 100644 index 0000000000..1b7b2672e6 --- /dev/null +++ b/types/diff/v3/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "interface-name": false, + "export-just-namespace": false + } +} diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index bdbda1ed95..0581057dea 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -174,6 +174,10 @@ declare namespace Dockerode { update(options: {}, callback: Callback): void; update(options: {}): Promise; + + logs(options: ContainerLogsOptions, callback: Callback): void; + logs(callback: Callback): void; + logs(options?: ContainerLogsOptions): Promise; } class Task { diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 0711243d0c..0c7e2c2e90 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -35,6 +35,10 @@ interface MyComponentState { stateProperty: string; } +function toComponentType(Component: ComponentClass | StatelessComponent): ComponentClass | StatelessComponent { + return Component; +} + class MyComponent extends Component { handleEcho(value: string) { return value; @@ -59,6 +63,8 @@ const MyStatelessComponent = (props: StatelessProps) => ; const AnotherStatelessComponent = (props: AnotherStatelessProps) => ; +const ComponentType = toComponentType(MyComponent); + // Enzyme.configure function configureTest() { const configureAdapter: { adapter: EnzymeAdapter } = { adapter: {} }; @@ -859,6 +865,14 @@ function ReactWrapperTest() { reactWrapper = new ReactWrapper(, undefined, { attachTo: document.createElement('div') }); reactWrapper = new ReactWrapper(, reactWrapper, { attachTo: document.createElement('div') }); } + + function test_component_type() { + const wrapper1 = shallow(
); + wrapper1.find(ComponentType).props().stringProp; // $ExpectType string + + const wrapper2 = mount(
); + wrapper2.find(ComponentType).props().stringProp; // $ExpectType string + } } // CheerioWrapper diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 0818b4e5ce..58e5938a8f 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -27,7 +27,9 @@ export interface ComponentClass { new(props: Props, context?: any): Component; } -export type StatelessComponent = (props: Props, context?: any) => JSX.Element; +export type StatelessComponent = (props: Props, context?: any) => JSX.Element | null; + +export type ComponentType = ComponentClass | StatelessComponent; /** * Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the @@ -372,8 +374,8 @@ export class ShallowWrapper

{ * Find every node in the render tree that matches the provided selector. * @param selector The selector to match. */ - find(component: ComponentClass): ShallowWrapper; find(statelessComponent: StatelessComponent): ShallowWrapper; + find(component: ComponentType): ShallowWrapper; find(props: EnzymePropSelector): ShallowWrapper; find(selector: string): ShallowWrapper; @@ -381,8 +383,8 @@ export class ShallowWrapper

{ * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ - filter(component: ComponentClass): ShallowWrapper; filter(statelessComponent: StatelessComponent): ShallowWrapper; + filter(component: ComponentType): ShallowWrapper; filter(props: EnzymePropSelector | string): ShallowWrapper; /** @@ -394,8 +396,8 @@ export class ShallowWrapper

{ * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector * can be provided and it will filter the children by this selector. */ - children(component: ComponentClass): ShallowWrapper; children(statelessComponent: StatelessComponent): ShallowWrapper; + children(component: ComponentType): ShallowWrapper; children(selector: string): ShallowWrapper; children(props?: EnzymePropSelector): ShallowWrapper; @@ -425,8 +427,8 @@ export class ShallowWrapper

{ * * Note: can only be called on a wrapper of a single node. */ - parents(component: ComponentClass): ShallowWrapper; parents(statelessComponent: StatelessComponent): ShallowWrapper; + parents(component: ComponentType): ShallowWrapper; parents(selector: string): ShallowWrapper; parents(props?: EnzymePropSelector): ShallowWrapper; @@ -436,8 +438,8 @@ export class ShallowWrapper

{ * * Note: can only be called on a wrapper of a single node. */ - closest(component: ComponentClass): ShallowWrapper; closest(statelessComponent: StatelessComponent): ShallowWrapper; + closest(component: ComponentType): ShallowWrapper; closest(props: EnzymePropSelector): ShallowWrapper; closest(selector: string): ShallowWrapper; @@ -487,8 +489,8 @@ export class ReactWrapper

{ * Find every node in the render tree that matches the provided selector. * @param selector The selector to match. */ - find(component: ComponentClass): ReactWrapper; find(statelessComponent: StatelessComponent): ReactWrapper; + find(component: ComponentType): ReactWrapper; find(props: EnzymePropSelector): ReactWrapper; find(selector: string): ReactWrapper; @@ -501,16 +503,16 @@ export class ReactWrapper

{ * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ - filter(component: ComponentClass): ReactWrapper; filter(statelessComponent: StatelessComponent): ReactWrapper; + filter(component: ComponentType): ReactWrapper; filter(props: EnzymePropSelector | string): ReactWrapper; /** * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector * can be provided and it will filter the children by this selector. */ - children(component: ComponentClass): ReactWrapper; children(statelessComponent: StatelessComponent): ReactWrapper; + children(component: ComponentType): ReactWrapper; children(selector: string): ReactWrapper; children(props?: EnzymePropSelector): ReactWrapper; @@ -526,8 +528,8 @@ export class ReactWrapper

{ * * Note: can only be called on a wrapper of a single node. */ - parents(component: ComponentClass): ReactWrapper; parents(statelessComponent: StatelessComponent): ReactWrapper; + parents(component: ComponentType): ReactWrapper; parents(selector: string): ReactWrapper; parents(props?: EnzymePropSelector): ReactWrapper; @@ -537,8 +539,8 @@ export class ReactWrapper

{ * * Note: can only be called on a wrapper of a single node. */ - closest(component: ComponentClass): ReactWrapper; closest(statelessComponent: StatelessComponent): ReactWrapper; + closest(component: ComponentType): ReactWrapper; closest(props: EnzymePropSelector): ReactWrapper; closest(selector: string): ReactWrapper; diff --git a/types/eslint/eslint-tests.ts b/types/eslint/eslint-tests.ts index ed211d220e..6d175716b3 100644 --- a/types/eslint/eslint-tests.ts +++ b/types/eslint/eslint-tests.ts @@ -539,4 +539,12 @@ ruleTester.run('my-rule', rule, { ] }); +ruleTester.run('simple-valid-test', rule, { + valid: [ + 'foo', + 'bar', + { code: 'foo', options: [{ allowFoo: true }] }, + ] +}); + //#endregion diff --git a/types/eslint/index.d.ts b/types/eslint/index.d.ts index 01f39ee83e..f1a585046c 100644 --- a/types/eslint/index.d.ts +++ b/types/eslint/index.d.ts @@ -540,7 +540,7 @@ export class RuleTester { name: string, rule: Rule.RuleModule, tests: { - valid?: RuleTester.ValidTestCase[]; + valid?: Array; invalid?: RuleTester.InvalidTestCase[]; }, ): void; diff --git a/types/fastify-rate-limit/fastify-rate-limit-tests.ts b/types/fastify-rate-limit/fastify-rate-limit-tests.ts new file mode 100644 index 0000000000..ee79951f48 --- /dev/null +++ b/types/fastify-rate-limit/fastify-rate-limit-tests.ts @@ -0,0 +1,22 @@ +import fastifyRateLimit = require("fastify-rate-limit"); +import * as IORedis from 'ioredis'; +import { FastifyRequest, DefaultQuery } from "fastify"; +import { IncomingMessage } from "http"; + +fastifyRateLimit(); + +const fastifyRateLimitOptions: fastifyRateLimit.FastifyRateLimitOptions> = { + max: 3, + timeWindow: 5000, + cache: 10000, + whitelist: ['127.0.0.1'], + redis: new IORedis({ host: '127.0.0.1' }), + skipOnError: true, // default false + keyGenerator: (req) => { + return req.headers['x-real-ip'] + || req.headers['x-client-ip'] + || req.headers['x-forwarded-for'] + || req.params.test + || req.ip; + }, +}; diff --git a/types/fastify-rate-limit/index.d.ts b/types/fastify-rate-limit/index.d.ts new file mode 100644 index 0000000000..888611ad72 --- /dev/null +++ b/types/fastify-rate-limit/index.d.ts @@ -0,0 +1,74 @@ +// Type definitions for fastify-rate-limit 2.0 +// Project: https://github.com/fastify/fastify-rate-limit#readme +// Definitions by: Christian D +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Redis } from "ioredis"; +import { FastifyRequest } from "fastify"; +import { IncomingMessage } from "http"; + +declare function fastifyRateLimit(): void; + +declare namespace fastifyRateLimit { + interface FastifyRateLimitOptions> { + /** + * Is the maximum number of requests a single client can perform inside a + * timeWindow. + * + * default: 1000 + */ + max?: number; + + /** + * The duration of the time window, can be expressed in milliseconds (as a + * number) or as a string, see ms too see the supported formats + * + * default: 1000 * 60 + */ + timeWindow?: number; + + /** + * This plugin internally uses a lru cache to handle the clients, you can + * change the size of the cache with this option. + * + * default: 5000 + */ + cache?: number; + + /** + * Array of string of ips to exclude from rate limiting. + * + * default: [] + */ + whitelist?: string[]; + + /** + * By default this plugins uses an in-memory store, which is fast but if + * you application works on more than one server it is useless, since the + * data is store locally. You can pass a Redis client here and magically + * the issue is solved. To achieve the maximum speed, this plugins requires + * the use of ioredis. + * + * default: null + */ + redis?: Redis; + + /** + * If `true` it will skip errors generated by the storage (eg, redis not + * reachable). + * + * default: false + */ + skipOnError?: boolean; + + /** + * Function to generate a unique identifier for each incoming request. + * + * default: (req) => req.ip + */ + keyGenerator?: (req: T) => string; + } +} + +export = fastifyRateLimit; diff --git a/types/fastify-rate-limit/package.json b/types/fastify-rate-limit/package.json new file mode 100644 index 0000000000..e8c68ab969 --- /dev/null +++ b/types/fastify-rate-limit/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "fastify": "^1.11.2" + } +} diff --git a/types/fastify-rate-limit/tsconfig.json b/types/fastify-rate-limit/tsconfig.json new file mode 100644 index 0000000000..5dc0e91ea2 --- /dev/null +++ b/types/fastify-rate-limit/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "fastify-rate-limit-tests.ts"], + "exclude": ["node-modules"] +} diff --git a/types/fastify-rate-limit/tslint.json b/types/fastify-rate-limit/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fastify-rate-limit/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/google-cloud__tasks/google-cloud__tasks-tests.ts b/types/google-cloud__tasks/google-cloud__tasks-tests.ts new file mode 100644 index 0000000000..4539f345ff --- /dev/null +++ b/types/google-cloud__tasks/google-cloud__tasks-tests.ts @@ -0,0 +1,18 @@ +import Tasks, { Queue } from "@google-cloud/tasks"; + +const client = new Tasks({}); + +const formattedParent = client.locationPath("[PROJECT]", "[LOCATION]"); +const queue: Partial = {}; +const request = { + parent: formattedParent, + queue +}; +client + .createQueue(request) + .then(([queue]) => { + const q = queue; + }) + .catch(err => { + console.error(err); + }); diff --git a/types/google-cloud__tasks/index.d.ts b/types/google-cloud__tasks/index.d.ts new file mode 100644 index 0000000000..c3347c8ea4 --- /dev/null +++ b/types/google-cloud__tasks/index.d.ts @@ -0,0 +1,1627 @@ +// Type definitions for @google-cloud/tasks 0.2 +// Project: https://github.com/googleapis/nodejs-tasks +// Definitions by: Ifiok Jr. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.8 + +/// + +import { Transform } from "stream"; +export type GoogleError = any; +export type GoogleAuthOptions = any; +export type CallOptions = any; +export type GoogleAuth = any; + +export interface CloudTasksConfig extends GoogleAuthOptions { + key?: string; + autoRetry?: boolean; + maxRetries?: number; + libName?: string; + libVersion?: string; + promise?: PromiseConstructor; +} + +export interface AppEngineHttpQueue { + appEngineRoutingOverride: AppEngineRouting; +} + +export interface AppEngineHttpRequest { + appEngineRouting: AppEngineRouting; + body: string; + headers: { + [key: string]: string; + }; + httpMethod: string; + relativeUri: string; +} + +export interface AppEngineRouting { + host: string; + instance: string; + service: string; + version: string; +} + +export interface Attempt { + dispatchTime: string; + responseStatus: Status; + responseTime: string; + scheduleTime: string; +} + +export interface Binding { + condition: Expr; + members: string[]; + role: string; +} + +export interface CreateTaskRequest { + responseView: View; + task: Partial; +} + +export interface Expr { + description: string; + expression: string; + location: string; + title: string; +} + +export interface ListLocationsResponse { + locations: Location[]; + nextPageToken?: string; +} + +export interface ListQueuesResponse { + nextPageToken?: string; + queues: Queue[]; +} + +export interface ListTasksResponse { + nextPageToken?: string; + tasks: Task[]; +} + +export interface Location { + displayName: string; + labels: { + [key: string]: string; + }; + locationId: string; + metadata: object; + name: string; +} + +export interface Policy { + bindings: Binding[]; + etag: string; + version: number; +} + +export interface Queue { + appEngineHttpQueue: AppEngineHttpQueue; + name: string; + purgeTime: string; + rateLimits: RateLimits; + retryConfig: RetryConfig; + state: string; +} + +export interface RateLimits { + maxBurstSize: number; + maxConcurrentDispatches: number; + maxDispatchesPerSecond: number; +} + +export interface RetryConfig { + maxAttempts: number; + maxBackoff: string; + maxDoublings: number; + maxRetryDuration: string; + minBackoff: string; +} + +export interface RunTaskRequest { + responseView?: View; +} + +export interface SetIamPolicyRequest { + policy: Partial; +} + +export interface Status { + code: number; + details: object[]; + message: string; +} + +/** + * `VIEW_UNSPECIFIED = 0;` + * When Unspecified. Defaults to the behaviour of BASIC. + * + * `BASIC = 1;` + * The basic view omits fields which can be large or can contain + * sensitive data. + * This view does not include the + * ([payload in AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] and + * [payload in PullMessage][google.cloud.tasks.v2beta2.PullMessage.payload]). These payloads are + * desirable to return only when needed, because they can be large + * and because of the sensitivity of the data that you choose to + * store in it. + * + * `FULL = 2;` + * All information is returned. + * + * Authorization for [FULL][google.cloud.tasks.v2beta2.Task.View.FULL] requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the [Queue][google.cloud.tasks.v2beta2.Queue] resource. + */ +export type View = 0 | 1 | 2; + +export interface Task { + appEngineHttpRequest: AppEngineHttpRequest; + createTime: string; + dispatchCount: number; + firstAttempt: Attempt; + lastAttempt: Attempt; + name: string; + responseCount: number; + scheduleTime: string; + view: View; +} + +export interface TestIamPermissionsRequest { + permissions?: string[]; +} + +export interface TestIamPermissionsResponse { + permissions?: string[]; +} + +export interface PromiseLike extends Promise { + /** + * Cancel the ongoing promise + */ + cancel(): void; +} + +export type Keys = keyof T; + +export type EnhancedPick< + T, + Req extends keyof T, + Opt extends keyof T +> = Required> & Partial>; + +export type ProjectIdCallback = ( + err?: Error | null, + projectId?: string | null +) => void; + +export type APICallback = ( + err: GoogleError | null, + response?: T +) => void; + +export type APIPaginatedCallback = ( + err: GoogleError | null, + response?: T, + next?: U | null, + rawResponse?: V +) => void; + +export interface CallOptionsWithPagination extends CallOptions { + autoPaginate: false; +} + +export interface MethodOverload { + (data: T, options?: CallOptions): PromiseLike<[R]>; + (data: T, options: CallOptions, callback: APICallback): void; + (data: T, callback: APICallback): void; +} + +export interface PaginatedMethodOverload { + (data: T, options: CallOptionsWithPagination): PromiseLike<[R, V, U]>; + (data: T, options?: CallOptions): PromiseLike<[R]>; + (data: T, options: CallOptions, callback: APICallback): void; + ( + data: T, + options: CallOptionsWithPagination, + callback: APIPaginatedCallback + ): void; + (data: T, callback: APICallback): void; +} + +export interface ParentRequest { + /** + * The location name. For example: projects/PROJECT_ID/locations/LOCATION_ID + */ + parent: string; +} + +export interface ResourceRequest { + /** + * The resource for which the policy is being requested. resource is usually specified as a path. For example, a Project resource is specified as projects/{project}. + */ + resource: string; +} + +export interface ListRequestObject extends ParentRequest { + /** + * `filter` can be used to specify a subset of queues. Any Queue field can be used as a filter and several operators as supported. + * For example: <=, <, >=, >, !=, =, :. The filter syntax is the same as described in Stackdriver's Advanced Logs Filters. + * Sample filter "state: PAUSED". + * Note that using filters might cause fewer queues than the requested page_size to be returned. + */ + filter?: string; + + /** + * The maximum number of resources contained in the underlying API response. If page streaming is performed per-resource, + * this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. + */ + pageSize?: number; +} + +export interface NamedRequest { + /** + * The resource name of the queue. For example: projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID + */ + name: string; +} + +export type CreateNamedRequest = ParentRequest & + { [P in N]: T }; +export type UpdateNamedRequest = ParentRequest & + { [P in N]: T }; + +/** + * Cloud Tasks allows developers to manage the execution of background + * work in their applications. + */ +export default class CloudTasksClient { + /** + * The DNS address for this API service. + * @default 'cloudtasks.googleapis.com' + */ + static readonly servicePath: string; + + /** + * The port for this API service. + * @default 443 + */ + static readonly port: number; + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @default ["https://www.googleapis.com/auth/cloud-platform"] + */ + static readonlyscopes: string; + + auth: GoogleAuth; + + /** + * Construct an instance of CloudTasksClient. + * + * @param [options] - The configuration object. See the subsequent + * parameters for more details. + * @param [options.credentials] - Credentials object. + * @param [options.credentials.client_email] + * @param [options.credentials.private_key] + * @param [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param [options.port] - The port on which to connect to + * the remote host. + * @param [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param [options.promise] - Custom promise module to use instead + * of native Promises. + * @param [options.servicePath] - The domain name of the + * API remote host. + */ + constructor(config: CloudTasksConfig); + + /** + * Return the project ID used by this class. + * @param callback - the callback to + * be called with the current project Id. + */ + getProjectId(): PromiseLike; + getProjectId(callback: ProjectIdCallback): void; + + // ------------------- + // -- Service calls -- + // ------------------- + + /** + * Lists queues. + * + * Queues are returned in lexicographical order. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param [request.filter] + * `filter` can be used to specify a subset of queues. Any Queue + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is Array of [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * + * When autoPaginate: false is specified through options, it contains the result + * in a single response. If the response indicates the next page exists, the third + * parameter is set to be used for the next request object. The fourth parameter keeps + * the raw response object of an object representing [ListQueuesResponse]{@link google.cloud.tasks.v2beta3.ListQueuesResponse}. + * The first element of the array is Array of [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * + * When autoPaginate: false is specified through options, the array has three elements. + * The first element is Array of [Queue]{@link google.cloud.tasks.v2beta3.Queue} in a single response. + * The second element is the next request object if the response + * indicates the next page exists, or null. The third element is + * an object representing [ListQueuesResponse]{@link google.cloud.tasks.v2beta3.ListQueuesResponse}. + * + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * // Iterate over all elements. + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * + * client.listQueues({parent: formattedParent}) + * .then(responses => { + * const resources = responses[0]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]) + * } + * }) + * .catch(err => { + * console.error(err); + * }); + * + * // Or obtain the paged response. + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * + * + * const options = {autoPaginate: false}; + * const callback = responses => { + * // The actual resources in a response. + * const resources = responses[0]; + * // The next request if the response shows that there are more responses. + * const nextRequest = responses[1]; + * // The actual response object, if necessary. + * // const rawResponse = responses[2]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]); + * } + * if (nextRequest) { + * // Fetch the next page. + * return client.listQueues(nextRequest, options).then(callback); + * } + * } + * client.listQueues({parent: formattedParent}, options) + * .then(callback) + * .catch(err => { + * console.error(err); + * }); + */ + listQueues: PaginatedMethodOverload< + ListRequestObject, + Queue[], + ListQueuesResponse + >; + + /** + * Equivalent to {@link listQueues}, but returns a NodeJS Stream object. + * + * This fetches the paged responses for {@link listQueues} continuously + * and invokes the callback registered for 'data' event for each element in the + * responses. + * + * The returned object has 'end' method when no more elements are required. + * + * autoPaginate option will be ignored. + * + * @see {@link https://nodejs.org/api/stream.html} + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param [request.filter] + * `filter` can be used to specify a subset of queues. Any Queue + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * An object stream which emits an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue} on 'data' event. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * client.listQueuesStream({parent: formattedParent}) + * .on('data', element => { + * // doThingsWith(element) + * }).on('error', err => { + * console.log(err); + * }); + */ + listQueuesStream( + request: ListRequestObject, + options?: CallOptions + ): Transform; + + /** + * Gets a queue. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The resource name of the queue. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.getQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + getQueue: MethodOverload; + + /** + * Creates a queue. + * + * Queues created with this method allow tasks to live for a maximum of 31 + * days. After a task is 31 days old, the task will be deleted regardless of whether + * it was dispatched or not. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) + * before using this method. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The location name in which the queue will be created. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * + * The list of allowed locations can be obtained by calling Cloud + * Tasks' implementation of + * ListLocations. + * @param request.queue + * Required. + * + * The queue to create. + * + * Queue's name cannot be the same as an existing queue. + * + * This object should have the same structure as [Queue]{@link google.cloud.tasks.v2beta3.Queue} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * const queue = {}; + * const request = { + * parent: formattedParent, + * queue: queue, + * }; + * client.createQueue(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + createQueue: MethodOverload< + CreateNamedRequest<"queue", Partial>, + Queue + >; + + /** + * Updates a queue. + * + * This method creates the queue if it does not exist and updates + * the queue if it does exist. + * + * Queues created with this method allow tasks to live for a maximum of 31 + * days. After a task is 31 days old, the task will be deleted regardless of whether + * it was dispatched or not. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) + * before using this method. + * + * @param request + * The request object that will be sent. + * @param request.queue + * Required. + * + * The queue to create or update. + * + * The queue's name must be specified. + * + * Output only fields cannot be modified using UpdateQueue. + * Any value specified for an output only field will be ignored. + * The queue's name cannot be changed. + * + * This object should have the same structure as [Queue]{@link google.cloud.tasks.v2beta3.Queue} + * @param [request.updateMask] + * A mask used to specify which fields of the queue are being updated. + * + * If empty, then all fields will be updated. + * + * This object should have the same structure as [FieldMask]{@link google.protobuf.FieldMask} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const queue = {}; + * client.updateQueue({queue: queue}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + updateQueue: MethodOverload< + UpdateNamedRequest< + "queue", + EnhancedPick< + Queue, + "name", + "appEngineHttpQueue" | "rateLimits" | "retryConfig" + > + >, + Queue + >; + + /** + * Deletes a queue. + * + * This command will delete the queue even if it has tasks in it. + * + * Note: If you delete a queue, a queue with the same name can't be created + * for 7 days. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) + * before using this method. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.deleteQueue({name: formattedName}).catch(err => { + * console.error(err); + * }); + */ + deleteQueue: MethodOverload; + + /** + * Purges a queue by deleting all of its tasks. + * + * All tasks created before this method is called are permanently deleted. + * + * Purge operations can take up to one minute to take effect. Tasks + * might be dispatched before the purge takes effect. A purge is irreversible. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.purgeQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + purgeQueue: MethodOverload; + + /** + * Pauses the queue. + * + * If a queue is paused then the system will stop dispatching tasks + * until the queue is resumed via + * ResumeQueue. Tasks can still be added + * when the queue is paused. A queue is paused if its + * state is PAUSED. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.pauseQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + pauseQueue: MethodOverload; + + /** + * Resume a queue. + * + * This method resumes a queue after it has been + * PAUSED or + * DISABLED. The state of a queue is stored + * in the queue's state; after calling this method it + * will be set to RUNNING. + * + * WARNING: Resuming many high-QPS queues at the same time can + * lead to target overloading. If you are resuming high-QPS + * queues, follow the 500/50/5 pattern described in + * [Managing Cloud Tasks Scaling Risks](https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.resumeQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + resumeQueue: MethodOverload; + + /** + * Gets the access control policy for a Queue. + * Returns an empty policy if the resource exists and does not have a policy + * set. + * + * Authorization requires the following + * [Google IAM](https://cloud.google.com/iam) permission on the specified + * resource parent: + * + * * `cloudtasks.queues.getIamPolicy` + * + * @param request + * The request object that will be sent. + * @param request.resource + * REQUIRED: The resource for which the policy is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Policy]{@link google.iam.v1.Policy}. + * The first element of the array is an object representing [Policy]{@link google.iam.v1.Policy}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedResource = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.getIamPolicy({resource: formattedResource}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + getIamPolicy: MethodOverload; + + /** + * Sets the access control policy for a Queue. Replaces any existing + * policy. + * + * Note: The Cloud Console does not check queue-level IAM permissions yet. + * Project-level permissions are required to use the Cloud Console. + * + * Authorization requires the following + * [Google IAM](https://cloud.google.com/iam) permission on the specified + * resource parent: + * + * * `cloudtasks.queues.setIamPolicy` + * + * @param request + * The request object that will be sent. + * @param request.resource + * REQUIRED: The resource for which the policy is being specified. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param request.policy + * REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * + * This object should have the same structure as [Policy]{@link google.iam.v1.Policy} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Policy]{@link google.iam.v1.Policy}. + * The first element of the array is an object representing [Policy]{@link google.iam.v1.Policy}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedResource = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * const policy = {}; + * const request = { + * resource: formattedResource, + * policy: policy, + * }; + * client.setIamPolicy(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + setIamPolicy: MethodOverload; + + /** + * Returns permissions that a caller has on a Queue. + * If the resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Note: This operation is designed to be used for building permission-aware + * UIs and command-line tools, not for authorization checking. This operation + * may "fail open" without warning. + * + * @param request + * The request object that will be sent. + * @param request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [TestIamPermissionsResponse]{@link google.iam.v1.TestIamPermissionsResponse}. + * The first element of the array is an object representing [TestIamPermissionsResponse]{@link google.iam.v1.TestIamPermissionsResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedResource = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * const permissions = []; + * const request = { + * resource: formattedResource, + * permissions: permissions, + * }; + * client.testIamPermissions(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + testIamPermissions: MethodOverload< + ResourceRequest & TestIamPermissionsRequest, + TestIamPermissionsResponse + >; + + /** + * Lists the tasks in a queue. + * + * By default, only the BASIC view is retrieved + * due to performance considerations; + * response_view controls the + * subset of information which is returned. + * + * The tasks may be returned in any order. The ordering may change at any + * time. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is Array of [Task]{@link google.cloud.tasks.v2beta3.Task}. + * + * When autoPaginate: false is specified through options, it contains the result + * in a single response. If the response indicates the next page exists, the third + * parameter is set to be used for the next request object. The fourth parameter keeps + * the raw response object of an object representing [ListTasksResponse]{@link google.cloud.tasks.v2beta3.ListTasksResponse}. + * The first element of the array is Array of [Task]{@link google.cloud.tasks.v2beta3.Task}. + * + * When autoPaginate: false is specified through options, the array has three elements. + * The first element is Array of [Task]{@link google.cloud.tasks.v2beta3.Task} in a single response. + * The second element is the next request object if the response + * indicates the next page exists, or null. The third element is + * an object representing [ListTasksResponse]{@link google.cloud.tasks.v2beta3.ListTasksResponse}. + * + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * // Iterate over all elements. + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * + * client.listTasks({parent: formattedParent}) + * .then(responses => { + * const resources = responses[0]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]) + * } + * }) + * .catch(err => { + * console.error(err); + * }); + * + * // Or obtain the paged response. + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * + * + * const options = {autoPaginate: false}; + * const callback = responses => { + * // The actual resources in a response. + * const resources = responses[0]; + * // The next request if the response shows that there are more responses. + * const nextRequest = responses[1]; + * // The actual response object, if necessary. + * // const rawResponse = responses[2]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]); + * } + * if (nextRequest) { + * // Fetch the next page. + * return client.listTasks(nextRequest, options).then(callback); + * } + * } + * client.listTasks({parent: formattedParent}, options) + * .then(callback) + * .catch(err => { + * console.error(err); + * }); + */ + listTasks: PaginatedMethodOverload< + ListRequestObject & RunTaskRequest, + Task[], + ListTasksResponse + >; + + /** + * Equivalent to {@link listTasks}, but returns a NodeJS Stream object. + * + * This fetches the paged responses for {@link listTasks} continuously + * and invokes the callback registered for 'data' event for each element in the + * responses. + * + * The returned object has 'end' method when no more elements are required. + * + * autoPaginate option will be ignored. + * + * @see {@link https://nodejs.org/api/stream.html} + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * An object stream which emits an object representing [Task]{@link google.cloud.tasks.v2beta3.Task} on 'data' event. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.listTasksStream({parent: formattedParent}) + * .on('data', element => { + * // doThingsWith(element) + * }).on('error', err => { + * console.log(err); + * }); + */ + listTasksStream( + request: ListRequestObject & RunTaskRequest, + options?: CallOptions + ): Transform; + + /** + * Gets a task. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The first element of the array is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.taskPath('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]'); + * client.getTask({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + getTask: MethodOverload; + /** + * Creates a task and adds it to a queue. + * + * Tasks cannot be updated after creation; there is no UpdateTask command. + * + * * For App Engine queues, the maximum task size is + * 100KB. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * + * The queue must already exist. + * @param request.task + * Required. + * + * The task to add. + * + * Task names have the following format: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`. + * The user can optionally specify a task name. If a + * name is not specified then the system will generate a random + * unique task id, which will be set in the task returned in the + * response. + * + * If schedule_time is not set or is in the + * past then Cloud Tasks will set it to the current time. + * + * Task De-duplication: + * + * Explicitly specifying a task ID enables task de-duplication. If + * a task's ID is identical to that of an existing task or a task + * that was deleted or executed recently then the call will fail + * with ALREADY_EXISTS. + * If the task's queue was created using Cloud Tasks, then another task with + * the same name can't be created for ~1hour after the original task was + * deleted or executed. If the task's queue was created using queue.yaml or + * queue.xml, then another task with the same name can't be created + * for ~9days after the original task was deleted or executed. + * + * Because there is an extra lookup cost to identify duplicate task + * names, these CreateTask calls have significantly + * increased latency. Using hashed strings for the task id or for + * the prefix of the task id is recommended. Choosing task ids that + * are sequential or have sequential prefixes, for example using a + * timestamp, causes an increase in latency and error rates in all + * task commands. The infrastructure relies on an approximately + * uniform distribution of task ids to store and serve tasks + * efficiently. + * + * This object should have the same structure as [Task]{@link google.cloud.tasks.v2beta3.Task} + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The first element of the array is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * const task = {}; + * const request = { + * parent: formattedParent, + * task: task, + * }; + * client.createTask(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + createTask: MethodOverload; + + /** + * Deletes a task. + * + * A task can be deleted if it is scheduled or dispatched. A task + * cannot be deleted if it has executed successfully or permanently + * failed. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.taskPath('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]'); + * client.deleteTask({name: formattedName}).catch(err => { + * console.error(err); + * }); + */ + deleteTask: MethodOverload; + + /** + * Forces a task to run now. + * + * When this method is called, Cloud Tasks will dispatch the task, even if + * the task is already running, the queue has reached its RateLimits or + * is PAUSED. + * + * This command is meant to be used for manual debugging. For + * example, RunTask can be used to retry a failed + * task after a fix has been made or to manually force a task to be + * dispatched now. + * + * The dispatched task is returned. That is, the task that is returned + * contains the status after the task is dispatched but + * before the task is received by its target. + * + * If Cloud Tasks receives a successful response from the task's + * target, then the task will be deleted; otherwise the task's + * schedule_time will be reset to the time that + * RunTask was called plus the retry delay specified + * in the queue's RetryConfig. + * + * RunTask returns + * NOT_FOUND when it is called on a + * task that has already succeeded or permanently failed. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The first element of the array is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.taskPath('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]'); + * client.runTask({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + runTask: MethodOverload; + + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified project resource name string. + * + * @param project + */ + projectPath(project: string): string; + + /** + * Return a fully-qualified location resource name string. + * + * @param project + * @param location + */ + locationPath(project: string, location: string): string; + + /** + * Return a fully-qualified queue resource name string. + * + * @param project + * @param location + * @param queue + */ + queuePath(project: string, location: string, queue: string): string; + + /** + * Return a fully-qualified task resource name string. + * + * @param project + * @param location + * @param queue + * @param task + */ + taskPath( + project: string, + location: string, + queue: string, + task: string + ): string; + + /** + * Parse the projectName from a project resource. + * + * @param projectName + * A fully-qualified path representing a project resources. + */ + matchProjectFromProjectName(projectName: string): string; + + /** + * Parse the locationName from a location resource. + * + * @param locationName + * A fully-qualified path representing a location resources. + */ + matchProjectFromLocationName(locationName: string): string; + + /** + * Parse the locationName from a location resource. + * + * @param locationName + * A fully-qualified path representing a location resources. + */ + matchLocationFromLocationName(locationName: string): string; + + /** + * Parse the queueName from a queue resource. + * + * @param queueName + * A fully-qualified path representing a queue resources. + */ + matchProjectFromQueueName(queueName: string): string; + + /** + * Parse the queueName from a queue resource. + * + * @param queueName + * A fully-qualified path representing a queue resources. + */ + matchLocationFromQueueName(queueName: string): string; + + /** + * Parse the queueName from a queue resource. + * + * @param queueName + * A fully-qualified path representing a queue resources. + */ + matchQueueFromQueueName(queueName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchProjectFromTaskName(taskName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchLocationFromTaskName(taskName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchQueueFromTaskName(taskName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchTaskFromTaskName(taskName: string): string; +} diff --git a/types/google-cloud__tasks/package.json b/types/google-cloud__tasks/package.json new file mode 100644 index 0000000000..c4a850824a --- /dev/null +++ b/types/google-cloud__tasks/package.json @@ -0,0 +1,14 @@ +{ + "private": true, + "dependencies": { + "google-gax": "^0.22.1" + }, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { + "*": [ + "ts3.1/*" + ] + } + } +} diff --git a/types/google-cloud__tasks/ts3.1/google-cloud__tasks-tests.ts b/types/google-cloud__tasks/ts3.1/google-cloud__tasks-tests.ts new file mode 100644 index 0000000000..94a7ebcfa4 --- /dev/null +++ b/types/google-cloud__tasks/ts3.1/google-cloud__tasks-tests.ts @@ -0,0 +1,21 @@ +import Tasks, { Queue } from "@google-cloud/tasks"; + +const client = new Tasks({}); + +// $ExpectError +const failedClient = new Tasks({ unrecognized: "" }); + +const formattedParent = client.locationPath("[PROJECT]", "[LOCATION]"); +const queue: Partial = {}; +const request = { + parent: formattedParent, + queue +}; +client + .createQueue(request) + .then(([queue]) => { + const q = queue; + }) + .catch(err => { + console.error(err); + }); diff --git a/types/google-cloud__tasks/ts3.1/index.d.ts b/types/google-cloud__tasks/ts3.1/index.d.ts new file mode 100644 index 0000000000..6b09fdd06d --- /dev/null +++ b/types/google-cloud__tasks/ts3.1/index.d.ts @@ -0,0 +1,1622 @@ +/// + +import { Transform } from "stream"; +import { + GoogleAuthOptions, + GoogleError, + CallOptions, + GoogleAuth +} from "google-gax"; + +export interface CloudTasksConfig extends GoogleAuthOptions { + key?: string; + autoRetry?: boolean; + maxRetries?: number; + libName?: string; + libVersion?: string; + promise?: PromiseConstructor; +} + +export interface AppEngineHttpQueue { + appEngineRoutingOverride: AppEngineRouting; +} + +export interface AppEngineHttpRequest { + appEngineRouting: AppEngineRouting; + body: string; + headers: { + [key: string]: string; + }; + httpMethod: string; + relativeUri: string; +} + +export interface AppEngineRouting { + host: string; + instance: string; + service: string; + version: string; +} + +export interface Attempt { + dispatchTime: string; + responseStatus: Status; + responseTime: string; + scheduleTime: string; +} + +export interface Binding { + condition: Expr; + members: string[]; + role: string; +} + +export interface CreateTaskRequest { + responseView: View; + task: Partial; +} + +export interface Expr { + description: string; + expression: string; + location: string; + title: string; +} + +export interface ListLocationsResponse { + locations: Location[]; + nextPageToken?: string; +} + +export interface ListQueuesResponse { + nextPageToken?: string; + queues: Queue[]; +} + +export interface ListTasksResponse { + nextPageToken?: string; + tasks: Task[]; +} + +export interface Location { + displayName: string; + labels: { + [key: string]: string; + }; + locationId: string; + metadata: object; + name: string; +} + +export interface Policy { + bindings: Binding[]; + etag: string; + version: number; +} + +export interface Queue { + appEngineHttpQueue: AppEngineHttpQueue; + name: string; + purgeTime: string; + rateLimits: RateLimits; + retryConfig: RetryConfig; + state: string; +} + +export interface RateLimits { + maxBurstSize: number; + maxConcurrentDispatches: number; + maxDispatchesPerSecond: number; +} + +export interface RetryConfig { + maxAttempts: number; + maxBackoff: string; + maxDoublings: number; + maxRetryDuration: string; + minBackoff: string; +} + +export interface RunTaskRequest { + responseView?: View; +} + +export interface SetIamPolicyRequest { + policy: Partial; +} + +export interface Status { + code: number; + details: object[]; + message: string; +} + +/** + * `VIEW_UNSPECIFIED = 0;` + * When Unspecified. Defaults to the behaviour of BASIC. + * + * `BASIC = 1;` + * The basic view omits fields which can be large or can contain + * sensitive data. + * This view does not include the + * ([payload in AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] and + * [payload in PullMessage][google.cloud.tasks.v2beta2.PullMessage.payload]). These payloads are + * desirable to return only when needed, because they can be large + * and because of the sensitivity of the data that you choose to + * store in it. + * + * `FULL = 2;` + * All information is returned. + * + * Authorization for [FULL][google.cloud.tasks.v2beta2.Task.View.FULL] requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the [Queue][google.cloud.tasks.v2beta2.Queue] resource. + */ +export type View = 0 | 1 | 2; + +export interface Task { + appEngineHttpRequest: AppEngineHttpRequest; + createTime: string; + dispatchCount: number; + firstAttempt: Attempt; + lastAttempt: Attempt; + name: string; + responseCount: number; + scheduleTime: string; + view: View; +} + +export interface TestIamPermissionsRequest { + permissions?: string[]; +} + +export interface TestIamPermissionsResponse { + permissions?: string[]; +} + +export interface PromiseLike extends Promise { + /** + * Cancel the ongoing promise + */ + cancel(): void; +} + +export type Keys = keyof T; + +export type EnhancedPick< + T, + Req extends keyof T, + Opt extends keyof T +> = Required> & Partial>; + +export type ProjectIdCallback = ( + err?: Error | null, + projectId?: string | null +) => void; + +export type APICallback = ( + err: GoogleError | null, + response?: T +) => void; + +export type APIPaginatedCallback = ( + err: GoogleError | null, + response?: T, + next?: U | null, + rawResponse?: V +) => void; + +export interface CallOptionsWithPagination extends CallOptions { + autoPaginate: false; +} + +export interface MethodOverload { + (data: T, options?: CallOptions): PromiseLike<[R]>; + (data: T, options: CallOptions, callback: APICallback): void; + (data: T, callback: APICallback): void; +} + +export interface PaginatedMethodOverload { + (data: T, options: CallOptionsWithPagination): PromiseLike<[R, V, U]>; + (data: T, options?: CallOptions): PromiseLike<[R]>; + (data: T, options: CallOptions, callback: APICallback): void; + ( + data: T, + options: CallOptionsWithPagination, + callback: APIPaginatedCallback + ): void; + (data: T, callback: APICallback): void; +} + +export interface ParentRequest { + /** + * The location name. For example: projects/PROJECT_ID/locations/LOCATION_ID + */ + parent: string; +} + +export interface ResourceRequest { + /** + * The resource for which the policy is being requested. resource is usually specified as a path. For example, a Project resource is specified as projects/{project}. + */ + resource: string; +} + +export interface ListRequestObject extends ParentRequest { + /** + * `filter` can be used to specify a subset of queues. Any Queue field can be used as a filter and several operators as supported. + * For example: <=, <, >=, >, !=, =, :. The filter syntax is the same as described in Stackdriver's Advanced Logs Filters. + * Sample filter "state: PAUSED". + * Note that using filters might cause fewer queues than the requested page_size to be returned. + */ + filter?: string; + + /** + * The maximum number of resources contained in the underlying API response. If page streaming is performed per-resource, + * this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. + */ + pageSize?: number; +} + +export interface NamedRequest { + /** + * The resource name of the queue. For example: projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID + */ + name: string; +} + +export type CreateNamedRequest = ParentRequest & + { [P in N]: T }; +export type UpdateNamedRequest = ParentRequest & + { [P in N]: T }; + +/** + * Cloud Tasks allows developers to manage the execution of background + * work in their applications. + */ +export default class CloudTasksClient { + /** + * The DNS address for this API service. + * @default 'cloudtasks.googleapis.com' + */ + static readonly servicePath: string; + + /** + * The port for this API service. + * @default 443 + */ + static readonly port: number; + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @default ["https://www.googleapis.com/auth/cloud-platform"] + */ + static readonlyscopes: string; + + auth: GoogleAuth; + + /** + * Construct an instance of CloudTasksClient. + * + * @param [options] - The configuration object. See the subsequent + * parameters for more details. + * @param [options.credentials] - Credentials object. + * @param [options.credentials.client_email] + * @param [options.credentials.private_key] + * @param [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param [options.port] - The port on which to connect to + * the remote host. + * @param [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param [options.promise] - Custom promise module to use instead + * of native Promises. + * @param [options.servicePath] - The domain name of the + * API remote host. + */ + constructor(config: CloudTasksConfig); + + /** + * Return the project ID used by this class. + * @param callback - the callback to + * be called with the current project Id. + */ + getProjectId(): PromiseLike; + getProjectId(callback: ProjectIdCallback): void; + + // ------------------- + // -- Service calls -- + // ------------------- + + /** + * Lists queues. + * + * Queues are returned in lexicographical order. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param [request.filter] + * `filter` can be used to specify a subset of queues. Any Queue + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is Array of [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * + * When autoPaginate: false is specified through options, it contains the result + * in a single response. If the response indicates the next page exists, the third + * parameter is set to be used for the next request object. The fourth parameter keeps + * the raw response object of an object representing [ListQueuesResponse]{@link google.cloud.tasks.v2beta3.ListQueuesResponse}. + * The first element of the array is Array of [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * + * When autoPaginate: false is specified through options, the array has three elements. + * The first element is Array of [Queue]{@link google.cloud.tasks.v2beta3.Queue} in a single response. + * The second element is the next request object if the response + * indicates the next page exists, or null. The third element is + * an object representing [ListQueuesResponse]{@link google.cloud.tasks.v2beta3.ListQueuesResponse}. + * + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * // Iterate over all elements. + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * + * client.listQueues({parent: formattedParent}) + * .then(responses => { + * const resources = responses[0]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]) + * } + * }) + * .catch(err => { + * console.error(err); + * }); + * + * // Or obtain the paged response. + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * + * + * const options = {autoPaginate: false}; + * const callback = responses => { + * // The actual resources in a response. + * const resources = responses[0]; + * // The next request if the response shows that there are more responses. + * const nextRequest = responses[1]; + * // The actual response object, if necessary. + * // const rawResponse = responses[2]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]); + * } + * if (nextRequest) { + * // Fetch the next page. + * return client.listQueues(nextRequest, options).then(callback); + * } + * } + * client.listQueues({parent: formattedParent}, options) + * .then(callback) + * .catch(err => { + * console.error(err); + * }); + */ + listQueues: PaginatedMethodOverload< + ListRequestObject, + Queue[], + ListQueuesResponse + >; + + /** + * Equivalent to {@link listQueues}, but returns a NodeJS Stream object. + * + * This fetches the paged responses for {@link listQueues} continuously + * and invokes the callback registered for 'data' event for each element in the + * responses. + * + * The returned object has 'end' method when no more elements are required. + * + * autoPaginate option will be ignored. + * + * @see {@link https://nodejs.org/api/stream.html} + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param [request.filter] + * `filter` can be used to specify a subset of queues. Any Queue + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * An object stream which emits an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue} on 'data' event. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * client.listQueuesStream({parent: formattedParent}) + * .on('data', element => { + * // doThingsWith(element) + * }).on('error', err => { + * console.log(err); + * }); + */ + listQueuesStream( + request: ListRequestObject, + options?: CallOptions + ): Transform; + + /** + * Gets a queue. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The resource name of the queue. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.getQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + getQueue: MethodOverload; + + /** + * Creates a queue. + * + * Queues created with this method allow tasks to live for a maximum of 31 + * days. After a task is 31 days old, the task will be deleted regardless of whether + * it was dispatched or not. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) + * before using this method. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The location name in which the queue will be created. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * + * The list of allowed locations can be obtained by calling Cloud + * Tasks' implementation of + * ListLocations. + * @param request.queue + * Required. + * + * The queue to create. + * + * Queue's name cannot be the same as an existing queue. + * + * This object should have the same structure as [Queue]{@link google.cloud.tasks.v2beta3.Queue} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * const queue = {}; + * const request = { + * parent: formattedParent, + * queue: queue, + * }; + * client.createQueue(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + createQueue: MethodOverload< + CreateNamedRequest<"queue", Partial>, + Queue + >; + + /** + * Updates a queue. + * + * This method creates the queue if it does not exist and updates + * the queue if it does exist. + * + * Queues created with this method allow tasks to live for a maximum of 31 + * days. After a task is 31 days old, the task will be deleted regardless of whether + * it was dispatched or not. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) + * before using this method. + * + * @param request + * The request object that will be sent. + * @param request.queue + * Required. + * + * The queue to create or update. + * + * The queue's name must be specified. + * + * Output only fields cannot be modified using UpdateQueue. + * Any value specified for an output only field will be ignored. + * The queue's name cannot be changed. + * + * This object should have the same structure as [Queue]{@link google.cloud.tasks.v2beta3.Queue} + * @param [request.updateMask] + * A mask used to specify which fields of the queue are being updated. + * + * If empty, then all fields will be updated. + * + * This object should have the same structure as [FieldMask]{@link google.protobuf.FieldMask} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const queue = {}; + * client.updateQueue({queue: queue}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + updateQueue: MethodOverload< + UpdateNamedRequest< + "queue", + EnhancedPick< + Queue, + "name", + "appEngineHttpQueue" | "rateLimits" | "retryConfig" + > + >, + Queue + >; + + /** + * Deletes a queue. + * + * This command will delete the queue even if it has tasks in it. + * + * Note: If you delete a queue, a queue with the same name can't be created + * for 7 days. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) + * before using this method. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.deleteQueue({name: formattedName}).catch(err => { + * console.error(err); + * }); + */ + deleteQueue: MethodOverload; + + /** + * Purges a queue by deleting all of its tasks. + * + * All tasks created before this method is called are permanently deleted. + * + * Purge operations can take up to one minute to take effect. Tasks + * might be dispatched before the purge takes effect. A purge is irreversible. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.purgeQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + purgeQueue: MethodOverload; + + /** + * Pauses the queue. + * + * If a queue is paused then the system will stop dispatching tasks + * until the queue is resumed via + * ResumeQueue. Tasks can still be added + * when the queue is paused. A queue is paused if its + * state is PAUSED. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.pauseQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + pauseQueue: MethodOverload; + + /** + * Resume a queue. + * + * This method resumes a queue after it has been + * PAUSED or + * DISABLED. The state of a queue is stored + * in the queue's state; after calling this method it + * will be set to RUNNING. + * + * WARNING: Resuming many high-QPS queues at the same time can + * lead to target overloading. If you are resuming high-QPS + * queues, follow the 500/50/5 pattern described in + * [Managing Cloud Tasks Scaling Risks](https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.resumeQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + resumeQueue: MethodOverload; + + /** + * Gets the access control policy for a Queue. + * Returns an empty policy if the resource exists and does not have a policy + * set. + * + * Authorization requires the following + * [Google IAM](https://cloud.google.com/iam) permission on the specified + * resource parent: + * + * * `cloudtasks.queues.getIamPolicy` + * + * @param request + * The request object that will be sent. + * @param request.resource + * REQUIRED: The resource for which the policy is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Policy]{@link google.iam.v1.Policy}. + * The first element of the array is an object representing [Policy]{@link google.iam.v1.Policy}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedResource = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.getIamPolicy({resource: formattedResource}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + getIamPolicy: MethodOverload; + + /** + * Sets the access control policy for a Queue. Replaces any existing + * policy. + * + * Note: The Cloud Console does not check queue-level IAM permissions yet. + * Project-level permissions are required to use the Cloud Console. + * + * Authorization requires the following + * [Google IAM](https://cloud.google.com/iam) permission on the specified + * resource parent: + * + * * `cloudtasks.queues.setIamPolicy` + * + * @param request + * The request object that will be sent. + * @param request.resource + * REQUIRED: The resource for which the policy is being specified. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param request.policy + * REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * + * This object should have the same structure as [Policy]{@link google.iam.v1.Policy} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Policy]{@link google.iam.v1.Policy}. + * The first element of the array is an object representing [Policy]{@link google.iam.v1.Policy}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedResource = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * const policy = {}; + * const request = { + * resource: formattedResource, + * policy: policy, + * }; + * client.setIamPolicy(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + setIamPolicy: MethodOverload; + + /** + * Returns permissions that a caller has on a Queue. + * If the resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Note: This operation is designed to be used for building permission-aware + * UIs and command-line tools, not for authorization checking. This operation + * may "fail open" without warning. + * + * @param request + * The request object that will be sent. + * @param request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [TestIamPermissionsResponse]{@link google.iam.v1.TestIamPermissionsResponse}. + * The first element of the array is an object representing [TestIamPermissionsResponse]{@link google.iam.v1.TestIamPermissionsResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedResource = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * const permissions = []; + * const request = { + * resource: formattedResource, + * permissions: permissions, + * }; + * client.testIamPermissions(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + testIamPermissions: MethodOverload< + ResourceRequest & TestIamPermissionsRequest, + TestIamPermissionsResponse + >; + + /** + * Lists the tasks in a queue. + * + * By default, only the BASIC view is retrieved + * due to performance considerations; + * response_view controls the + * subset of information which is returned. + * + * The tasks may be returned in any order. The ordering may change at any + * time. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is Array of [Task]{@link google.cloud.tasks.v2beta3.Task}. + * + * When autoPaginate: false is specified through options, it contains the result + * in a single response. If the response indicates the next page exists, the third + * parameter is set to be used for the next request object. The fourth parameter keeps + * the raw response object of an object representing [ListTasksResponse]{@link google.cloud.tasks.v2beta3.ListTasksResponse}. + * The first element of the array is Array of [Task]{@link google.cloud.tasks.v2beta3.Task}. + * + * When autoPaginate: false is specified through options, the array has three elements. + * The first element is Array of [Task]{@link google.cloud.tasks.v2beta3.Task} in a single response. + * The second element is the next request object if the response + * indicates the next page exists, or null. The third element is + * an object representing [ListTasksResponse]{@link google.cloud.tasks.v2beta3.ListTasksResponse}. + * + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * // Iterate over all elements. + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * + * client.listTasks({parent: formattedParent}) + * .then(responses => { + * const resources = responses[0]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]) + * } + * }) + * .catch(err => { + * console.error(err); + * }); + * + * // Or obtain the paged response. + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * + * + * const options = {autoPaginate: false}; + * const callback = responses => { + * // The actual resources in a response. + * const resources = responses[0]; + * // The next request if the response shows that there are more responses. + * const nextRequest = responses[1]; + * // The actual response object, if necessary. + * // const rawResponse = responses[2]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]); + * } + * if (nextRequest) { + * // Fetch the next page. + * return client.listTasks(nextRequest, options).then(callback); + * } + * } + * client.listTasks({parent: formattedParent}, options) + * .then(callback) + * .catch(err => { + * console.error(err); + * }); + */ + listTasks: PaginatedMethodOverload< + ListRequestObject & RunTaskRequest, + Task[], + ListTasksResponse + >; + + /** + * Equivalent to {@link listTasks}, but returns a NodeJS Stream object. + * + * This fetches the paged responses for {@link listTasks} continuously + * and invokes the callback registered for 'data' event for each element in the + * responses. + * + * The returned object has 'end' method when no more elements are required. + * + * autoPaginate option will be ignored. + * + * @see {@link https://nodejs.org/api/stream.html} + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * An object stream which emits an object representing [Task]{@link google.cloud.tasks.v2beta3.Task} on 'data' event. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.listTasksStream({parent: formattedParent}) + * .on('data', element => { + * // doThingsWith(element) + * }).on('error', err => { + * console.log(err); + * }); + */ + listTasksStream( + request: ListRequestObject & RunTaskRequest, + options?: CallOptions + ): Transform; + + /** + * Gets a task. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The first element of the array is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.taskPath('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]'); + * client.getTask({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + getTask: MethodOverload; + /** + * Creates a task and adds it to a queue. + * + * Tasks cannot be updated after creation; there is no UpdateTask command. + * + * * For App Engine queues, the maximum task size is + * 100KB. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * + * The queue must already exist. + * @param request.task + * Required. + * + * The task to add. + * + * Task names have the following format: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`. + * The user can optionally specify a task name. If a + * name is not specified then the system will generate a random + * unique task id, which will be set in the task returned in the + * response. + * + * If schedule_time is not set or is in the + * past then Cloud Tasks will set it to the current time. + * + * Task De-duplication: + * + * Explicitly specifying a task ID enables task de-duplication. If + * a task's ID is identical to that of an existing task or a task + * that was deleted or executed recently then the call will fail + * with ALREADY_EXISTS. + * If the task's queue was created using Cloud Tasks, then another task with + * the same name can't be created for ~1hour after the original task was + * deleted or executed. If the task's queue was created using queue.yaml or + * queue.xml, then another task with the same name can't be created + * for ~9days after the original task was deleted or executed. + * + * Because there is an extra lookup cost to identify duplicate task + * names, these CreateTask calls have significantly + * increased latency. Using hashed strings for the task id or for + * the prefix of the task id is recommended. Choosing task ids that + * are sequential or have sequential prefixes, for example using a + * timestamp, causes an increase in latency and error rates in all + * task commands. The infrastructure relies on an approximately + * uniform distribution of task ids to store and serve tasks + * efficiently. + * + * This object should have the same structure as [Task]{@link google.cloud.tasks.v2beta3.Task} + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The first element of the array is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * const task = {}; + * const request = { + * parent: formattedParent, + * task: task, + * }; + * client.createTask(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + createTask: MethodOverload; + + /** + * Deletes a task. + * + * A task can be deleted if it is scheduled or dispatched. A task + * cannot be deleted if it has executed successfully or permanently + * failed. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.taskPath('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]'); + * client.deleteTask({name: formattedName}).catch(err => { + * console.error(err); + * }); + */ + deleteTask: MethodOverload; + + /** + * Forces a task to run now. + * + * When this method is called, Cloud Tasks will dispatch the task, even if + * the task is already running, the queue has reached its RateLimits or + * is PAUSED. + * + * This command is meant to be used for manual debugging. For + * example, RunTask can be used to retry a failed + * task after a fix has been made or to manually force a task to be + * dispatched now. + * + * The dispatched task is returned. That is, the task that is returned + * contains the status after the task is dispatched but + * before the task is received by its target. + * + * If Cloud Tasks receives a successful response from the task's + * target, then the task will be deleted; otherwise the task's + * schedule_time will be reset to the time that + * RunTask was called plus the retry delay specified + * in the queue's RetryConfig. + * + * RunTask returns + * NOT_FOUND when it is called on a + * task that has already succeeded or permanently failed. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The first element of the array is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.taskPath('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]'); + * client.runTask({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + runTask: MethodOverload; + + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified project resource name string. + * + * @param project + */ + projectPath(project: string): string; + + /** + * Return a fully-qualified location resource name string. + * + * @param project + * @param location + */ + locationPath(project: string, location: string): string; + + /** + * Return a fully-qualified queue resource name string. + * + * @param project + * @param location + * @param queue + */ + queuePath(project: string, location: string, queue: string): string; + + /** + * Return a fully-qualified task resource name string. + * + * @param project + * @param location + * @param queue + * @param task + */ + taskPath( + project: string, + location: string, + queue: string, + task: string + ): string; + + /** + * Parse the projectName from a project resource. + * + * @param projectName + * A fully-qualified path representing a project resources. + */ + matchProjectFromProjectName(projectName: string): string; + + /** + * Parse the locationName from a location resource. + * + * @param locationName + * A fully-qualified path representing a location resources. + */ + matchProjectFromLocationName(locationName: string): string; + + /** + * Parse the locationName from a location resource. + * + * @param locationName + * A fully-qualified path representing a location resources. + */ + matchLocationFromLocationName(locationName: string): string; + + /** + * Parse the queueName from a queue resource. + * + * @param queueName + * A fully-qualified path representing a queue resources. + */ + matchProjectFromQueueName(queueName: string): string; + + /** + * Parse the queueName from a queue resource. + * + * @param queueName + * A fully-qualified path representing a queue resources. + */ + matchLocationFromQueueName(queueName: string): string; + + /** + * Parse the queueName from a queue resource. + * + * @param queueName + * A fully-qualified path representing a queue resources. + */ + matchQueueFromQueueName(queueName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchProjectFromTaskName(taskName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchLocationFromTaskName(taskName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchQueueFromTaskName(taskName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchTaskFromTaskName(taskName: string): string; +} diff --git a/types/google-cloud__tasks/ts3.1/tsconfig.json b/types/google-cloud__tasks/ts3.1/tsconfig.json new file mode 100644 index 0000000000..08ba955879 --- /dev/null +++ b/types/google-cloud__tasks/ts3.1/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "paths": { + "@google-cloud/tasks": ["google-cloud__tasks"] + }, + "baseUrl": "../../", + "typeRoots": ["../../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "google-cloud__tasks-tests.ts"] +} diff --git a/types/google-cloud__tasks/ts3.1/tslint.json b/types/google-cloud__tasks/ts3.1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/google-cloud__tasks/ts3.1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/google-cloud__tasks/tsconfig.json b/types/google-cloud__tasks/tsconfig.json new file mode 100644 index 0000000000..498e1217fc --- /dev/null +++ b/types/google-cloud__tasks/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "paths": { + "@google-cloud/tasks": ["google-cloud__tasks"] + }, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "google-cloud__tasks-tests.ts"] +} diff --git a/types/google-cloud__tasks/tslint.json b/types/google-cloud__tasks/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/google-cloud__tasks/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index 891186f7ee..085ab122c1 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -288,6 +288,12 @@ export declare class RequestError implements Error { public name: string; public message: string; public code: string; + public number?: number; + public state?: number; + public class?: number; + public lineNumber?: number; + public serverName?: string; + public procName?: string; } export declare class Transaction extends events.EventEmitter { diff --git a/types/multiparty/index.d.ts b/types/multiparty/index.d.ts index ca968fefcf..1dbb3e272b 100644 --- a/types/multiparty/index.d.ts +++ b/types/multiparty/index.d.ts @@ -19,6 +19,13 @@ export declare class Form extends events.EventEmitter { * @param callback */ parse(request: http.IncomingMessage, callback?: (error: Error, fields: any, files: any) => any): void; + + on(event: "part", listener: (part: Part) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "progress", listener: (bytesReceived: number, bytesExpected: number) => void): this; + on(event: "field", listener: (name: string, value: string) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; } export interface File { @@ -29,7 +36,7 @@ export interface File { /** * the filename that the user reports for the file */ - originalFileName: string; + originalFilename: string; /** * the absolute path of the uploaded file on disk */ @@ -44,7 +51,7 @@ export interface File { size: number; } -interface Part extends stream.Readable { +export interface Part extends stream.Readable { /** * the headers for this part. For example, you may be interested in content-type */ diff --git a/types/needle/index.d.ts b/types/needle/index.d.ts index 509e212c6e..af879cfacc 100644 --- a/types/needle/index.d.ts +++ b/types/needle/index.d.ts @@ -247,6 +247,7 @@ declare namespace needle { export type NeedleCallback = core.NeedleCallback; export type NeedleHttpVerbs = core.NeedleHttpVerbs; export type NeedleOptions = core.NeedleOptions; + export type NeedleResponse = core.NeedleResponse; export type ReadableStream = core.ReadableStream; /** diff --git a/types/needle/needle-tests.ts b/types/needle/needle-tests.ts index a216b1f686..fac7efa58c 100644 --- a/types/needle/needle-tests.ts +++ b/types/needle/needle-tests.ts @@ -73,14 +73,18 @@ function API_head() { function API_get() { // using promises + let resp: needle.NeedleResponse; + needle('get', 'google.com/search?q=syd+barrett') - .then((resp) => { + .then((_resp) => { // if no http:// is found, Needle will automagically prepend it. + resp = _resp; }); // using callback - needle.get('google.com/search?q=syd+barrett', (err, resp) => { + needle.get('google.com/search?q=syd+barrett', (err, _resp) => { // if no http:// is found, Needle will automagically prepend it. + resp = _resp; // assign response }); } diff --git a/types/next-seo/index.d.ts b/types/next-seo/index.d.ts new file mode 100644 index 0000000000..8d7c487393 --- /dev/null +++ b/types/next-seo/index.d.ts @@ -0,0 +1,84 @@ +// Type definitions for next-seo 1.10 +// Project: https://github.com/garmeeh/next-seo#readme +// Definitions by: Thomas Kosiewski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Component } from "react"; + +export interface NextSeoProps { + config: Config; +} + +export interface Config { + title?: string; + titleTemplate?: string; + description?: string; + canonical?: string; + + dangerouslySetAllPagesToNoIndex?: boolean; + noindex?: boolean; + + twitter?: Twitter; + facebook?: Facebook; + openGraph?: OpenGraph; +} + +export interface Twitter { + cardType?: string; + site?: string; + handle?: string; +} + +export interface Facebook { + appId?: number; +} + +export interface OpenGraph { + url?: string; + type?: string; + title?: string; + description?: string; + images?: ReadonlyArray; + defaultImageHeight?: number; + defaultImageWidth?: number; + locale?: string; + site_name?: string; + + profile?: OpenGraphProfile; + book?: OpenGraphBook; + article?: OpenGraphArticle; +} + +export interface OpenGraphImages { + url?: string; + width?: number; + height?: number; + alt?: string; +} + +export interface OpenGraphProfile { + firstName?: string; + lastName?: string; + username?: string; + gender?: string; +} + +export interface OpenGraphBook { + authors?: ReadonlyArray; + isbn?: string; + releaseDate?: string; + tags?: ReadonlyArray; +} + +export interface OpenGraphArticle { + publishedTime?: string; + modifiedTime?: string; + expirationTime?: string; + + authors?: ReadonlyArray; + section?: string; + tags?: ReadonlyArray; +} + +export default class NextSeo extends Component { } diff --git a/types/next-seo/next-seo-tests.ts b/types/next-seo/next-seo-tests.ts new file mode 100644 index 0000000000..3c2da4b032 --- /dev/null +++ b/types/next-seo/next-seo-tests.ts @@ -0,0 +1,48 @@ +import NextSeo from 'next-seo'; + +new NextSeo({ + config: { + canonical: "", + dangerouslySetAllPagesToNoIndex: false, + description: "", + facebook: { + appId: 0, + }, + noindex: false, + openGraph: { + book: { + authors: [""], + isbn: "", + releaseDate: "", + tags: [""], + }, + defaultImageHeight: 0, + defaultImageWidth: 0, + description: "", + images: [{ + alt: "", + height: 0, + url: "", + width: 0, + }], + locale: "", + profile: { + firstName: "", + gender: "", + lastName: "", + username: "", + }, + site_name: "", + title: "", + type: "", + url: "", + }, + title: "", + titleTemplate: "", + twitter: { + cardType: "", + handle: "", + site: "", + }, + }, +}); diff --git a/types/next-seo/tsconfig.json b/types/next-seo/tsconfig.json new file mode 100644 index 0000000000..faea26b9bc --- /dev/null +++ b/types/next-seo/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "target": "es6", + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "next-seo-tests.ts" + ] +} diff --git a/types/next-seo/tslint.json b/types/next-seo/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/next-seo/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/next/app.d.ts b/types/next/app.d.ts index 392b997f89..3e933c09c6 100644 --- a/types/next/app.d.ts +++ b/types/next/app.d.ts @@ -53,6 +53,6 @@ export type AppComponentType

= NextComponent >; export class Container extends React.Component {} -export default class App

extends React.Component

{ +export default class App

extends React.Component

{ static getInitialProps(context: NextAppContext): Promise; } diff --git a/types/next/test/next-app-tests.tsx b/types/next/test/next-app-tests.tsx index eaa2c0ad07..514cc24436 100644 --- a/types/next/test/next-app-tests.tsx +++ b/types/next/test/next-app-tests.tsx @@ -6,6 +6,10 @@ interface TestAppProps { pageProps: any; } +interface TestAppState { + color: string; +} + interface TypedQuery extends DefaultQuery { id?: string; } @@ -33,6 +37,20 @@ class TestAppWithProps extends App { } } +class ErrorTestAppWithState extends App { + static async getInitialProps({ Component, router, ctx }: NextAppContext) { + const pageProps = Component.getInitialProps && (await Component.getInitialProps(ctx)); + return { pageProps }; + } + + render() { + const { Component, router, pageProps, example } = this.props; + return ; + } + + state: {}; // $ExpectError +} + class TestAppWithTypedQuery extends App { static async getInitialProps({ ctx }: NextAppContext) { const { id } = ctx.query; diff --git a/types/node-sql-parser/index.d.ts b/types/node-sql-parser/index.d.ts new file mode 100644 index 0000000000..c711212c63 --- /dev/null +++ b/types/node-sql-parser/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for node-sql-parser 1.0 +// Project: https://github.com/taozhi8833998/node-sql-parser#readme +// Definitions by: taozhi8833998 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export interface With { + name: string; + stmt: any[]; + columns?: any[]; +} +export type WhilteListCheckMode = 'table' | 'column'; +export interface TableColumnAst { + tableList: string[]; + columnsList: string[]; + ast: AST[] | AST; +} +export interface From { + db: string | null; + table: string; + as: string | null; +} +export interface Dual { + type: 'dual'; +} +export interface Limit { + type: string; + value: number; +} +export interface OrderBy { + type: 'ASC' | 'DESC'; + expr: any; +} +export interface ColumnRef { + type: 'column_ref'; + table: string | null; + column: string; +} +export interface SetList { + column: string; + value: any; + table: string | null; +} +export interface InsertReplaceValue { + type: 'expr_list'; + value: any[]; +} +export interface Select { + with: With | null; + type: 'select'; + options: any[] | null; + distinct: 'DISTINCT' | null; + columns: any[] | '*'; + from: Array | null; + where: any; + groupby: ColumnRef[] | null; + having: any[] | null; + orderby: OrderBy[] | null; + limit: Limit[] | null; +} +export interface Insert_Replace { + type: 'replace' | 'insert'; + db: string | null; + table: string; + columns: string[] | null; + values: InsertReplaceValue[]; +} +export interface Update { + type: 'udpate'; + db: string | null; + table: string; + set: SetList[]; + where: any; +} +export interface Delete { + type: 'delete'; + tables: any; + from: Array; + where: any; +} +export type AST = Select | Insert_Replace | Update | Delete; + +export class Parser { + constructor(); + + parse(sql: string): TableColumnAst; + + astify(sql: string): AST[] | AST; + + sqlify(ast: AST[] | AST): string; + + whiteListCheck(sql: string, whiteList: string[], type?: WhilteListCheckMode): Error | undefined; + + tableList(sql: string): string[]; + + columnList(sql: string): string[]; +} diff --git a/types/node-sql-parser/node-sql-parser-tests.ts b/types/node-sql-parser/node-sql-parser-tests.ts new file mode 100644 index 0000000000..050c69a855 --- /dev/null +++ b/types/node-sql-parser/node-sql-parser-tests.ts @@ -0,0 +1,19 @@ +import { Parser } from 'node-sql-parser'; + +const parser = new Parser(); +const sql = 'select id from tableA'; + +// $ExpectType Select | Insert_Replace | Update | Delete | AST[] +const selectAst = parser.astify(sql); + +// $ExpectType string +parser.sqlify(selectAst); + +// $ExpectType string[] +parser.tableList(sql); + +// $ExpectType string[] +parser.columnList(sql); + +// $ExpectType Error | undefined +parser.whiteListCheck(sql, ['select::null::tableA'], 'table'); diff --git a/types/node-sql-parser/tsconfig.json b/types/node-sql-parser/tsconfig.json new file mode 100644 index 0000000000..c7f24afb95 --- /dev/null +++ b/types/node-sql-parser/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "node-sql-parser-tests.ts" + ] +} diff --git a/types/node-sql-parser/tslint.json b/types/node-sql-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/node-sql-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index c63b6c892b..417782b2f3 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -32,6 +32,7 @@ // Zane Hannan AU // Jeremie Rodriguez // Samuel Ainsworth +// Kyle Uehlein // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** inspector module types */ @@ -2886,6 +2887,7 @@ declare module "child_process" { gid?: number; windowsHide?: boolean; windowsVerbatimArguments?: boolean; + shell?: boolean | string; } interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { encoding: BufferEncoding; diff --git a/types/nodegit/index.d.ts b/types/nodegit/index.d.ts index d1afcd6ea4..680aec7174 100644 --- a/types/nodegit/index.d.ts +++ b/types/nodegit/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for nodegit 0.22 +// Type definitions for nodegit 0.24 // Project: https://github.com/nodegit/nodegit // Definitions by: Dolan Miu , Tobias Nießen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -79,7 +79,7 @@ export { Refspec } from './ref-spec'; export { Reference } from './reference'; export { RemoteCallbacks } from './remote-callbacks'; export { Remote } from './remote'; -export { Repository } from './repository'; +export { Repository, RepositoryInitOptions } from './repository'; export { Reset } from './reset'; export { Revparse } from './rev-parse'; export { Revwalk } from './rev-walk'; diff --git a/types/obelisk.js/index.d.ts b/types/obelisk.js/index.d.ts index 2e4cf8bc3d..d28643e2c5 100644 --- a/types/obelisk.js/index.d.ts +++ b/types/obelisk.js/index.d.ts @@ -1,228 +1,262 @@ -// Type definitions for obelisk.js v1.1.0 +// Type definitions for obelisk.js 1.2 // Project: https://github.com/nosir/obelisk.js/ // Definitions by: Brian Drupieski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace obelisk { +export as namespace obelisk; - export var version: string; - export var author: string; +export var version: string; +export var author: string; - export class Matrix { - constructor(a?: number, b?: number, c?: number, d?: number, tx?: number, ty?: number); +export class Matrix { + constructor(a?: number, b?: number, c?: number, d?: number, tx?: number, ty?: number); - a: number; - b: number; - c: number; - d: number; - tx: number; - ty: number; - } + a: number; + b: number; + c: number; + d: number; + tx: number; + ty: number; +} + +export class Point { + constructor(x?: number, y?: number); - export class Point { - constructor(x?: number, y?: number); + x: number; + y: number; +} - x: number; - y: number; - } +export class Point3D { + constructor(x?: number, y?: number, z?: number); + + x: number; + y: number; + z: number; + + toGlobalCoordinates(offset?: obelisk.Point): obelisk.Point; +} + +export class ColorGeom { + static get32(color: number): number; + static applyBrightness(color: number, brightness: number, highlight?: boolean): number; +} + +export class ColorPattern { + static GRASS_GREEN: number; + static YELLOW: number; + static WINE_RED: number; + static PINK: number; + static PURPLE: number; + static BLUE: number; + static GRAY: number; + static BLACK: number; + static FINE_COLORS: number[]; + + static getRandomComfortableColor(): number; +} + +export class CanvasTool { + static getPixel(imageData: ImageData, x: number, y: number): number; +} + +export class CanvasManager { + static defaultCanvas: HTMLCanvasElement; + + static getDefaultCanvas(): HTMLCanvasElement; + static getNewCanvas(): HTMLCanvasElement; +} + +export class AbstractColor { + constructor(); + + inner: number; + border: number; + borderHighlight: number; + left: number; + right: number; + horizontal: number; + leftSlope: number; + rightSlope: number; +} + +export class CubeColor extends AbstractColor { + constructor(border?: number, borderHighlight?: number, left?: number, right?: number, horizontal?: number); + + BRIGHTNESS_GAIN: number; + + getByHorizontalColor(horizontal: number): CubeColor; +} + +export class PyramidColor extends AbstractColor { + constructor(border?: number, borderHighlight?: number, left?: number, right?: number); + + BRIGHTNESS_GAIN: number; + + getByRightColor(horizontal: number): PyramidColor; +} + +export class SideColor extends AbstractColor { + constructor(border?: number, inner?: number); + + BRIGHTNESS_GAIN: number; + + getByInnerColor(inner: number): SideColor; +} + +export class SlopeColor extends AbstractColor { + constructor( + border?: number, + borderHighlight?: number, + left?: number, + right?: number, + leftSlope?: number, + rightSlope?: number, + ); + + BRIGHTNESS_GAIN: number; + + getByHorizontalColor(horizontal: number): SlopeColor; +} + +export class LineColor extends AbstractColor { + constructor(border?: number, inner?: number); +} + +export class AbstractDimension { + constructor(); + + xAxis: number; + yAxis: number; + zAxis: number; + tall: boolean; +} + +export class BrickDimension extends AbstractDimension { + constructor(xAxis?: number, yAxis?: number); +} + +export class CubeDimension extends AbstractDimension { + constructor(xAxis?: number, yAxis?: number, zAxis?: number); +} + +export class PyramidDimension extends AbstractDimension { + constructor(axis?: number, tall?: boolean); +} + +export class SideXDimension extends AbstractDimension { + constructor(xAxis?: number, zAxis?: number); +} + +export class SideYDimension extends AbstractDimension { + constructor(yAxis?: number, zAxis?: number); +} - export class Point3D { - constructor(x?: number, y?: number, z?: number); +export class SlopeDimension extends AbstractDimension { + constructor(xAxis?: number, yAxis?: number); +} - x: number; - y: number; - z: number; +export class LineXDimension extends AbstractDimension { + constructor(axis?: number); +} - toGlobalCoordinates(offset?: obelisk.Point): obelisk.Point; - } +export class LineYDimension extends AbstractDimension { + constructor(axis?: number); +} + +export class LineZDimension extends AbstractDimension { + constructor(axis?: number); +} + +export class BitmapData { + constructor(w: number, h: number, useDefaultCanvas?: boolean); + + imageData: ImageData; + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; - export class ColorGeom { - static get32(color: number): number; - static applyBrightness(color: number, brightness: number, highlight?: boolean): number; - } + setPixel(posX: number, posY: number, color: number): void; + setPixelByIndex(index: number, color: number): void; + checkPixelAvailable(x: number, y: number): boolean; + floodFill(posX: number, posY: number, color: number): void; +} - export class ColorPattern { - static GRASS_GREEN: number; - static YELLOW: number; - static WINE_RED: number; - static PINK: number; - static PURPLE: number; - static BLUE: number; - static GRAY: number; - static BLACK: number; - static FINE_COLORS: number[]; +export class PixelObject { + constructor(primitive: AbstractPrimitive, point3D?: Point3D); - static getRandomComfortableColor(): number; - } + x: number; + y: number; + canvas: HTMLCanvasElement; +} + +export class PixelView { + constructor(canvas: HTMLCanvasElement, point?: Point); + + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; + point: Point; + + renderObject(primitive: AbstractPrimitive, point3D?: Point3D): void; + clear(): void; +} + +export class AbstractPrimitive { + constructor(); + + canvas: HTMLCanvasElement; + w: number; + h: number; + dimension: AbstractDimension; + color: AbstractColor; + border: boolean; + bitmapData: BitmapData; + useDefaultCanvas: boolean; + matrix: Matrix; +} - export class CanvasTool { - static getPixel(imageData: ImageData, x: number, y: number): number; - } - - export class CanvasManager { - static defaultCanvas: HTMLCanvasElement; - - static getDefaultCanvas(): HTMLCanvasElement; - static getNewCanvas(): HTMLCanvasElement; - } - - export class AbstractColor { - constructor(); - - inner: number; - border: number; - borderHighlight: number; - left: number; - right: number; - horizontal: number; - leftSlope: number; - rightSlope: number; - } - - export class CubeColor extends AbstractColor { - constructor(border?: number, borderHighlight?: number, left?: number, right?: number, horizontal?: number); - - BRIGHTNESS_GAIN: number; - - getByHorizontalColor(horizontal: number): CubeColor; - } - - export class PyramidColor extends AbstractColor { - constructor(border?: number, borderHighlight?: number, left?: number, right?: number); - - BRIGHTNESS_GAIN: number; - - getByRightColor(horizontal: number): PyramidColor; - } - - export class SideColor extends AbstractColor { - constructor(border?: number, inner?: number); - - BRIGHTNESS_GAIN: number; - - getByInnerColor(inner: number): SideColor; - } - - export class SlopeColor extends AbstractColor { - constructor(border?: number, borderHighlight?: number, left?: number, right?: number, leftSlope?: number, rightSlope?: number); - - BRIGHTNESS_GAIN: number; - - getByHorizontalColor(horizontal: number): SlopeColor; - } - - export class AbstractDimension { - constructor(); - - xAxis: number; - yAxis: number; - zAxis: number; - tall: boolean; - } - - export class BrickDimension extends AbstractDimension { - constructor(xAxis?: number, yAxis?: number); - } - - export class CubeDimension extends AbstractDimension { - constructor(xAxis?: number, yAxis?: number, zAxis?: number); - } - - export class PyramidDimension extends AbstractDimension { - constructor(axis?: number, tall?: boolean); - } - - export class SideXDimension extends AbstractDimension { - constructor(xAxis?: number, zAxis?: number); - } - - export class SideYDimension extends AbstractDimension { - constructor(yAxis?: number, zAxis?: number); - } - - export class SlopeDimension extends AbstractDimension { - constructor(xAxis?: number, yAxis?: number); - } - - export class BitmapData { - constructor(w: number, h: number, useDefaultCanvas?: boolean); - - imageData: ImageData; - canvas: HTMLCanvasElement; - context : CanvasRenderingContext2D; - - setPixel(posX: number, posY: number, color: number): void; - setPixelByIndex(index: number, color: number): void; - checkPixelAvailable(x: number, y: number): boolean; - floodFill(posX: number, posY: number, color: number): void; - } - - export class PixelObject { - constructor(primitive: AbstractPrimitive, point3D?: Point3D); - - x: number; - y: number; - canvas: HTMLCanvasElement; - } - - export class PixelView { - constructor(canvas: HTMLCanvasElement, point?: Point); - - canvas: HTMLCanvasElement; - context: CanvasRenderingContext2D; - point: Point; - - renderObject(primitive: AbstractPrimitive, point3D?: Point3D): void; - clear(): void; - } - - export class AbstractPrimitive { - constructor(); - - canvas: HTMLCanvasElement; - w: number; - h: number; - dimension: AbstractDimension; - color: AbstractColor; - border: boolean; - bitmapData: BitmapData; - useDefaultCanvas: boolean; - matrix: Matrix; - } - - export class Brick extends AbstractPrimitive { - constructor(dimension?: BrickDimension, color?: SideColor, border?: boolean, useDefaultCanvas?: boolean); - } - - export class Cube extends AbstractPrimitive { - constructor(dimension?: CubeDimension, color?: CubeColor, border?: boolean, useDefaultCanvas?: boolean); - } - - export class Pyramid extends AbstractPrimitive { - constructor(dimension?: PyramidDimension, color?: PyramidColor, border?: boolean, useDefaultCanvas?: boolean); - } - - export class SideX extends AbstractPrimitive { - constructor(dimension?: SideXDimension, color?: SideColor, border?: boolean, useDefaultCanvas?: boolean); - } - - export class SideY extends AbstractPrimitive { - constructor(dimension?: SideYDimension, color?: SideColor, border?: boolean, useDefaultCanvas?: boolean); - } - - export class SlopeEast extends AbstractPrimitive { - constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean); - } - - export class SlopeNorth extends AbstractPrimitive { - constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean); - } - - export class SlopeSouth extends AbstractPrimitive { - constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean); - } - - export class SlopeWest extends AbstractPrimitive { - constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean); - } +export class Brick extends AbstractPrimitive { + constructor(dimension?: BrickDimension, color?: SideColor, border?: boolean, useDefaultCanvas?: boolean); +} + +export class Cube extends AbstractPrimitive { + constructor(dimension?: CubeDimension, color?: CubeColor, border?: boolean, useDefaultCanvas?: boolean); +} + +export class Pyramid extends AbstractPrimitive { + constructor(dimension?: PyramidDimension, color?: PyramidColor, border?: boolean, useDefaultCanvas?: boolean); +} + +export class SideX extends AbstractPrimitive { + constructor(dimension?: SideXDimension, color?: SideColor, border?: boolean, useDefaultCanvas?: boolean); +} + +export class SideY extends AbstractPrimitive { + constructor(dimension?: SideYDimension, color?: SideColor, border?: boolean, useDefaultCanvas?: boolean); +} + +export class SlopeEast extends AbstractPrimitive { + constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean); +} + +export class SlopeNorth extends AbstractPrimitive { + constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean); +} + +export class SlopeSouth extends AbstractPrimitive { + constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean); +} + +export class SlopeWest extends AbstractPrimitive { + constructor(dimension?: SlopeDimension, color?: SlopeColor, border?: boolean, useDefaultCanvas?: boolean); +} + +export class LineX extends AbstractPrimitive { + constructor(dimension?: LineXDimension, color?: LineColor, useDefaultCanvas?: boolean); +} + +export class LineY extends AbstractPrimitive { + constructor(dimension?: LineYDimension, color?: LineColor, useDefaultCanvas?: boolean); +} + +export class LineZ extends AbstractPrimitive { + constructor(dimension?: LineZDimension, color?: LineColor, useDefaultCanvas?: boolean); } diff --git a/types/obelisk.js/obelisk.js-tests.ts b/types/obelisk.js/obelisk.js-tests.ts index e47b474467..4cc4328409 100644 --- a/types/obelisk.js/obelisk.js-tests.ts +++ b/types/obelisk.js/obelisk.js-tests.ts @@ -1,3 +1,5 @@ +import * as obelisk from 'obelisk.js'; + function test_brick() { var canvas = document.getElementById('canvas-demo'); @@ -143,4 +145,31 @@ function test_gif_rendering() { var floorDimension = new obelisk.CubeDimension((size - 2) * (WIDTH + 2), (size - 2) * 9, size); var floor = new obelisk.Cube(floorDimension, new obelisk.CubeColor(), false); pixelViewFloor.renderObject(floor, new obelisk.Point3D(-20, -30, 0)); -} \ No newline at end of file +} + +function test_line_rendering() { + var canvas = document.getElementById('canvas-demo') as HTMLCanvasElement; + + // create pixel view container in point + var point = new obelisk.Point(400, 200); + var pixelView = new obelisk.PixelView(canvas, point); + + // create brick + var colorX = new obelisk.LineColor(obelisk.ColorPattern.PINK); + var colorY = new obelisk.LineColor(obelisk.ColorPattern.BLACK); + var colorZ = new obelisk.LineColor(obelisk.ColorPattern.BLUE); + + var dimensionX = new obelisk.LineXDimension(100); + var dimensionY = new obelisk.LineYDimension(100); + var dimensionZ = new obelisk.LineZDimension(100); + + var lineX = new obelisk.LineX(dimensionX, colorX); + var lineY = new obelisk.LineY(dimensionY, colorY); + var lineZ = new obelisk.LineZ(dimensionZ, colorZ); + + // render in view + var p3D = new obelisk.Point3D(0, 0, 0); + pixelView.renderObject(lineX, p3D); + pixelView.renderObject(lineY, p3D); + pixelView.renderObject(lineZ, p3D); +} diff --git a/types/obelisk.js/tslint.json b/types/obelisk.js/tslint.json index d67ffb3a73..40aa0a5f91 100644 --- a/types/obelisk.js/tslint.json +++ b/types/obelisk.js/tslint.json @@ -7,7 +7,7 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, + "dt-header": true, "eofline": false, "export-just-namespace": false, "import-spacing": false, diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index fab2c5095a..75e9ed910f 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -10844,8 +10844,8 @@ declare namespace Office { * * * Appointment items - * These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurence. - * IPM.Appointment,IPM.Appointment.Occurence + * These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurrence. + * IPM.Appointment,IPM.Appointment.Occurrence * * * Message items @@ -12648,8 +12648,8 @@ declare namespace Office { * * * Appointment items - * These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurence. - * IPM.Appointment,IPM.Appointment.Occurence + * These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurrence. + * IPM.Appointment,IPM.Appointment.Occurrence * * * Message items @@ -14303,8 +14303,8 @@ declare namespace Office { * * * Appointment items - * These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurence. - * IPM.Appointment,IPM.Appointment.Occurence + * These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurrence. + * IPM.Appointment,IPM.Appointment.Occurrence * * * Message items diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 0c13640c74..f0fee147ba 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -10844,8 +10844,8 @@ declare namespace Office { * * * Appointment items - * These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurence. - * IPM.Appointment,IPM.Appointment.Occurence + * These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurrence. + * IPM.Appointment,IPM.Appointment.Occurrence * * * Message items @@ -12648,8 +12648,8 @@ declare namespace Office { * * * Appointment items - * These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurence. - * IPM.Appointment,IPM.Appointment.Occurence + * These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurrence. + * IPM.Appointment,IPM.Appointment.Occurrence * * * Message items @@ -14303,8 +14303,8 @@ declare namespace Office { * * * Appointment items - * These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurence. - * IPM.Appointment,IPM.Appointment.Occurence + * These are calendar items of the item class IPM.Appointment or IPM.Appointment.Occurrence. + * IPM.Appointment,IPM.Appointment.Occurrence * * * Message items diff --git a/types/opossum/index.d.ts b/types/opossum/index.d.ts index b17a1dd0be..612615ad86 100644 --- a/types/opossum/index.d.ts +++ b/types/opossum/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for opossum 1.9 +// Type definitions for opossum 1.10 // Project: https://github.com/nodeshift/opossum // Definitions by: Quinn Langille // Willy Zhang @@ -23,6 +23,7 @@ export class CircuitBreaker extends EventEmitter { readonly closed: boolean; readonly opened: boolean; readonly halfOpen: boolean; + readonly isShutdown: boolean; readonly status: Status; readonly stats: Stats; readonly hystrixStats: HystrixStats; @@ -40,6 +41,7 @@ export class CircuitBreaker extends EventEmitter { func: (...args: any[]) => Promise, interval?: number ): void; + shutdown(): void; } export enum Event { diff --git a/types/opossum/opossum-tests.ts b/types/opossum/opossum-tests.ts index ebbf0bea47..69d64497f0 100644 --- a/types/opossum/opossum-tests.ts +++ b/types/opossum/opossum-tests.ts @@ -39,6 +39,7 @@ breaker.closed; // $ExpectType boolean breaker.opened; // $ExpectType boolean breaker.halfOpen; // $ExpectType boolean breaker.warmUp; // $ExpectType boolean +breaker.isShutdown; // $ExpectType boolean breaker.volumeThreshold; // $ExpectType number breaker.status.stats.latencyMean; // $ExpectType number breaker.stats.latencyTimes; // $ExpectType number[] @@ -49,6 +50,7 @@ breaker.open(); // $ExpectType void breaker.close(); // $ExpectType void breaker.disable(); // $ExpectType void breaker.enable(); // $ExpectType void +breaker.shutdown(); // $ExpectType void // The following are examples are from the libs README and official documentation // https://nodeshift.github.io/opossum/index.html. diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index 6c1f2979fb..08a6d794ad 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -21,26 +21,7 @@ declare module paper { /** * Gives access to paper's configurable settings. */ - export var settings: { - - /** - * controls whether newly created items are automatically inserted into the scene graph, by adding them to project.activeLayer — default: true - */ - insertItems: boolean; - /** - * controls what value newly created items have their item.applyMatrix property set to (Note that not all items can set this to false) — default: true - */ - applyMatrix: boolean; - /** - * the size of the curve handles when drawing selections — default: 4 - */ - handleSize: number; - /* - * the default tolerance for hit- tests, when no value is specified — default: 0 - */ - hitTolerance: number; - - }; + export var settings: Settings; /** * The currently active project. @@ -1163,13 +1144,7 @@ declare module paper { /** * Gives access to paper's configurable settings. */ - settings: { - - applyMatrix: boolean; - handleSize: number; - hitTolerance: number; - - }; + settings: Settings; /** * The currently active project. @@ -5481,6 +5456,25 @@ declare module paper { type: 'mousedown' | 'mouseup' | 'mousedrag' | 'click' | 'doubleclick' | 'mousemove' | 'mouseenter' | 'mouseleave'; } + + export interface Settings { + /** + * controls whether newly created items are automatically inserted into the scene graph, by adding them to project.activeLayer — default: true + */ + insertItems: boolean; + /** + * controls what value newly created items have their item.applyMatrix property set to (Note that not all items can set this to false) — default: true + */ + applyMatrix: boolean; + /** + * the size of the curve handles when drawing selections — default: 4 + */ + handleSize: number; + /* + * the default tolerance for hit- tests, when no value is specified — default: 0 + */ + hitTolerance: number; + } } declare module 'paper' diff --git a/types/paper/paper-tests.ts b/types/paper/paper-tests.ts index 1d1bc32abe..280b68c0e9 100644 --- a/types/paper/paper-tests.ts +++ b/types/paper/paper-tests.ts @@ -81,6 +81,10 @@ hitTestResults = paper.project.hitTestAll(hitTestPoint, hitOptionsInterfaceFull) paper.view.scaling = new paper.Point(1, 1); +paper.settings.insertItems = true +const paperScope = new paper.PaperScope(); +paperScope.settings.insertItems = false; + function Examples() { function BooleanOperations(){ let text = new paper.PointText({ diff --git a/types/react-bootstrap-typeahead/index.d.ts b/types/react-bootstrap-typeahead/index.d.ts index 52f99825d5..2f1ad8b7be 100644 --- a/types/react-bootstrap-typeahead/index.d.ts +++ b/types/react-bootstrap-typeahead/index.d.ts @@ -4,37 +4,121 @@ // Rajab Shakirov // Paito Anderson // Andreas Richter +// Dale Fenton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 -// TODO: components +// TypeScript Version: 2.9 import * as React from 'react'; -import * as CSS from 'csstype'; +export type Omit = Pick>; +export type StringPropertyNames = { [K in keyof T]: T[K] extends string ? K : never }[keyof T]; -export interface TypeaheadFilterbyProps { - filterBy: string[]; - labelKey: (string | (() => void)); - multiple: boolean; - selected: any[]; - caseSensitive: boolean; - ignoreDiacritics: boolean; +/* --------------------------------------------------------------------------- + Constants and Enumerated Types +--------------------------------------------------------------------------- */ +export type TypeaheadModel = string|object; +export type TypeaheadBsSizes = 'large' | 'lg' | 'small' | 'sm'; +export type TypeaheadAlign = 'justify' | 'left' | 'right'; +// if options is an object, only let labelKey be a key of that object, whose value is a string +// or a custom label function that takes a single option and returns a string for the label +export type TypeaheadLabelKey = T extends object ? (StringPropertyNames | ((option: T) => string)) : never; +// don't allow onBlur, onChange, onFocus or onKeyDown as members of inputProps +// those props should be supplied directly to or +export interface InputProps extends Omit, 'onBlur'|'onChange'|'onFocus'|'onKeyDown'> { } + +/* --------------------------------------------------------------------------- + Typeahead Contexts +--------------------------------------------------------------------------- */ +export interface TypeaheadContext { + activeIndex?: number; + hintText?: string; + initialItem?: T; + isOnlyResult?: boolean; + onActiveItemChange?: (options: T) => void; + onAdd?: (option: T) => void; + onInitialItemChange?: (option: T) => void; + onMenuItemClick?: (option: T, e: Event) => void; + selectHintOnEnter?: boolean; +} + +export interface TypeaheadState { + activeIndex: number|null; + activeItem: T|null; + initialItem: T|null; + isFocused: boolean; + selected: T[]; + showMenu: boolean; + shownResults: number; text: string; } -export interface TypeaheadMenuProps { +export interface InputContainerPropsSingle { + 'aria-activedescendant': string; + 'aria-autocomplete': 'list' | 'both'; + 'aria-expanded': boolean | 'true' | 'false'; + 'aria-haspopup': 'listbox'; + 'aria-owns': string; + autoComplete: string; + disabled: boolean; + inputRef: React.LegacyRef; + onBlur: (e: Event) => void; + onChange: (selected: T[]) => void; + onClick: (e: Event) => void; + onFocus: (e: Event) => void; + onKeyDown: (e: Event) => void; + placeholder: string|null; + role: 'combobox'; + value: string; +} + +export interface InputContainerPropsMultiple extends Omit, 'role'> { + inputClassName: string; + labelKey: TypeaheadLabelKey; + onRemove: (e: Event) => void; + renderToken: (selectedItem: T, props: TypeaheadMenuProps, index: number) => React.ReactNode; + role: ''; + selected: T[]; +} + +export type HintedInputContextKeys = 'hintText' | 'initialItem' | 'onAdd' | 'selectHintOnEnter'; +export interface HintedInputContext extends Pick, HintedInputContextKeys> {} + +export type MenuItemContextKeys = 'activeIndex' | 'isOnlyResult' | 'onActiveItemChange' | 'onInitialItemChange' | 'onMenuItemClick'; +export interface MenuItemContext extends Pick, MenuItemContextKeys> {} + +export interface TokenContext { + active: boolean; + onBlur: (e: any) => void; + onClick: (e: any) => void; + onFocus: (e: any) => void; + onKeyDown: (e: any) => void; +} + +/* --------------------------------------------------------------------------- + Typeahead Props and Component +--------------------------------------------------------------------------- */ +export interface TypeaheadContainerProps { + activeIndex: number | null; + activeItem: T | null; + initialItem: T | null; + isFocused: boolean; + selected: T[]; + showMenu: boolean; + shownResults: number; text: string; } -export interface TypeaheadProps { - /* For localized accessibility: Should return a string indicating the number of results for screen readers. Receives the current results. */ +export interface TypeaheadProps { + /* For localized accessibility: Should return a string indicating the number of results for screen readers. + Receives the current results. */ a11yNumResults?: () => void; - /* For localized accessibility: Should return a string indicating the number of selections for screen readers. Receives the current selections. */ + /* For localized accessibility: Should return a string indicating the number of selections for screen readers. + Receives the current selections. */ a11yNumSelected?: () => void; /* Specify menu alignment. The default value is justify, which makes the menu as wide as the input and truncates long values. Specifying left or right will align the menu to that side and the width will be determined by the length of menu item values. */ - align?: 'justify' | 'left' | 'right'; + align?: TypeaheadAlign; /* Allows the creation of new selections on the fly. Any new items will be added to the list of selections, but not the list of original options unless handled as such by Typeahead's parent. @@ -49,7 +133,7 @@ export interface TypeaheadProps { bodyContainer?: boolean; /* Specify the size of the input. */ - bsSize?: 'large' | 'lg' | 'small' | 'sm'; + bsSize?: TypeaheadBsSizes; /* Whether or not filtering should be case-sensitive. */ caseSensitive?: boolean; @@ -60,6 +144,9 @@ export interface TypeaheadProps { /* The initial value displayed in the text input. */ defaultInputValue?: string; + /* Whether or not the menu is displayed upon initial render. */ + defaultOpen?: boolean; + /* Specify any pre-selected options. Use only if you want the component to be uncontrolled. */ defaultSelected?: T[]; @@ -74,7 +161,10 @@ export interface TypeaheadProps { emptyLabel?: string; /* Either an array of fields in option to search, or a custom filtering callback. */ - filterBy?: (string[] | ((option: T | string, props: TypeaheadFilterbyProps) => boolean)); + filterBy?: (string[] | ((option: T, props: AllTypeaheadOwnAndInjectedProps) => boolean)); + + /* Whether or not to automatically adjust the position of the menu when it reaches the viewport boundaries. */ + flip?: boolean; /* Highlights the menu item if there is only one result and allows selecting that item by hitting enter. Does not work with allowNew. */ @@ -84,7 +174,7 @@ export interface TypeaheadProps { ignoreDiacritics?: boolean; /* Props to be applied directly to the input. onBlur, onChange, onFocus, and onKeyDown are ignored. */ - inputProps?: object; + inputProps?: InputProps; /* Bootstrap 4 only. Adds the `is-invalid` classname to the `form-control`. */ isInvalid?: boolean; @@ -95,8 +185,9 @@ export interface TypeaheadProps { /* Bootstrap 4 only. Adds the `is-valid` classname to the `form-control`. */ isValid?: boolean; - /* Specify which option key to use for display or a render function. By default, the selector will use the label key. */ - labelKey?: string | ((option: T | string) => string); + /* Specify which option key to use for display or a render function. + By default, the selector will use the label key. */ + labelKey?: TypeaheadLabelKey; /* Maximum height of the dropdown menu. */ maxHeight?: string; @@ -105,6 +196,9 @@ export interface TypeaheadProps { so as not to render too many DOM nodes in the case of large data sets. */ maxResults?: number; + /* Id applied to the top-level menu element. Required for accessibility. */ + menuId?: string; + /* Number of input characters that must be entered before showing results. */ minLength?: number; @@ -115,28 +209,35 @@ export interface TypeaheadProps { newSelectionPrefix?: string; /* Invoked when the input is blurred. Receives an event. */ - onBlur?: (e: Event) => any; + onBlur?: (e: Event) => void; /* Invoked whenever items are added or removed. Receives an array of the selected options. */ - onChange?: (selected: T[]) => any; + onChange?: (selected: T[]) => void; /* Invoked when the input is focused. Receives an event. */ - onFocus?: (e: Event) => any; + onFocus?: (e: Event) => void; /* Invoked when the input value changes. Receives the string value of the input, as well as the original event. */ - onInputChange?: (input: string, e: Event) => any; + onInputChange?: (input: string, e: Event) => void; /* Invoked when a key is pressed. Receives an event. */ - onKeyDown?: (e: Event) => any; + onKeyDown?: (e: Event) => void; - /* Invoked when the menu is hidden. */ - onMenuHide?: (e: Event) => any; + /* DEPRECATED: Invoked when the menu is hidden. */ + onMenuHide?: () => void; - /* Invoked when the menu is shown. */ - onMenuShow?: (e: Event) => any; + /* DEPRECATED: Invoked when the menu is shown. */ + onMenuShow?: () => void; + + /* Invoked when menu visibility changes. */ + onMenuToggle?: (show: boolean) => void; /* Invoked when the pagination menu item is clicked. */ - onPaginate?: (e: Event) => any; + onPaginate?: (e: Event, numResults: number) => void; + + /* Whether or not the menu should be displayed. undefined allows the component to control visibility, + while true and false show and hide the menu, respectively. */ + open?: boolean; /* Full set of options, including any pre-selected options. */ options: T[]; @@ -151,13 +252,13 @@ export interface TypeaheadProps { placeholder?: string; /* Callback for custom menu rendering. */ - renderMenu?: (results: Array, menuProps: any) => any; + renderMenu?: (results: T[], menuProps: any) => React.ReactNode; /* Provides a hook for customized rendering of menu item contents. */ - renderMenuItemChildren?: (option: T, props: TypeaheadMenuProps, index: number) => any; + renderMenuItemChildren?: (option: T, props: TypeaheadMenuProps, index: number) => React.ReactNode; /* Provides a hook for customized rendering of tokens when multiple selections are enabled. */ - renderToken?: (selectedItem: T | string, onRemove: () => void) => any; + renderToken?: (selectedItem: T, props: TypeaheadMenuProps, index: number) => React.ReactNode; /* The selected option(s) displayed in the input. Use this prop if you want to control the component via its parent. */ selected?: T[]; @@ -166,9 +267,13 @@ export interface TypeaheadProps { selectHintOnEnter?: boolean; } -export const Typeahead: React.ClassicComponentClass>; +export type AllTypeaheadOwnAndInjectedProps = TypeaheadProps & TypeaheadContainerProps; +export class Typeahead extends React.Component> { } -export interface AsyncTypeaheadProps extends TypeaheadProps { +/* --------------------------------------------------------------------------- + AsyncTypeahead Props and Component +--------------------------------------------------------------------------- */ +export interface AsyncTypeaheadProps extends TypeaheadProps { /* Delay, in milliseconds, before performing search. */ delay?: number; @@ -179,45 +284,148 @@ export interface AsyncTypeaheadProps extends TypeaheadProps { onSearch: (query: string) => void; /* Message displayed in the menu when there is no user input. */ - promptText?: string; + promptText?: React.ReactNode; /* Message to display in the menu while the request is pending. */ - searchText?: string; + searchText?: React.ReactNode; /* Whether or not the component should cache query results. */ useCache?: boolean; } -export const AsyncTypeahead: React.ClassicComponentClass>; +export class AsyncTypeahead extends React.Component> { } -export interface HighligherProps { - key?: string; - search: string; - optionId?: any; +/* --------------------------------------------------------------------------- + TypeaheadInputSingle & TypeaheadInputMulti Props and Component +--------------------------------------------------------------------------- */ +export interface BaseTypeaheadInputProps extends React.InputHTMLAttributes<'input'> { + type: 'text'; } -export const Highlighter: React.ClassicComponentClass>; +export interface TypeaheadSingleInputWithHocProps extends + Omit>, + InputContainerPropsSingle {} -export interface MenuProps { +export interface TypeaheadMulitInputWithHocProps extends + Omit>, + HintedInputContext, + InputContainerPropsMultiple {} + +export type TypeaheadInputPropKeys = 'bsSize'|'disabled'|'inputProps'|'labelKey'|'multiple'| + 'onBlur'|'onChange'|'onFocus'|'onKeyDown'|'placeholder'|'renderToken'|'selected'; + +export type TypeaheadInputProps = Pick, TypeaheadInputPropKeys>; + +export class TypeaheadInputSingle extends React.Component> { } +export class TypeaheadInputMulti extends React.Component> { } + +/* --------------------------------------------------------------------------- + Highlighter Props and Component +--------------------------------------------------------------------------- */ +export interface HighligherProps { + children: React.ReactNode; + search: string; +} + +export class Highlighter extends React.PureComponent { } + +/* --------------------------------------------------------------------------- + ClearButton Props and Component +--------------------------------------------------------------------------- */ +export interface ClearButtonProps extends React.HTMLAttributes<'button'> { + bsSize?: TypeaheadBsSizes; + label?: string; + onClick: React.HTMLAttributes<'button'>['onClick']; // make onClick requried +} + +export const ClearButton: React.FunctionComponent; + +/* --------------------------------------------------------------------------- + Loader Props and Component +--------------------------------------------------------------------------- */ +export interface LoaderProps { + bsSize: TypeaheadBsSizes; +} + +export const Loader: React.FunctionComponent; + +/* --------------------------------------------------------------------------- + AutosizeInput Props and Component +--------------------------------------------------------------------------- */ +export interface AutosizeInputProps extends Pick, 'className' | 'style'> { + inputClassName?: string; + inputRef?: React.LegacyRef; + inputStyle?: Pick; + style: React.CSSProperties; +} + +export class AutosizeInput extends React.Component { } + +/* --------------------------------------------------------------------------- + Menu Props and Component +--------------------------------------------------------------------------- */ +export interface MenuProps { id: string; className?: string; emptyLabel?: string; - innerRef?: string; + innerRef?: React.LegacyRef; maxHeight?: string; - style?: CSS.Properties; + style?: React.CSSProperties; + text?: string; } -export const Menu: React.ClassicComponentClass>; +export type MenuHeaderProps = Omit, 'className'>; -export interface MenuItemProps { +export class Menu extends React.Component { + static Divider: React.FunctionComponent; + static Header: React.FunctionComponent; +} + +/* --------------------------------------------------------------------------- + TypeaheadMenu Props and Component +--------------------------------------------------------------------------- */ +// prop names that Typeahead provides to TypeaheadMenu +export type TypeaheadMenuPropsPick = 'labelKey' | 'newSelectionPrefix'| 'options' | 'renderMenuItemChildren'; +export interface TypeaheadMenuProps extends MenuProps, Pick, TypeaheadMenuPropsPick> {} +export class TypeaheadMenu extends React.Component> { } + +/* --------------------------------------------------------------------------- + Menu Item Props and Component +--------------------------------------------------------------------------- */ +export interface BaseMenuItemProps extends React.HTMLProps<'li'> { + active?: boolean; +} +export class BaseMenuItem extends React.Component { } + +export interface MenuItemProps extends BaseMenuItemProps { option: T; position: number; label?: string; - active?: boolean; - className?: string; - disabled?: boolean; - onClick?: (e: Event) => any; - onMouseDown?: (e: Event) => any; } -export const MenuItem: React.ClassicComponentClass>; +export class MenuItem extends React.Component> { } + +/* --------------------------------------------------------------------------- + Overlay Props and Component +--------------------------------------------------------------------------- */ +export type OverlayTypeaheadProps = Pick, 'align' | 'dropup' | 'flip' | 'onMenuHide' | 'onMenuShow' | 'onMenuToggle'>; + +export interface OverlayProps extends OverlayTypeaheadProps { + children?: React.ReactNode; + className?: string; + container: HTMLElement; + referenceElement?: HTMLElement; + show?: boolean; +} + +export class Overlay extends React.Component { } + +/* --------------------------------------------------------------------------- + Token Props and Component +--------------------------------------------------------------------------- */ +export interface TokenProps extends React.HTMLProps<'div'> { + active?: boolean; + onRemove?: () => void; // Token does not invoke onRemove with any parameters +} + +export class Token extends React.Component { } diff --git a/types/react-bootstrap-typeahead/package.json b/types/react-bootstrap-typeahead/package.json deleted file mode 100644 index e6696d08e7..0000000000 --- a/types/react-bootstrap-typeahead/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "private": true, - "dependencies": { - "csstype": "^2.2.0" - } -} diff --git a/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx b/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx index c77052a3c6..7e2c3a29a6 100644 --- a/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx +++ b/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx @@ -1,25 +1,78 @@ import * as React from 'react'; -import { Typeahead, Highlighter, Menu, MenuItem } from 'react-bootstrap-typeahead'; +import { ClearButton, Typeahead, Highlighter, Menu, MenuItem, Token } from 'react-bootstrap-typeahead'; -const options = [ - { name: 'Alabama', population: 4780127, capital: 'Montgomery', region: 'South' }, - { name: 'Alaska', population: 710249, capital: 'Juneau', region: 'West' }, - { name: 'Arizona', population: 6392307, capital: 'Phoenix', region: 'West' }, - { name: 'Arkansas', population: 2915958, capital: 'Little Rock', region: 'South' }, - { name: 'California', population: 37254503, capital: 'Sacramento', region: 'West' }, - { name: 'Colorado', population: 5029324, capital: 'Denver', region: 'West' }, +interface State { + capital: string; + name: string; + population: number; + region: string; + setValue: (value: State) => void; +} +interface GroupedStates { + [key: string]: State[]; +} +type StringPropertyNames = { [K in keyof T]: T[K] extends string ? K : never }[keyof T]; +type StateKeysValid = StringPropertyNames; +const options: State[] = [ + { name: 'Alabama', population: 4780127, capital: 'Montgomery', region: 'South', setValue: () => {} }, + { name: 'Alaska', population: 710249, capital: 'Juneau', region: 'West', setValue: () => {} }, + { name: 'Arizona', population: 6392307, capital: 'Phoenix', region: 'West', setValue: () => {} }, + { name: 'Arkansas', population: 2915958, capital: 'Little Rock', region: 'South', setValue: () => {} }, + { name: 'California', population: 37254503, capital: 'Sacramento', region: 'West', setValue: () => {} }, + { name: 'Colorado', population: 5029324, capital: 'Denver', region: 'West', setValue: () => {} }, ]; +const stateNames = options.map(o => o.name); + +const groups: GroupedStates = options.reduce((accum: GroupedStates, option: State) => { + const optKey = option.name.slice(0, 1).toLowerCase(); + if (accum[optKey] !== undefined) { + accum[optKey].push(option); + } else { + accum[optKey] = [option]; + } + return accum; +}, {}); + class BasicExample extends React.Component { state = { multiple: false, }; + genCustomMenu = () => { + const menuItems = Object.keys(groups).reduce((accum, letter) => { + const header = [ + , + + {`States starting with: ${letter.toUpperCase()}`} + {}} /> + , + , + ]; + const states = groups[letter].map((state: State, index: number) => { + return ({state.name}); + }); + return [...accum, ...header, ...states]; + }, [] as JSX.Element[]); + + return menuItems; + } + render() { const { multiple } = this.state; return (

+ + (props.text.indexOf(option) !== -1)} + /> (props.text.indexOf(option) !== -1) } + filterBy={(option, props) => (props.text.indexOf(option.name) !== -1) } placeholder="Choose a state..." /> (text.indexOf(option) !== -1) } + filterBy={(option, {text}) => (text.indexOf(option.name) !== -1) } placeholder="Choose a state..." /> - + {option.name} {index} } @@ -69,6 +122,23 @@ class BasicExample extends React.Component { ))} + { + return console.log(props.text)}> + {selectedItem.name} {}} /> + ; + }} + > + {...this.genCustomMenu()} +
); } diff --git a/types/react-grid-layout/index.d.ts b/types/react-grid-layout/index.d.ts index 91c8ad1f9c..c643e976c3 100644 --- a/types/react-grid-layout/index.d.ts +++ b/types/react-grid-layout/index.d.ts @@ -4,6 +4,7 @@ // Ali Taheri , // Zheyang Song , // Andrew Hathaway +// Manav Mishra // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -12,11 +13,11 @@ import * as React from "react"; export as namespace ReactGridLayout; export = ReactGridLayout; -declare class ReactGridLayout extends React.Component { } +declare class ReactGridLayout extends React.Component< + ReactGridLayout.ReactGridLayoutProps +> {} declare namespace ReactGridLayout { - type Breakpoints = 'lg' | 'md' | 'sm' | 'xs' | 'xxs'; - interface Layout { /** * A string corresponding to the component key. @@ -85,9 +86,9 @@ declare namespace ReactGridLayout { isResizable?: boolean; } - type Layouts = { - [P in Breakpoints]?: Layout[]; - }; + interface Layouts { + [P: string]: Layout[]; + } type ItemCallback = ( layout: Layout[], @@ -263,12 +264,12 @@ declare namespace ReactGridLayout { * * Breakpoint names are arbitrary but must match in the cols and layouts objects. */ - breakpoints?: {[P in Breakpoints]: number }; + breakpoints?: { [P: string]: number }; /** * Number of cols. This is a breakpoint -> cols map, e.g. `{lg: 12, md: 10, ...}`. */ - cols?: {[P in Breakpoints]: number }; + cols?: { [P: string]: number }; /** * layouts is an object mapping breakpoints to layouts. @@ -298,7 +299,7 @@ declare namespace ReactGridLayout { ): void; } - class Responsive extends React.Component { } + class Responsive extends React.Component {} interface WidthProviderProps { /** diff --git a/types/react-grid-layout/react-grid-layout-tests.tsx b/types/react-grid-layout/react-grid-layout-tests.tsx index 78ecf594ef..70c88bae0d 100644 --- a/types/react-grid-layout/react-grid-layout-tests.tsx +++ b/types/react-grid-layout/react-grid-layout-tests.tsx @@ -54,6 +54,31 @@ class ResponsiveGridTest extends React.Component { } } +class ResponsiveGridTestWithCustomBreakpoints extends React.Component { + render() { + const layouts = { + lg: [ + { i: '1', x: 0, y: 0, w: 1, h: 2, static: true }, + { i: '2', x: 1, y: 0, w: 3, h: 2, minW: 2, maxW: 4 }, + { i: '3', x: 4, y: 0, w: 1, h: 2 } + ] + }; + + return ( + +
a
+
b
+
c
+
+ ); + } +} + class ResponsiveGridWidthProviderTest extends React.Component { render() { return ( diff --git a/types/react-is/react-is-tests.tsx b/types/react-is/react-is-tests.tsx index afbf0aabb6..d41b2a828b 100644 --- a/types/react-is/react-is-tests.tsx +++ b/types/react-is/react-is-tests.tsx @@ -6,7 +6,7 @@ import * as ReactIs from 'react-is'; // Determining if a Component is Valid interface CompProps { - forwardedRef: React.Ref | null; + forwardedRef: React.Ref; children?: React.ReactNode; } diff --git a/types/react-json-tree/index.d.ts b/types/react-json-tree/index.d.ts index d0ab7cab62..c57cdd3d51 100644 --- a/types/react-json-tree/index.d.ts +++ b/types/react-json-tree/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for react-json-tree v0.6.5 +// Type definitions for react-json-tree 0.6 // Project: https://github.com/alexkuz/react-json-tree/ // Definitions by: Grant Nestor +// Zain Afzal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -18,7 +19,7 @@ export interface JSONTreeProps extends Props { sortObjectKeys?: Function | boolean; shouldExpandNode?: (keyPath: (string | number)[], data: [any] | {}, level: number) => boolean; getItemString?: (type: string, data: [any] | {}, itemType: string, itemString: string) => JSX.Element; - labelRenderer?: (raw: [string, string]) => JSX.Element; + labelRenderer?: (keyPath: string[], nodeType?: string, expanded?: boolean, expandable?: boolean) => JSX.Element; valueRenderer?: (displayValue: string|number, rawValue?: string|number|boolean|null, ...keyPath: (string|number)[]) => JSX.Element; postprocessValue?: (raw: string) => JSX.Element; isCustomNode?: () => boolean; diff --git a/types/react-json-tree/tslint.json b/types/react-json-tree/tslint.json index e3610fefae..92d14c6344 100644 --- a/types/react-json-tree/tslint.json +++ b/types/react-json-tree/tslint.json @@ -7,7 +7,6 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, diff --git a/types/react-jss/index.d.ts b/types/react-jss/index.d.ts index 7656897a08..c2ee0a008a 100644 --- a/types/react-jss/index.d.ts +++ b/types/react-jss/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for react-jss 8.6 // Project: https://github.com/cssinjs/react-jss#readme // Definitions by: Sebastian Silbermann +// James Lawrence // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { createGenerateClassName, JSS, SheetsRegistry } from "jss"; diff --git a/types/react-jss/lib/injectSheet.d.ts b/types/react-jss/lib/injectSheet.d.ts index fd66af5c38..ef6bdb3dbb 100644 --- a/types/react-jss/lib/injectSheet.d.ts +++ b/types/react-jss/lib/injectSheet.d.ts @@ -53,26 +53,33 @@ export type PropsOf = C extends new (props: infer P) => React.Component */ export type PropInjector = < C extends React.ComponentType, InjectedProps>> ->( + >( component: C ) => React.ComponentType< Omit>, keyof InjectedProps> & - AdditionalProps ->; + AdditionalProps + >; -export interface CSSProperties extends CSS.Properties { +// Allow functions that take the properties of the component and return a CSS value +export type DynamicCSSRule = { + [K in keyof CSS.Properties]: + | CSS.Properties[K] + | ((props: Props) => CSS.Properties[K]) +}[keyof CSS.Properties]; + +export interface CSSProperties { // Allow pseudo selectors and media queries [k: string]: - | CSS.Properties[keyof CSS.Properties] - | CSSProperties; + | DynamicCSSRule + | CSSProperties; } -export type Styles = Record< +export type Styles = Record< ClassKey, - CSSProperties ->; -export type StyleCreator = ( + CSSProperties + >; +export type StyleCreator = ( theme: T -) => Styles; +) => Styles; export interface Theming { channel: string; @@ -89,15 +96,16 @@ export interface InjectOptions extends CreateStyleSheetOptions { export type ClassNameMap = Record; export type WithSheet< S extends string | Styles | StyleCreator, - GivenTheme = undefined -> = { + GivenTheme = undefined, + Props = {} + > = { classes: ClassNameMap< S extends string ? S - : S extends StyleCreator - ? C - : S extends Styles ? C : never - >; + : S extends StyleCreator + ? C + : S extends Styles ? C : never + >; } & WithTheme ? T : GivenTheme>; export interface WithTheme { @@ -110,7 +118,7 @@ export interface StyledComponentProps { innerRef?: React.Ref | React.RefObject; } -export default function injectSheet( - stylesOrCreator: Styles | StyleCreator, +export default function injectSheet( + stylesOrCreator: Styles | StyleCreator, options?: InjectOptions -): PropInjector, StyledComponentProps>; +): PropInjector, StyledComponentProps>; diff --git a/types/react-jss/react-jss-tests.tsx b/types/react-jss/react-jss-tests.tsx index 803170bb99..0ba2ee3d8b 100644 --- a/types/react-jss/react-jss-tests.tsx +++ b/types/react-jss/react-jss-tests.tsx @@ -17,42 +17,44 @@ interface MyTheme { /** * helper function to counter typescripts type widening */ -function createStyles(styles: Styles): Styles { - return styles; +// tslint:disable-next-line:no-unnecessary-generics +function createStyles(styles: Styles): Styles { + return styles as Styles; } -const styles = (theme: MyTheme) => - createStyles({ - myButton: { - color: theme.color.primary, - margin: 1, - "& span": { - fontWeight: "revert" - } - }, - myLabel: { - fontStyle: "italic" - } - }); - -interface ButtonProps extends WithSheet { +interface ButtonProps { label: string; + active?: boolean; } -const Button: React.SFC = ({ classes, children }) => { +const styles = (theme: MyTheme) => createStyles({ + myButton: { + color: (props: ButtonProps) => props.active ? 'red' : theme.color.primary, + margin: 1, + "& span": { + fontWeight: "revert" + } + }, + myLabel: { + fontStyle: "italic" + } +}); +const Button: React.SFC> = ({active, classes, children}) => { return ( - + <> + + ); }; const ManuallyStyles = () => { return (