diff --git a/notNeededPackages.json b/notNeededPackages.json index 1521fd7426..801a80b693 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -396,6 +396,12 @@ "sourceRepoURL": "https://github.com/date-fns/date-fns", "asOfVersion": "2.6.0" }, + { + "libraryName": "dd-trace", + "typingsPackageName": "dd-trace", + "sourceRepoURL": "https://github.com/DataDog/dd-trace-js", + "asOfVersion": "0.9.0" + }, { "libraryName": "decimal.js", "typingsPackageName": "decimal.js", @@ -414,6 +420,12 @@ "sourceRepoURL": "https://github.com/sindresorhus/delay", "asOfVersion": "3.1.0" }, + { + "libraryName": "detect-browser", + "typingsPackageName": "detect-browser", + "sourceRepoURL": "https://github.com/DamonOehlman/detect-browser", + "asOfVersion": "4.0.0" + }, { "libraryName": "DevExtreme", "typingsPackageName": "devextreme", @@ -730,7 +742,7 @@ "libraryName": "i18next-browser-languagedetector", "typingsPackageName": "i18next-browser-languagedetector", "sourceRepoURL": "https://github.com/i18next/i18next-browser-languagedetector", - "asOfVersion": "2.0.2" + "asOfVersion": "3.0.0" }, { "libraryName": "i18next-xhr-backend", @@ -768,6 +780,12 @@ "sourceRepoURL": "https://github.com/taye/interact.js", "asOfVersion": "1.3.0" }, + { + "libraryName": "internal-ip", + "typingsPackageName": "internal-ip", + "sourceRepoURL": "https://github.com/sindresorhus/internal-ip", + "asOfVersion": "4.1.0" + }, { "libraryName": "inversify", "typingsPackageName": "inversify", @@ -1122,11 +1140,23 @@ "sourceRepoURL": "http://onsen.io", "asOfVersion": "2.0.0" }, + { + "libraryName": "p-map", + "typingsPackageName": "p-map", + "sourceRepoURL": "https://github.com/sindresorhus/p-map", + "asOfVersion": "2.0.0" + }, + { + "libraryName": "p-pipe", + "typingsPackageName": "p-pipe", + "sourceRepoURL": "https://github.com/sindresorhus/p-pipe", + "asOfVersion": "2.0.1" + }, { "libraryName": "p-throttle", "typingsPackageName": "p-throttle", "sourceRepoURL": "https://github.com/sindresorhus/p-throttle", - "asOfVersion": "2.0.0" + "asOfVersion": "2.1.0" }, { "libraryName": "param-case", @@ -1776,6 +1806,12 @@ "sourceRepoURL": "https://github.com/vuejs/vue-router", "asOfVersion": "2.0.0" }, + { + "libraryName": "wait-for-localhost", + "typingsPackageName": "wait-for-localhost", + "sourceRepoURL": "https://github.com/sindresorhus/wait-for-localhost", + "asOfVersion": "3.1.0" + }, { "libraryName": "webcola", "typingsPackageName": "webcola", diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 6b012d5677..444e043210 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -512,5 +512,10 @@ declare module 'angular' { } type IStickyService = (scope: IScope, element: JQuery, elementClone?: JQuery) => void; + + interface IInteractionService { + getLastInteractionType(): string|null; + isUserInvoked(checkDelay?: number): boolean; + } } } diff --git a/types/argparse/argparse-tests.ts b/types/argparse/argparse-tests.ts index ed714ada95..942e2bb4f2 100644 --- a/types/argparse/argparse-tests.ts +++ b/types/argparse/argparse-tests.ts @@ -1,6 +1,12 @@ // near copy of each of the tests from https://github.com/nodeca/argparse/tree/master/examples -import { ArgumentParser, RawDescriptionHelpFormatter } from 'argparse'; +import { + ArgumentParser, + RawDescriptionHelpFormatter, + Action, + ActionConstructorOptions, + Namespace, +} from 'argparse'; let args: any; const simpleExample = new ArgumentParser({ @@ -276,3 +282,26 @@ group.addArgument(['--bar'], { help: 'bar help' }); formatterExample.printHelp(); + +class CustomAction1 extends Action { + constructor(options: ActionConstructorOptions) { + super(options); + } + call(parser: ArgumentParser, namespace: Namespace, values: string | string[], optionString: string | null) { + console.log('custom action 1'); + } +} + +class CustomAction2 extends Action { + call(parser: ArgumentParser, namespace: Namespace, values: string | string[], optionString: string | null) { + console.log('custom action 2'); + } +} + +const customActionExample = new ArgumentParser({ addHelp: false }); +customActionExample.addArgument('--abc', { + action: CustomAction1, +}); +customActionExample.addArgument('--def', { + action: CustomAction2, +}); diff --git a/types/argparse/index.d.ts b/types/argparse/index.d.ts index 3330055b1f..a229b6bc49 100644 --- a/types/argparse/index.d.ts +++ b/types/argparse/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Andrew Schurman // Tomasz Łaziuk // Sebastian Silbermann +// Kannan Goundan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -79,13 +80,24 @@ export interface ArgumentGroupOptions { description?: string; } +export abstract class Action { + protected dest: string; + constructor(options: ActionConstructorOptions); + abstract call(parser: ArgumentParser, namespace: Namespace, values: string | string[], optionString: string | null): void; +} + +// Passed to the Action constructor. Subclasses are just expected to relay this to +// the super() constructor, so using an "opaque type" pattern is probably fine. +// Someone may want to fill this out in the future. +export type ActionConstructorOptions = number & {_: 'ActionConstructorOptions'}; + export class HelpFormatter { } export class ArgumentDefaultsHelpFormatter { } export class RawDescriptionHelpFormatter { } export class RawTextHelpFormatter { } export interface ArgumentOptions { - action?: string; + action?: string | { new(options: ActionConstructorOptions): Action }; optionStrings?: string[]; dest?: string; nargs?: string | number; diff --git a/types/argparse/tsconfig.json b/types/argparse/tsconfig.json index 49e7b03ca8..9248f1d078 100644 --- a/types/argparse/tsconfig.json +++ b/types/argparse/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "argparse-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/assets-webpack-plugin/assets-webpack-plugin-tests.ts b/types/assets-webpack-plugin/assets-webpack-plugin-tests.ts index b02c707d81..838ac825ea 100644 --- a/types/assets-webpack-plugin/assets-webpack-plugin-tests.ts +++ b/types/assets-webpack-plugin/assets-webpack-plugin-tests.ts @@ -8,15 +8,21 @@ const config: webpack.Configuration = { filename: 'assets.json' }), new AssetsPlugin({ + entrypoints: true, filename: 'assets.json', fullPath: false, + fileTypes: ['css'], includeManifest: true, + includeAllFileTypes: false, + keepInMemory: true, + manifestFirst: true, path: '/foo/bar', prettyPrint: true, processOutput: (assets) => ( 'window.assets = ' + JSON.stringify(assets) ), update: true, + useCompilerPath: true, metadata: { meta: 'data' }, diff --git a/types/assets-webpack-plugin/index.d.ts b/types/assets-webpack-plugin/index.d.ts index 63563d6298..397002add3 100644 --- a/types/assets-webpack-plugin/index.d.ts +++ b/types/assets-webpack-plugin/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for assets-webpack-plugin 3.5 +// Type definitions for assets-webpack-plugin 3.9 // Project: https://github.com/ztoben/assets-webpack-plugin // Definitions by: Michael Strobel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -16,18 +16,36 @@ declare namespace AssetsWebpackPlugin { type ProcessOutputFn = (assets: Assets) => string; interface Options { + /** + * If the "entrypoints" option is given, the output will be limited to the entrypoints and the chunks associated with them. + * false by default + */ + entrypoints?: boolean; + /** * Name for the created json file. * "webpack-assets.json" by default */ filename?: string; + /** + * When set and "includeAllFileTypes" is set false, only assets matching these types will be included in the assets file. + * ['js', 'css'] by default + */ + fileTypes?: string[]; + /** * If false the output will not include the full path of the generated file. * true by default */ fullPath?: boolean; + /** + * When set false, falls back to the "fileTypes" option array to decide which file types to include in the assets file. + * true by default + */ + includeAllFileTypes?: boolean; + /** * Inserts the manifest javascript as a text property in your assets. * Accepts the name of your manifest chunk. @@ -38,6 +56,19 @@ declare namespace AssetsWebpackPlugin { */ includeManifest?: boolean; + /** + * When set the assets file will only be generated in memory while running webpack-dev-server and not written to disk. + * false by default + */ + keepInMemory?: boolean; + + /** + * Orders the assets output so that manifest is the first entry. + * This is useful for cases where script tags are generated from the assets json output, and order of import is important. + * false by default + */ + manifestFirst?: boolean; + /** * Inject metadata into the output file. All values will be injected into the key "metadata" */ @@ -66,6 +97,12 @@ declare namespace AssetsWebpackPlugin { * false by default */ update?: boolean; + + /** + * Will override the path to use the compiler output path set in your webpack config. + * false by default + */ + useCompilerPath?: boolean; } } diff --git a/types/aws-iot-device-sdk/aws-iot-device-sdk-tests.ts b/types/aws-iot-device-sdk/aws-iot-device-sdk-tests.ts index 66655f8dd3..89eff9a8c6 100644 --- a/types/aws-iot-device-sdk/aws-iot-device-sdk-tests.ts +++ b/types/aws-iot-device-sdk/aws-iot-device-sdk-tests.ts @@ -101,3 +101,50 @@ const thingShadows = new awsIot.thingShadow({ thingShadows.on("timeout", function(thingName: string, clientToken: string) { }); + +const jobs = new awsIot.jobs({ + keyPath: "", + certPath: "", + caPath: "", + clientId: "", + region: "", + baseReconnectTimeMs: 1000, + protocol: "wss", + port: 443, + host: "", + debug: false +}); + +jobs.subscribeToJobs("thingname", "operationname", (err, job) => { + console.error("Error", err); + if (err || !job) { + return; + } + console.log("job id", job.id); + console.log("job info", job.document); + console.log("job op", job.operation); + console.log("job status", job.status); + console.log("job status details", job.status.statusDetails); + console.log( + "job status details progress", + job.status.statusDetails.progress + ); + + job.inProgress({ progress: "1" }, err => + console.error("Job progress error", err) + ); + job.failed({ progress: "2" }, err => + console.error("Job failed error", err) + ); + job.succeeded({ progress: "3" }, err => + console.error("Job failed error", err) + ); +}); + +jobs.startJobNotifications("thingname", err => + console.error("Start job notification error", err) +); + +jobs.unsubscribeFromJobs("thingname", "operationame", err => + console.error("Unsubscribe from jobs error", err) +); diff --git a/types/aws-iot-device-sdk/index.d.ts b/types/aws-iot-device-sdk/index.d.ts index f2bcab818c..8b52a68bfc 100644 --- a/types/aws-iot-device-sdk/index.d.ts +++ b/types/aws-iot-device-sdk/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for aws-iot-device-sdk 2.1.0 +// Type definitions for aws-iot-device-sdk 2.2.0 // Project: https://github.com/aws/aws-iot-device-sdk-js // Definitions by: Markus Olsson // Margus Lamp @@ -391,3 +391,115 @@ export class thingShadow extends NodeJS.EventEmitter { /** Emitted when a different client"s update or delete operation is accepted on the shadow. */ on(event: "foreignStateChange", listener: (thingName: string, operation: "update" | "delete", stateObject: any) => void): this; } + +export interface statusDetails { + progress: string; +} + +export interface jobStatus { + status: string; + statusDetails: statusDetails; +} + +export interface jobDocument { + [key: string]: any +} + +export interface job { + /** Object that contains job execution information and functions for updating job execution status. */ + + /** Returns the job id. */ + id: string; + + /** + * The JSON document describing details of the job to be executed eg. + * { + * "operation": "install", + * "otherProperty": "value", + * ... + * } + */ + document: jobDocument; + + /** + * Returns the job operation from the job document. Eg. 'install', 'reboot', etc. + */ + operation: string; + + /** + * Returns the current job status according to AWS Orchestra. + */ + status: jobStatus; + + /** + * Update the status of the job execution to be IN_PROGRESS for the thing associated with the job. + * + * @param statusDetails - optional document describing the status details of the in progress job + * @param callback - function(err) optional callback for when the operation completes, err is null if no error occurred + */ + inProgress(statusDetails?: statusDetails, callback?: (err: Error) => void): void; + + /** + * Update the status of the job execution to be FAILED for the thing associated with the job. + * + * @param statusDetails - optional document describing the status details of the in progress job e.g. + * @param callback - function(err) optional callback for when the operation completes, err is null if no error occurred + */ + failed(statusDetails?: statusDetails, callback?: (err: Error) => void): void; + + /** + * Update the status of the job execution to be SUCCESS for the thing associated with the job. + * + * @param statusDetails - optional document describing the status details of the in progress job e.g. + * @param callback - function(err) optional callback for when the operation completes, err is null if no error occurred + */ + succeeded(statusDetails?: statusDetails, callback?: (err: Error) => void): void; +} + +export class jobs extends device { + /** + * The `jobs` class wraps an instance of the `device` class with additional functionality to + * handle job execution management through the AWS IoT Jobs platform. Arguments in `deviceOptions` + * are the same as those in the device class and the `jobs` class supports all of the + * same events and functions as the `device` class. + */ + constructor(options?: DeviceOptions); + + /** + * Subscribes to job execution notifications for the thing named `thingName`. If + * `operationName` is specified then the callback will only be called when a job + * ready for execution contains a property called `operation` in its job document with + * a value matching `operationName`. If `operationName` is omitted then the callback + * will be called for every job ready for execution that does not match another + * `subscribeToJobs` subscription. + * + * @param thingName - name of the Thing to receive job execution notifications + * @param operationName - optionally filter job execution notifications to jobs with a value + * for the `operation` property that matches `operationName + * @param callback - function (err, job) callback for when a job execution is ready for processing or an error occurs + * - `err` a subscription error or an error that occurs when client is disconnecting + * - `job` an object that contains job execution information and functions for updating job execution status. + */ + subscribeToJobs(thingName: string, operationName: string, callback?: (err: Error, job: job) => void): void; + + /** + * Causes any existing queued job executions for the given thing to be published + * to the appropriate subscribeToJobs handler. Only needs to be called once per thing. + * + * @param thingName - name of the Thing to cancel job execution notifications for + * @param callback - function (err) callback for when the startJobNotifications operation completes + */ + startJobNotifications(thingName: string, callback: (error: Error) => void): mqtt.Client; + + /** + * Unsubscribes from job execution notifications for the thing named `thingName` having + * operations with a value of the given `operationName`. If `operationName` is omitted then + * the default handler for the thing with the given name is unsubscribed. + * + * @param thingName - name of the Thing to cancel job execution notifications for + * @param operationName - optional name of previously subscribed operation names + * @param callback - function (err) callback for when the unsubscribe operation completes + */ + unsubscribeFromJobs(thingName: string, operationName: string, callback: (err: Error) => void): void; + +} diff --git a/types/babel-types/babel-types-tests.ts b/types/babel-types/babel-types-tests.ts index 8ffb1b32de..921608924c 100644 --- a/types/babel-types/babel-types-tests.ts +++ b/types/babel-types/babel-types-tests.ts @@ -53,6 +53,12 @@ traverse(ast, { } }); +// Node type checks +t.isIdentifier(t.identifier("id")); +t.isIdentifier(exp); +t.isIdentifier(null); +t.isIdentifier(undefined); + // TypeScript Types // TODO: Test all variants of these functions' signatures diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index d37cdf0a76..f0d781a7ed 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -1514,246 +1514,246 @@ export function TSUndefinedKeyword(): TSUndefinedKeyword; export function TSUnionType(types: TSType[]): TSUnionType; export function TSVoidKeyword(): TSVoidKeyword; -export function isArrayExpression(node: object, opts?: object): node is ArrayExpression; -export function isAssignmentExpression(node: object, opts?: object): node is AssignmentExpression; -export function isBinaryExpression(node: object, opts?: object): node is BinaryExpression; -export function isDirective(node: object, opts?: object): node is Directive; -export function isDirectiveLiteral(node: object, opts?: object): node is DirectiveLiteral; -export function isBlockStatement(node: object, opts?: object): node is BlockStatement; -export function isBreakStatement(node: object, opts?: object): node is BreakStatement; -export function isCallExpression(node: object, opts?: object): node is CallExpression; -export function isCatchClause(node: object, opts?: object): node is CatchClause; -export function isConditionalExpression(node: object, opts?: object): node is ConditionalExpression; -export function isContinueStatement(node: object, opts?: object): node is ContinueStatement; -export function isDebuggerStatement(node: object, opts?: object): node is DebuggerStatement; -export function isDoWhileStatement(node: object, opts?: object): node is DoWhileStatement; -export function isEmptyStatement(node: object, opts?: object): node is EmptyStatement; -export function isExpressionStatement(node: object, opts?: object): node is ExpressionStatement; -export function isFile(node: object, opts?: object): node is File; -export function isForInStatement(node: object, opts?: object): node is ForInStatement; -export function isForStatement(node: object, opts?: object): node is ForStatement; -export function isFunctionDeclaration(node: object, opts?: object): node is FunctionDeclaration; -export function isFunctionExpression(node: object, opts?: object): node is FunctionExpression; -export function isIdentifier(node: object, opts?: object): node is Identifier; -export function isIfStatement(node: object, opts?: object): node is IfStatement; -export function isLabeledStatement(node: object, opts?: object): node is LabeledStatement; -export function isStringLiteral(node: object, opts?: object): node is StringLiteral; -export function isNumericLiteral(node: object, opts?: object): node is NumericLiteral; -export function isNullLiteral(node: object, opts?: object): node is NullLiteral; -export function isBooleanLiteral(node: object, opts?: object): node is BooleanLiteral; -export function isRegExpLiteral(node: object, opts?: object): node is RegExpLiteral; -export function isLogicalExpression(node: object, opts?: object): node is LogicalExpression; -export function isMemberExpression(node: object, opts?: object): node is MemberExpression; -export function isNewExpression(node: object, opts?: object): node is NewExpression; -export function isProgram(node: object, opts?: object): node is Program; -export function isObjectExpression(node: object, opts?: object): node is ObjectExpression; -export function isObjectMethod(node: object, opts?: object): node is ObjectMethod; -export function isObjectProperty(node: object, opts?: object): node is ObjectProperty; -export function isRestElement(node: object, opts?: object): node is RestElement; -export function isReturnStatement(node: object, opts?: object): node is ReturnStatement; -export function isSequenceExpression(node: object, opts?: object): node is SequenceExpression; -export function isSwitchCase(node: object, opts?: object): node is SwitchCase; -export function isSwitchStatement(node: object, opts?: object): node is SwitchStatement; -export function isThisExpression(node: object, opts?: object): node is ThisExpression; -export function isThrowStatement(node: object, opts?: object): node is ThrowStatement; -export function isTryStatement(node: object, opts?: object): node is TryStatement; -export function isUnaryExpression(node: object, opts?: object): node is UnaryExpression; -export function isUpdateExpression(node: object, opts?: object): node is UpdateExpression; -export function isVariableDeclaration(node: object, opts?: object): node is VariableDeclaration; -export function isVariableDeclarator(node: object, opts?: object): node is VariableDeclarator; -export function isWhileStatement(node: object, opts?: object): node is WhileStatement; -export function isWithStatement(node: object, opts?: object): node is WithStatement; -export function isAssignmentPattern(node: object, opts?: object): node is AssignmentPattern; -export function isArrayPattern(node: object, opts?: object): node is ArrayPattern; -export function isArrowFunctionExpression(node: object, opts?: object): node is ArrowFunctionExpression; -export function isClassBody(node: object, opts?: object): node is ClassBody; -export function isClassDeclaration(node: object, opts?: object): node is ClassDeclaration; -export function isClassExpression(node: object, opts?: object): node is ClassExpression; -export function isExportAllDeclaration(node: object, opts?: object): node is ExportAllDeclaration; -export function isExportDefaultDeclaration(node: object, opts?: object): node is ExportDefaultDeclaration; -export function isExportNamedDeclaration(node: object, opts?: object): node is ExportNamedDeclaration; -export function isExportSpecifier(node: object, opts?: object): node is ExportSpecifier; -export function isForOfStatement(node: object, opts?: object): node is ForOfStatement; -export function isImportDeclaration(node: object, opts?: object): node is ImportDeclaration; -export function isImportDefaultSpecifier(node: object, opts?: object): node is ImportDefaultSpecifier; -export function isImportNamespaceSpecifier(node: object, opts?: object): node is ImportNamespaceSpecifier; -export function isImportSpecifier(node: object, opts?: object): node is ImportSpecifier; -export function isMetaProperty(node: object, opts?: object): node is MetaProperty; -export function isClassMethod(node: object, opts?: object): node is ClassMethod; -export function isObjectPattern(node: object, opts?: object): node is ObjectPattern; -export function isSpreadElement(node: object, opts?: object): node is SpreadElement; -export function isSuper(node: object, opts?: object): node is Super; -export function isTaggedTemplateExpression(node: object, opts?: object): node is TaggedTemplateExpression; -export function isTemplateElement(node: object, opts?: object): node is TemplateElement; -export function isTemplateLiteral(node: object, opts?: object): node is TemplateLiteral; -export function isYieldExpression(node: object, opts?: object): node is YieldExpression; -export function isAnyTypeAnnotation(node: object, opts?: object): node is AnyTypeAnnotation; -export function isArrayTypeAnnotation(node: object, opts?: object): node is ArrayTypeAnnotation; -export function isBooleanTypeAnnotation(node: object, opts?: object): node is BooleanTypeAnnotation; -export function isBooleanLiteralTypeAnnotation(node: object, opts?: object): node is BooleanLiteralTypeAnnotation; -export function isNullLiteralTypeAnnotation(node: object, opts?: object): node is NullLiteralTypeAnnotation; -export function isClassImplements(node: object, opts?: object): node is ClassImplements; -export function isClassProperty(node: object, opts?: object): node is ClassProperty; -export function isDeclareClass(node: object, opts?: object): node is DeclareClass; -export function isDeclareFunction(node: object, opts?: object): node is DeclareFunction; -export function isDeclareInterface(node: object, opts?: object): node is DeclareInterface; -export function isDeclareModule(node: object, opts?: object): node is DeclareModule; -export function isDeclareTypeAlias(node: object, opts?: object): node is DeclareTypeAlias; -export function isDeclareVariable(node: object, opts?: object): node is DeclareVariable; -export function isExistentialTypeParam(node: object, opts?: object): node is ExistentialTypeParam; -export function isFunctionTypeAnnotation(node: object, opts?: object): node is FunctionTypeAnnotation; -export function isFunctionTypeParam(node: object, opts?: object): node is FunctionTypeParam; -export function isGenericTypeAnnotation(node: object, opts?: object): node is GenericTypeAnnotation; -export function isInterfaceExtends(node: object, opts?: object): node is InterfaceExtends; -export function isInterfaceDeclaration(node: object, opts?: object): node is InterfaceDeclaration; -export function isIntersectionTypeAnnotation(node: object, opts?: object): node is IntersectionTypeAnnotation; -export function isMixedTypeAnnotation(node: object, opts?: object): node is MixedTypeAnnotation; -export function isNullableTypeAnnotation(node: object, opts?: object): node is NullableTypeAnnotation; -export function isNumericLiteralTypeAnnotation(node: object, opts?: object): node is NumericLiteralTypeAnnotation; -export function isNumberTypeAnnotation(node: object, opts?: object): node is NumberTypeAnnotation; -export function isStringLiteralTypeAnnotation(node: object, opts?: object): node is StringLiteralTypeAnnotation; -export function isStringTypeAnnotation(node: object, opts?: object): node is StringTypeAnnotation; -export function isThisTypeAnnotation(node: object, opts?: object): node is ThisTypeAnnotation; -export function isTupleTypeAnnotation(node: object, opts?: object): node is TupleTypeAnnotation; -export function isTypeofTypeAnnotation(node: object, opts?: object): node is TypeofTypeAnnotation; -export function isTypeAlias(node: object, opts?: object): node is TypeAlias; -export function isTypeAnnotation(node: object, opts?: object): node is TypeAnnotation; -export function isTypeCastExpression(node: object, opts?: object): node is TypeCastExpression; -export function isTypeParameter(node: object, opts?: object): node is TypeParameter; -export function isTypeParameterDeclaration(node: object, opts?: object): node is TypeParameterDeclaration; -export function isTypeParameterInstantiation(node: object, opts?: object): node is TypeParameterInstantiation; -export function isObjectTypeAnnotation(node: object, opts?: object): node is ObjectTypeAnnotation; -export function isObjectTypeCallProperty(node: object, opts?: object): node is ObjectTypeCallProperty; -export function isObjectTypeIndexer(node: object, opts?: object): node is ObjectTypeIndexer; -export function isObjectTypeProperty(node: object, opts?: object): node is ObjectTypeProperty; -export function isQualifiedTypeIdentifier(node: object, opts?: object): node is QualifiedTypeIdentifier; -export function isUnionTypeAnnotation(node: object, opts?: object): node is UnionTypeAnnotation; -export function isVoidTypeAnnotation(node: object, opts?: object): node is VoidTypeAnnotation; -export function isJSXAttribute(node: object, opts?: object): node is JSXAttribute; -export function isJSXClosingElement(node: object, opts?: object): node is JSXClosingElement; -export function isJSXElement(node: object, opts?: object): node is JSXElement; -export function isJSXEmptyExpression(node: object, opts?: object): node is JSXEmptyExpression; -export function isJSXExpressionContainer(node: object, opts?: object): node is JSXExpressionContainer; -export function isJSXIdentifier(node: object, opts?: object): node is JSXIdentifier; -export function isJSXMemberExpression(node: object, opts?: object): node is JSXMemberExpression; -export function isJSXNamespacedName(node: object, opts?: object): node is JSXNamespacedName; -export function isJSXOpeningElement(node: object, opts?: object): node is JSXOpeningElement; -export function isJSXSpreadAttribute(node: object, opts?: object): node is JSXSpreadAttribute; -export function isJSXText(node: object, opts?: object): node is JSXText; -export function isNoop(node: object, opts?: object): node is Noop; -export function isParenthesizedExpression(node: object, opts?: object): node is ParenthesizedExpression; -export function isAwaitExpression(node: object, opts?: object): node is AwaitExpression; -export function isBindExpression(node: object, opts?: object): node is BindExpression; -export function isDecorator(node: object, opts?: object): node is Decorator; -export function isDoExpression(node: object, opts?: object): node is DoExpression; -export function isExportDefaultSpecifier(node: object, opts?: object): node is ExportDefaultSpecifier; -export function isExportNamespaceSpecifier(node: object, opts?: object): node is ExportNamespaceSpecifier; -export function isRestProperty(node: object, opts?: object): node is RestProperty; -export function isSpreadProperty(node: object, opts?: object): node is SpreadProperty; -export function isExpression(node: object, opts?: object): node is Expression; -export function isBinary(node: object, opts?: object): node is Binary; -export function isScopable(node: object, opts?: object): node is Scopable; -export function isBlockParent(node: object, opts?: object): node is BlockParent; -export function isBlock(node: object, opts?: object): node is Block; -export function isStatement(node: object, opts?: object): node is Statement; -export function isTerminatorless(node: object, opts?: object): node is Terminatorless; -export function isCompletionStatement(node: object, opts?: object): node is CompletionStatement; -export function isConditional(node: object, opts?: object): node is Conditional; -export function isLoop(node: object, opts?: object): node is Loop; -export function isWhile(node: object, opts?: object): node is While; -export function isExpressionWrapper(node: object, opts?: object): node is ExpressionWrapper; -export function isFor(node: object, opts?: object): node is For; -export function isForXStatement(node: object, opts?: object): node is ForXStatement; +export function isArrayExpression(node: object | null | undefined, opts?: object): node is ArrayExpression; +export function isAssignmentExpression(node: object | null | undefined, opts?: object): node is AssignmentExpression; +export function isBinaryExpression(node: object | null | undefined, opts?: object): node is BinaryExpression; +export function isDirective(node: object | null | undefined, opts?: object): node is Directive; +export function isDirectiveLiteral(node: object | null | undefined, opts?: object): node is DirectiveLiteral; +export function isBlockStatement(node: object | null | undefined, opts?: object): node is BlockStatement; +export function isBreakStatement(node: object | null | undefined, opts?: object): node is BreakStatement; +export function isCallExpression(node: object | null | undefined, opts?: object): node is CallExpression; +export function isCatchClause(node: object | null | undefined, opts?: object): node is CatchClause; +export function isConditionalExpression(node: object | null | undefined, opts?: object): node is ConditionalExpression; +export function isContinueStatement(node: object | null | undefined, opts?: object): node is ContinueStatement; +export function isDebuggerStatement(node: object | null | undefined, opts?: object): node is DebuggerStatement; +export function isDoWhileStatement(node: object | null | undefined, opts?: object): node is DoWhileStatement; +export function isEmptyStatement(node: object | null | undefined, opts?: object): node is EmptyStatement; +export function isExpressionStatement(node: object | null | undefined, opts?: object): node is ExpressionStatement; +export function isFile(node: object | null | undefined, opts?: object): node is File; +export function isForInStatement(node: object | null | undefined, opts?: object): node is ForInStatement; +export function isForStatement(node: object | null | undefined, opts?: object): node is ForStatement; +export function isFunctionDeclaration(node: object | null | undefined, opts?: object): node is FunctionDeclaration; +export function isFunctionExpression(node: object | null | undefined, opts?: object): node is FunctionExpression; +export function isIdentifier(node: object | null | undefined, opts?: object): node is Identifier; +export function isIfStatement(node: object | null | undefined, opts?: object): node is IfStatement; +export function isLabeledStatement(node: object | null | undefined, opts?: object): node is LabeledStatement; +export function isStringLiteral(node: object | null | undefined, opts?: object): node is StringLiteral; +export function isNumericLiteral(node: object | null | undefined, opts?: object): node is NumericLiteral; +export function isNullLiteral(node: object | null | undefined, opts?: object): node is NullLiteral; +export function isBooleanLiteral(node: object | null | undefined, opts?: object): node is BooleanLiteral; +export function isRegExpLiteral(node: object | null | undefined, opts?: object): node is RegExpLiteral; +export function isLogicalExpression(node: object | null | undefined, opts?: object): node is LogicalExpression; +export function isMemberExpression(node: object | null | undefined, opts?: object): node is MemberExpression; +export function isNewExpression(node: object | null | undefined, opts?: object): node is NewExpression; +export function isProgram(node: object | null | undefined, opts?: object): node is Program; +export function isObjectExpression(node: object | null | undefined, opts?: object): node is ObjectExpression; +export function isObjectMethod(node: object | null | undefined, opts?: object): node is ObjectMethod; +export function isObjectProperty(node: object | null | undefined, opts?: object): node is ObjectProperty; +export function isRestElement(node: object | null | undefined, opts?: object): node is RestElement; +export function isReturnStatement(node: object | null | undefined, opts?: object): node is ReturnStatement; +export function isSequenceExpression(node: object | null | undefined, opts?: object): node is SequenceExpression; +export function isSwitchCase(node: object | null | undefined, opts?: object): node is SwitchCase; +export function isSwitchStatement(node: object | null | undefined, opts?: object): node is SwitchStatement; +export function isThisExpression(node: object | null | undefined, opts?: object): node is ThisExpression; +export function isThrowStatement(node: object | null | undefined, opts?: object): node is ThrowStatement; +export function isTryStatement(node: object | null | undefined, opts?: object): node is TryStatement; +export function isUnaryExpression(node: object | null | undefined, opts?: object): node is UnaryExpression; +export function isUpdateExpression(node: object | null | undefined, opts?: object): node is UpdateExpression; +export function isVariableDeclaration(node: object | null | undefined, opts?: object): node is VariableDeclaration; +export function isVariableDeclarator(node: object | null | undefined, opts?: object): node is VariableDeclarator; +export function isWhileStatement(node: object | null | undefined, opts?: object): node is WhileStatement; +export function isWithStatement(node: object | null | undefined, opts?: object): node is WithStatement; +export function isAssignmentPattern(node: object | null | undefined, opts?: object): node is AssignmentPattern; +export function isArrayPattern(node: object | null | undefined, opts?: object): node is ArrayPattern; +export function isArrowFunctionExpression(node: object | null | undefined, opts?: object): node is ArrowFunctionExpression; +export function isClassBody(node: object | null | undefined, opts?: object): node is ClassBody; +export function isClassDeclaration(node: object | null | undefined, opts?: object): node is ClassDeclaration; +export function isClassExpression(node: object | null | undefined, opts?: object): node is ClassExpression; +export function isExportAllDeclaration(node: object | null | undefined, opts?: object): node is ExportAllDeclaration; +export function isExportDefaultDeclaration(node: object | null | undefined, opts?: object): node is ExportDefaultDeclaration; +export function isExportNamedDeclaration(node: object | null | undefined, opts?: object): node is ExportNamedDeclaration; +export function isExportSpecifier(node: object | null | undefined, opts?: object): node is ExportSpecifier; +export function isForOfStatement(node: object | null | undefined, opts?: object): node is ForOfStatement; +export function isImportDeclaration(node: object | null | undefined, opts?: object): node is ImportDeclaration; +export function isImportDefaultSpecifier(node: object | null | undefined, opts?: object): node is ImportDefaultSpecifier; +export function isImportNamespaceSpecifier(node: object | null | undefined, opts?: object): node is ImportNamespaceSpecifier; +export function isImportSpecifier(node: object | null | undefined, opts?: object): node is ImportSpecifier; +export function isMetaProperty(node: object | null | undefined, opts?: object): node is MetaProperty; +export function isClassMethod(node: object | null | undefined, opts?: object): node is ClassMethod; +export function isObjectPattern(node: object | null | undefined, opts?: object): node is ObjectPattern; +export function isSpreadElement(node: object | null | undefined, opts?: object): node is SpreadElement; +export function isSuper(node: object | null | undefined, opts?: object): node is Super; +export function isTaggedTemplateExpression(node: object | null | undefined, opts?: object): node is TaggedTemplateExpression; +export function isTemplateElement(node: object | null | undefined, opts?: object): node is TemplateElement; +export function isTemplateLiteral(node: object | null | undefined, opts?: object): node is TemplateLiteral; +export function isYieldExpression(node: object | null | undefined, opts?: object): node is YieldExpression; +export function isAnyTypeAnnotation(node: object | null | undefined, opts?: object): node is AnyTypeAnnotation; +export function isArrayTypeAnnotation(node: object | null | undefined, opts?: object): node is ArrayTypeAnnotation; +export function isBooleanTypeAnnotation(node: object | null | undefined, opts?: object): node is BooleanTypeAnnotation; +export function isBooleanLiteralTypeAnnotation(node: object | null | undefined, opts?: object): node is BooleanLiteralTypeAnnotation; +export function isNullLiteralTypeAnnotation(node: object | null | undefined, opts?: object): node is NullLiteralTypeAnnotation; +export function isClassImplements(node: object | null | undefined, opts?: object): node is ClassImplements; +export function isClassProperty(node: object | null | undefined, opts?: object): node is ClassProperty; +export function isDeclareClass(node: object | null | undefined, opts?: object): node is DeclareClass; +export function isDeclareFunction(node: object | null | undefined, opts?: object): node is DeclareFunction; +export function isDeclareInterface(node: object | null | undefined, opts?: object): node is DeclareInterface; +export function isDeclareModule(node: object | null | undefined, opts?: object): node is DeclareModule; +export function isDeclareTypeAlias(node: object | null | undefined, opts?: object): node is DeclareTypeAlias; +export function isDeclareVariable(node: object | null | undefined, opts?: object): node is DeclareVariable; +export function isExistentialTypeParam(node: object | null | undefined, opts?: object): node is ExistentialTypeParam; +export function isFunctionTypeAnnotation(node: object | null | undefined, opts?: object): node is FunctionTypeAnnotation; +export function isFunctionTypeParam(node: object | null | undefined, opts?: object): node is FunctionTypeParam; +export function isGenericTypeAnnotation(node: object | null | undefined, opts?: object): node is GenericTypeAnnotation; +export function isInterfaceExtends(node: object | null | undefined, opts?: object): node is InterfaceExtends; +export function isInterfaceDeclaration(node: object | null | undefined, opts?: object): node is InterfaceDeclaration; +export function isIntersectionTypeAnnotation(node: object | null | undefined, opts?: object): node is IntersectionTypeAnnotation; +export function isMixedTypeAnnotation(node: object | null | undefined, opts?: object): node is MixedTypeAnnotation; +export function isNullableTypeAnnotation(node: object | null | undefined, opts?: object): node is NullableTypeAnnotation; +export function isNumericLiteralTypeAnnotation(node: object | null | undefined, opts?: object): node is NumericLiteralTypeAnnotation; +export function isNumberTypeAnnotation(node: object | null | undefined, opts?: object): node is NumberTypeAnnotation; +export function isStringLiteralTypeAnnotation(node: object | null | undefined, opts?: object): node is StringLiteralTypeAnnotation; +export function isStringTypeAnnotation(node: object | null | undefined, opts?: object): node is StringTypeAnnotation; +export function isThisTypeAnnotation(node: object | null | undefined, opts?: object): node is ThisTypeAnnotation; +export function isTupleTypeAnnotation(node: object | null | undefined, opts?: object): node is TupleTypeAnnotation; +export function isTypeofTypeAnnotation(node: object | null | undefined, opts?: object): node is TypeofTypeAnnotation; +export function isTypeAlias(node: object | null | undefined, opts?: object): node is TypeAlias; +export function isTypeAnnotation(node: object | null | undefined, opts?: object): node is TypeAnnotation; +export function isTypeCastExpression(node: object | null | undefined, opts?: object): node is TypeCastExpression; +export function isTypeParameter(node: object | null | undefined, opts?: object): node is TypeParameter; +export function isTypeParameterDeclaration(node: object | null | undefined, opts?: object): node is TypeParameterDeclaration; +export function isTypeParameterInstantiation(node: object | null | undefined, opts?: object): node is TypeParameterInstantiation; +export function isObjectTypeAnnotation(node: object | null | undefined, opts?: object): node is ObjectTypeAnnotation; +export function isObjectTypeCallProperty(node: object | null | undefined, opts?: object): node is ObjectTypeCallProperty; +export function isObjectTypeIndexer(node: object | null | undefined, opts?: object): node is ObjectTypeIndexer; +export function isObjectTypeProperty(node: object | null | undefined, opts?: object): node is ObjectTypeProperty; +export function isQualifiedTypeIdentifier(node: object | null | undefined, opts?: object): node is QualifiedTypeIdentifier; +export function isUnionTypeAnnotation(node: object | null | undefined, opts?: object): node is UnionTypeAnnotation; +export function isVoidTypeAnnotation(node: object | null | undefined, opts?: object): node is VoidTypeAnnotation; +export function isJSXAttribute(node: object | null | undefined, opts?: object): node is JSXAttribute; +export function isJSXClosingElement(node: object | null | undefined, opts?: object): node is JSXClosingElement; +export function isJSXElement(node: object | null | undefined, opts?: object): node is JSXElement; +export function isJSXEmptyExpression(node: object | null | undefined, opts?: object): node is JSXEmptyExpression; +export function isJSXExpressionContainer(node: object | null | undefined, opts?: object): node is JSXExpressionContainer; +export function isJSXIdentifier(node: object | null | undefined, opts?: object): node is JSXIdentifier; +export function isJSXMemberExpression(node: object | null | undefined, opts?: object): node is JSXMemberExpression; +export function isJSXNamespacedName(node: object | null | undefined, opts?: object): node is JSXNamespacedName; +export function isJSXOpeningElement(node: object | null | undefined, opts?: object): node is JSXOpeningElement; +export function isJSXSpreadAttribute(node: object | null | undefined, opts?: object): node is JSXSpreadAttribute; +export function isJSXText(node: object | null | undefined, opts?: object): node is JSXText; +export function isNoop(node: object | null | undefined, opts?: object): node is Noop; +export function isParenthesizedExpression(node: object | null | undefined, opts?: object): node is ParenthesizedExpression; +export function isAwaitExpression(node: object | null | undefined, opts?: object): node is AwaitExpression; +export function isBindExpression(node: object | null | undefined, opts?: object): node is BindExpression; +export function isDecorator(node: object | null | undefined, opts?: object): node is Decorator; +export function isDoExpression(node: object | null | undefined, opts?: object): node is DoExpression; +export function isExportDefaultSpecifier(node: object | null | undefined, opts?: object): node is ExportDefaultSpecifier; +export function isExportNamespaceSpecifier(node: object | null | undefined, opts?: object): node is ExportNamespaceSpecifier; +export function isRestProperty(node: object | null | undefined, opts?: object): node is RestProperty; +export function isSpreadProperty(node: object | null | undefined, opts?: object): node is SpreadProperty; +export function isExpression(node: object | null | undefined, opts?: object): node is Expression; +export function isBinary(node: object | null | undefined, opts?: object): node is Binary; +export function isScopable(node: object | null | undefined, opts?: object): node is Scopable; +export function isBlockParent(node: object | null | undefined, opts?: object): node is BlockParent; +export function isBlock(node: object | null | undefined, opts?: object): node is Block; +export function isStatement(node: object | null | undefined, opts?: object): node is Statement; +export function isTerminatorless(node: object | null | undefined, opts?: object): node is Terminatorless; +export function isCompletionStatement(node: object | null | undefined, opts?: object): node is CompletionStatement; +export function isConditional(node: object | null | undefined, opts?: object): node is Conditional; +export function isLoop(node: object | null | undefined, opts?: object): node is Loop; +export function isWhile(node: object | null | undefined, opts?: object): node is While; +export function isExpressionWrapper(node: object | null | undefined, opts?: object): node is ExpressionWrapper; +export function isFor(node: object | null | undefined, opts?: object): node is For; +export function isForXStatement(node: object | null | undefined, opts?: object): node is ForXStatement; // tslint:disable-next-line ban-types -export function isFunction(node: object, opts?: object): node is Function; -export function isFunctionParent(node: object, opts?: object): node is FunctionParent; -export function isPureish(node: object, opts?: object): node is Pureish; -export function isDeclaration(node: object, opts?: object): node is Declaration; -export function isLVal(node: object, opts?: object): node is LVal; -export function isLiteral(node: object, opts?: object): node is Literal; -export function isImmutable(node: object, opts?: object): node is Immutable; -export function isUserWhitespacable(node: object, opts?: object): node is UserWhitespacable; -export function isMethod(node: object, opts?: object): node is Method; -export function isObjectMember(node: object, opts?: object): node is ObjectMember; -export function isProperty(node: object, opts?: object): node is Property; -export function isUnaryLike(node: object, opts?: object): node is UnaryLike; -export function isPattern(node: object, opts?: object): node is Pattern; -export function isClass(node: object, opts?: object): node is Class; -export function isModuleDeclaration(node: object, opts?: object): node is ModuleDeclaration; -export function isExportDeclaration(node: object, opts?: object): node is ExportDeclaration; -export function isModuleSpecifier(node: object, opts?: object): node is ModuleSpecifier; -export function isFlow(node: object, opts?: object): node is Flow; -export function isFlowBaseAnnotation(node: object, opts?: object): node is FlowBaseAnnotation; -export function isFlowDeclaration(node: object, opts?: object): node is FlowDeclaration; -export function isJSX(node: object, opts?: object): node is JSX; -export function isNumberLiteral(node: object, opts?: object): node is NumericLiteral; -export function isRegexLiteral(node: object, opts?: object): node is RegExpLiteral; +export function isFunction(node: object | null | undefined, opts?: object): node is Function; +export function isFunctionParent(node: object | null | undefined, opts?: object): node is FunctionParent; +export function isPureish(node: object | null | undefined, opts?: object): node is Pureish; +export function isDeclaration(node: object | null | undefined, opts?: object): node is Declaration; +export function isLVal(node: object | null | undefined, opts?: object): node is LVal; +export function isLiteral(node: object | null | undefined, opts?: object): node is Literal; +export function isImmutable(node: object | null | undefined, opts?: object): node is Immutable; +export function isUserWhitespacable(node: object | null | undefined, opts?: object): node is UserWhitespacable; +export function isMethod(node: object | null | undefined, opts?: object): node is Method; +export function isObjectMember(node: object | null | undefined, opts?: object): node is ObjectMember; +export function isProperty(node: object | null | undefined, opts?: object): node is Property; +export function isUnaryLike(node: object | null | undefined, opts?: object): node is UnaryLike; +export function isPattern(node: object | null | undefined, opts?: object): node is Pattern; +export function isClass(node: object | null | undefined, opts?: object): node is Class; +export function isModuleDeclaration(node: object | null | undefined, opts?: object): node is ModuleDeclaration; +export function isExportDeclaration(node: object | null | undefined, opts?: object): node is ExportDeclaration; +export function isModuleSpecifier(node: object | null | undefined, opts?: object): node is ModuleSpecifier; +export function isFlow(node: object | null | undefined, opts?: object): node is Flow; +export function isFlowBaseAnnotation(node: object | null | undefined, opts?: object): node is FlowBaseAnnotation; +export function isFlowDeclaration(node: object | null | undefined, opts?: object): node is FlowDeclaration; +export function isJSX(node: object | null | undefined, opts?: object): node is JSX; +export function isNumberLiteral(node: object | null | undefined, opts?: object): node is NumericLiteral; +export function isRegexLiteral(node: object | null | undefined, opts?: object): node is RegExpLiteral; -export function isReferencedIdentifier(node: object, opts?: object): node is Identifier | JSXIdentifier; -export function isReferencedMemberExpression(node: object, opts?: object): node is MemberExpression; -export function isBindingIdentifier(node: object, opts?: object): node is Identifier; -export function isScope(node: object, opts?: object): node is Scopable; -export function isReferenced(node: object, opts?: object): boolean; -export function isBlockScoped(node: object, opts?: object): node is FunctionDeclaration | ClassDeclaration | VariableDeclaration; -export function isVar(node: object, opts?: object): node is VariableDeclaration; -export function isUser(node: object, opts?: object): boolean; -export function isGenerated(node: object, opts?: object): boolean; -export function isPure(node: object, opts?: object): boolean; +export function isReferencedIdentifier(node: object | null | undefined, opts?: object): node is Identifier | JSXIdentifier; +export function isReferencedMemberExpression(node: object | null | undefined, opts?: object): node is MemberExpression; +export function isBindingIdentifier(node: object | null | undefined, opts?: object): node is Identifier; +export function isScope(node: object | null | undefined, opts?: object): node is Scopable; +export function isReferenced(node: object | null | undefined, opts?: object): boolean; +export function isBlockScoped(node: object | null | undefined, opts?: object): node is FunctionDeclaration | ClassDeclaration | VariableDeclaration; +export function isVar(node: object | null | undefined, opts?: object): node is VariableDeclaration; +export function isUser(node: object | null | undefined, opts?: object): boolean; +export function isGenerated(node: object | null | undefined, opts?: object): boolean; +export function isPure(node: object | null | undefined, opts?: object): boolean; -export function isTSAnyKeyword(node: object, opts?: object): node is TSAnyKeyword; -export function isTSArrayType(node: object, opts?: object): node is TSArrayType; -export function isTSAsExpression(node: object, opts?: object): node is TSAsExpression; -export function isTSBooleanKeyword(node: object, opts?: object): node is TSBooleanKeyword; -export function isTSCallSignatureDeclaration(node: object, opts?: object): node is TSCallSignatureDeclaration; -export function isTSConstructSignatureDeclaration(node: object, opts?: object): node is TSTypeElement; -export function isTSConstructorType(node: object, opts?: object): node is TSConstructorType; -export function isTSDeclareFunction(node: object, opts?: object): node is TSDeclareFunction; -export function isTSDeclareMethod(node: object, opts?: object): node is TSDeclareMethod; -export function isTSEnumDeclaration(node: object, opts?: object): node is TSEnumDeclaration; -export function isTSEnumMember(node: object, opts?: object): node is TSEnumMember; -export function isTSExportAssignment(node: object, opts?: object): node is TSExportAssignment; -export function isTSExpressionWithTypeArguments(node: object, opts?: object): node is TSExpressionWithTypeArguments; -export function isTSExternalModuleReference(node: object, opts?: object): node is TSExternalModuleReference; -export function isTSFunctionType(node: object, opts?: object): node is TSFunctionType; -export function isTSImportEqualsDeclaration(node: object, opts?: object): node is TSImportEqualsDeclaration; -export function isTSIndexSignature(node: object, opts?: object): node is TSIndexSignature; -export function isTSIndexedAccessType(node: object, opts?: object): node is TSIndexedAccessType; -export function isTSInterfaceBody(node: object, opts?: object): node is TSInterfaceBody; -export function isTSInterfaceDeclaration(node: object, opts?: object): node is TSInterfaceDeclaration; -export function isTSIntersectionType(node: object, opts?: object): node is TSIntersectionType; -export function isTSLiteralType(node: object, opts?: object): node is TSLiteralType; -export function isTSMappedType(node: object, opts?: object): node is TSMappedType; -export function isTSMethodSignature(node: object, opts?: object): node is TSMethodSignature; -export function isTSModuleBlock(node: object, opts?: object): node is TSModuleBlock; -export function isTSModuleDeclaration(node: object, opts?: object): node is TSModuleDeclaration; -export function isTSNamespaceExportDeclaration(node: object, opts?: object): node is TSNamespaceExportDeclaration; -export function isTSNeverKeyword(node: object, opts?: object): node is TSNeverKeyword; -export function isTSNonNullExpression(node: object, opts?: object): node is TSNonNullExpression; -export function isTSNullKeyword(node: object, opts?: object): node is TSNullKeyword; -export function isTSNumberKeyword(node: object, opts?: object): node is TSNumberKeyword; -export function isTSObjectKeyword(node: object, opts?: object): node is TSObjectKeyword; -export function isTSParameterProperty(node: object, opts?: object): node is TSParameterProperty; -export function isTSParenthesizedType(node: object, opts?: object): node is TSParenthesizedType; -export function isTSPropertySignature(node: object, opts?: object): node is TSPropertySignature; -export function isTSQualifiedName(node: object, opts?: object): node is TSQualifiedName; -export function isTSStringKeyword(node: object, opts?: object): node is TSStringKeyword; -export function isTSSymbolKeyword(node: object, opts?: object): node is TSSymbolKeyword; -export function isTSThisType(node: object, opts?: object): node is TSThisType; -export function isTSTupleType(node: object, opts?: object): node is TSTupleType; -export function isTSTypeAliasDeclaration(node: object, opts?: object): node is TSTypeAliasDeclaration; -export function isTSTypeAnnotation(node: object, opts?: object): node is TSTypeAnnotation; -export function isTSTypeAssertion(node: object, opts?: object): node is TSTypeAssertion; -export function isTSTypeLiteral(node: object, opts?: object): node is TSTypeLiteral; -export function isTSTypeOperator(node: object, opts?: object): node is TSTypeOperator; -export function isTSTypeParameter(node: object, opts?: object): node is TSTypeParameter; -export function isTSTypeParameterDeclaration(node: object, opts?: object): node is TSTypeParameterDeclaration; -export function isTSTypeParameterInstantiation(node: object, opts?: object): node is TSTypeParameterInstantiation; -export function isTSTypePredicate(node: object, opts?: object): node is TSTypePredicate; -export function isTSTypeQuery(node: object, opts?: object): node is TSTypeQuery; -export function isTSTypeReference(node: object, opts?: object): node is TSTypeReference; -export function isTSUndefinedKeyword(node: object, opts?: object): node is TSUndefinedKeyword; -export function isTSUnionType(node: object, opts?: object): node is TSUnionType; -export function isTSVoidKeyword(node: object, opts?: object): node is TSVoidKeyword; +export function isTSAnyKeyword(node: object | null | undefined, opts?: object): node is TSAnyKeyword; +export function isTSArrayType(node: object | null | undefined, opts?: object): node is TSArrayType; +export function isTSAsExpression(node: object | null | undefined, opts?: object): node is TSAsExpression; +export function isTSBooleanKeyword(node: object | null | undefined, opts?: object): node is TSBooleanKeyword; +export function isTSCallSignatureDeclaration(node: object | null | undefined, opts?: object): node is TSCallSignatureDeclaration; +export function isTSConstructSignatureDeclaration(node: object | null | undefined, opts?: object): node is TSTypeElement; +export function isTSConstructorType(node: object | null | undefined, opts?: object): node is TSConstructorType; +export function isTSDeclareFunction(node: object | null | undefined, opts?: object): node is TSDeclareFunction; +export function isTSDeclareMethod(node: object | null | undefined, opts?: object): node is TSDeclareMethod; +export function isTSEnumDeclaration(node: object | null | undefined, opts?: object): node is TSEnumDeclaration; +export function isTSEnumMember(node: object | null | undefined, opts?: object): node is TSEnumMember; +export function isTSExportAssignment(node: object | null | undefined, opts?: object): node is TSExportAssignment; +export function isTSExpressionWithTypeArguments(node: object | null | undefined, opts?: object): node is TSExpressionWithTypeArguments; +export function isTSExternalModuleReference(node: object | null | undefined, opts?: object): node is TSExternalModuleReference; +export function isTSFunctionType(node: object | null | undefined, opts?: object): node is TSFunctionType; +export function isTSImportEqualsDeclaration(node: object | null | undefined, opts?: object): node is TSImportEqualsDeclaration; +export function isTSIndexSignature(node: object | null | undefined, opts?: object): node is TSIndexSignature; +export function isTSIndexedAccessType(node: object | null | undefined, opts?: object): node is TSIndexedAccessType; +export function isTSInterfaceBody(node: object | null | undefined, opts?: object): node is TSInterfaceBody; +export function isTSInterfaceDeclaration(node: object | null | undefined, opts?: object): node is TSInterfaceDeclaration; +export function isTSIntersectionType(node: object | null | undefined, opts?: object): node is TSIntersectionType; +export function isTSLiteralType(node: object | null | undefined, opts?: object): node is TSLiteralType; +export function isTSMappedType(node: object | null | undefined, opts?: object): node is TSMappedType; +export function isTSMethodSignature(node: object | null | undefined, opts?: object): node is TSMethodSignature; +export function isTSModuleBlock(node: object | null | undefined, opts?: object): node is TSModuleBlock; +export function isTSModuleDeclaration(node: object | null | undefined, opts?: object): node is TSModuleDeclaration; +export function isTSNamespaceExportDeclaration(node: object | null | undefined, opts?: object): node is TSNamespaceExportDeclaration; +export function isTSNeverKeyword(node: object | null | undefined, opts?: object): node is TSNeverKeyword; +export function isTSNonNullExpression(node: object | null | undefined, opts?: object): node is TSNonNullExpression; +export function isTSNullKeyword(node: object | null | undefined, opts?: object): node is TSNullKeyword; +export function isTSNumberKeyword(node: object | null | undefined, opts?: object): node is TSNumberKeyword; +export function isTSObjectKeyword(node: object | null | undefined, opts?: object): node is TSObjectKeyword; +export function isTSParameterProperty(node: object | null | undefined, opts?: object): node is TSParameterProperty; +export function isTSParenthesizedType(node: object | null | undefined, opts?: object): node is TSParenthesizedType; +export function isTSPropertySignature(node: object | null | undefined, opts?: object): node is TSPropertySignature; +export function isTSQualifiedName(node: object | null | undefined, opts?: object): node is TSQualifiedName; +export function isTSStringKeyword(node: object | null | undefined, opts?: object): node is TSStringKeyword; +export function isTSSymbolKeyword(node: object | null | undefined, opts?: object): node is TSSymbolKeyword; +export function isTSThisType(node: object | null | undefined, opts?: object): node is TSThisType; +export function isTSTupleType(node: object | null | undefined, opts?: object): node is TSTupleType; +export function isTSTypeAliasDeclaration(node: object | null | undefined, opts?: object): node is TSTypeAliasDeclaration; +export function isTSTypeAnnotation(node: object | null | undefined, opts?: object): node is TSTypeAnnotation; +export function isTSTypeAssertion(node: object | null | undefined, opts?: object): node is TSTypeAssertion; +export function isTSTypeLiteral(node: object | null | undefined, opts?: object): node is TSTypeLiteral; +export function isTSTypeOperator(node: object | null | undefined, opts?: object): node is TSTypeOperator; +export function isTSTypeParameter(node: object | null | undefined, opts?: object): node is TSTypeParameter; +export function isTSTypeParameterDeclaration(node: object | null | undefined, opts?: object): node is TSTypeParameterDeclaration; +export function isTSTypeParameterInstantiation(node: object | null | undefined, opts?: object): node is TSTypeParameterInstantiation; +export function isTSTypePredicate(node: object | null | undefined, opts?: object): node is TSTypePredicate; +export function isTSTypeQuery(node: object | null | undefined, opts?: object): node is TSTypeQuery; +export function isTSTypeReference(node: object | null | undefined, opts?: object): node is TSTypeReference; +export function isTSUndefinedKeyword(node: object | null | undefined, opts?: object): node is TSUndefinedKeyword; +export function isTSUnionType(node: object | null | undefined, opts?: object): node is TSUnionType; +export function isTSVoidKeyword(node: object | null | undefined, opts?: object): node is TSVoidKeyword; // React specific export interface ReactHelpers { @@ -1762,231 +1762,231 @@ export interface ReactHelpers { } export const react: ReactHelpers; -export function assertArrayExpression(node: object, opts?: object): void; -export function assertAssignmentExpression(node: object, opts?: object): void; -export function assertBinaryExpression(node: object, opts?: object): void; -export function assertDirective(node: object, opts?: object): void; -export function assertDirectiveLiteral(node: object, opts?: object): void; -export function assertBlockStatement(node: object, opts?: object): void; -export function assertBreakStatement(node: object, opts?: object): void; -export function assertCallExpression(node: object, opts?: object): void; -export function assertCatchClause(node: object, opts?: object): void; -export function assertConditionalExpression(node: object, opts?: object): void; -export function assertContinueStatement(node: object, opts?: object): void; -export function assertDebuggerStatement(node: object, opts?: object): void; -export function assertDoWhileStatement(node: object, opts?: object): void; -export function assertEmptyStatement(node: object, opts?: object): void; -export function assertExpressionStatement(node: object, opts?: object): void; -export function assertFile(node: object, opts?: object): void; -export function assertForInStatement(node: object, opts?: object): void; -export function assertForStatement(node: object, opts?: object): void; -export function assertFunctionDeclaration(node: object, opts?: object): void; -export function assertFunctionExpression(node: object, opts?: object): void; -export function assertIdentifier(node: object, opts?: object): void; -export function assertIfStatement(node: object, opts?: object): void; -export function assertLabeledStatement(node: object, opts?: object): void; -export function assertStringLiteral(node: object, opts?: object): void; -export function assertNumericLiteral(node: object, opts?: object): void; -export function assertNullLiteral(node: object, opts?: object): void; -export function assertBooleanLiteral(node: object, opts?: object): void; -export function assertRegExpLiteral(node: object, opts?: object): void; -export function assertLogicalExpression(node: object, opts?: object): void; -export function assertMemberExpression(node: object, opts?: object): void; -export function assertNewExpression(node: object, opts?: object): void; -export function assertProgram(node: object, opts?: object): void; -export function assertObjectExpression(node: object, opts?: object): void; -export function assertObjectMethod(node: object, opts?: object): void; -export function assertObjectProperty(node: object, opts?: object): void; -export function assertRestElement(node: object, opts?: object): void; -export function assertReturnStatement(node: object, opts?: object): void; -export function assertSequenceExpression(node: object, opts?: object): void; -export function assertSwitchCase(node: object, opts?: object): void; -export function assertSwitchStatement(node: object, opts?: object): void; -export function assertThisExpression(node: object, opts?: object): void; -export function assertThrowStatement(node: object, opts?: object): void; -export function assertTryStatement(node: object, opts?: object): void; -export function assertUnaryExpression(node: object, opts?: object): void; -export function assertUpdateExpression(node: object, opts?: object): void; -export function assertVariableDeclaration(node: object, opts?: object): void; -export function assertVariableDeclarator(node: object, opts?: object): void; -export function assertWhileStatement(node: object, opts?: object): void; -export function assertWithStatement(node: object, opts?: object): void; -export function assertAssignmentPattern(node: object, opts?: object): void; -export function assertArrayPattern(node: object, opts?: object): void; -export function assertArrowFunctionExpression(node: object, opts?: object): void; -export function assertClassBody(node: object, opts?: object): void; -export function assertClassDeclaration(node: object, opts?: object): void; -export function assertClassExpression(node: object, opts?: object): void; -export function assertExportAllDeclaration(node: object, opts?: object): void; -export function assertExportDefaultDeclaration(node: object, opts?: object): void; -export function assertExportNamedDeclaration(node: object, opts?: object): void; -export function assertExportSpecifier(node: object, opts?: object): void; -export function assertForOfStatement(node: object, opts?: object): void; -export function assertImportDeclaration(node: object, opts?: object): void; -export function assertImportDefaultSpecifier(node: object, opts?: object): void; -export function assertImportNamespaceSpecifier(node: object, opts?: object): void; -export function assertImportSpecifier(node: object, opts?: object): void; -export function assertMetaProperty(node: object, opts?: object): void; -export function assertClassMethod(node: object, opts?: object): void; -export function assertObjectPattern(node: object, opts?: object): void; -export function assertSpreadElement(node: object, opts?: object): void; -export function assertSuper(node: object, opts?: object): void; -export function assertTaggedTemplateExpression(node: object, opts?: object): void; -export function assertTemplateElement(node: object, opts?: object): void; -export function assertTemplateLiteral(node: object, opts?: object): void; -export function assertYieldExpression(node: object, opts?: object): void; -export function assertAnyTypeAnnotation(node: object, opts?: object): void; -export function assertArrayTypeAnnotation(node: object, opts?: object): void; -export function assertBooleanTypeAnnotation(node: object, opts?: object): void; -export function assertBooleanLiteralTypeAnnotation(node: object, opts?: object): void; -export function assertNullLiteralTypeAnnotation(node: object, opts?: object): void; -export function assertClassImplements(node: object, opts?: object): void; -export function assertClassProperty(node: object, opts?: object): void; -export function assertDeclareClass(node: object, opts?: object): void; -export function assertDeclareFunction(node: object, opts?: object): void; -export function assertDeclareInterface(node: object, opts?: object): void; -export function assertDeclareModule(node: object, opts?: object): void; -export function assertDeclareTypeAlias(node: object, opts?: object): void; -export function assertDeclareVariable(node: object, opts?: object): void; -export function assertExistentialTypeParam(node: object, opts?: object): void; -export function assertFunctionTypeAnnotation(node: object, opts?: object): void; -export function assertFunctionTypeParam(node: object, opts?: object): void; -export function assertGenericTypeAnnotation(node: object, opts?: object): void; -export function assertInterfaceExtends(node: object, opts?: object): void; -export function assertInterfaceDeclaration(node: object, opts?: object): void; -export function assertIntersectionTypeAnnotation(node: object, opts?: object): void; -export function assertMixedTypeAnnotation(node: object, opts?: object): void; -export function assertNullableTypeAnnotation(node: object, opts?: object): void; -export function assertNumericLiteralTypeAnnotation(node: object, opts?: object): void; -export function assertNumberTypeAnnotation(node: object, opts?: object): void; -export function assertStringLiteralTypeAnnotation(node: object, opts?: object): void; -export function assertStringTypeAnnotation(node: object, opts?: object): void; -export function assertThisTypeAnnotation(node: object, opts?: object): void; -export function assertTupleTypeAnnotation(node: object, opts?: object): void; -export function assertTypeofTypeAnnotation(node: object, opts?: object): void; -export function assertTypeAlias(node: object, opts?: object): void; -export function assertTypeAnnotation(node: object, opts?: object): void; -export function assertTypeCastExpression(node: object, opts?: object): void; -export function assertTypeParameter(node: object, opts?: object): void; -export function assertTypeParameterDeclaration(node: object, opts?: object): void; -export function assertTypeParameterInstantiation(node: object, opts?: object): void; -export function assertObjectTypeAnnotation(node: object, opts?: object): void; -export function assertObjectTypeCallProperty(node: object, opts?: object): void; -export function assertObjectTypeIndexer(node: object, opts?: object): void; -export function assertObjectTypeProperty(node: object, opts?: object): void; -export function assertQualifiedTypeIdentifier(node: object, opts?: object): void; -export function assertUnionTypeAnnotation(node: object, opts?: object): void; -export function assertVoidTypeAnnotation(node: object, opts?: object): void; -export function assertJSXAttribute(node: object, opts?: object): void; -export function assertJSXClosingElement(node: object, opts?: object): void; -export function assertJSXElement(node: object, opts?: object): void; -export function assertJSXEmptyExpression(node: object, opts?: object): void; -export function assertJSXExpressionContainer(node: object, opts?: object): void; -export function assertJSXIdentifier(node: object, opts?: object): void; -export function assertJSXMemberExpression(node: object, opts?: object): void; -export function assertJSXNamespacedName(node: object, opts?: object): void; -export function assertJSXOpeningElement(node: object, opts?: object): void; -export function assertJSXSpreadAttribute(node: object, opts?: object): void; -export function assertJSXText(node: object, opts?: object): void; -export function assertNoop(node: object, opts?: object): void; -export function assertParenthesizedExpression(node: object, opts?: object): void; -export function assertAwaitExpression(node: object, opts?: object): void; -export function assertBindExpression(node: object, opts?: object): void; -export function assertDecorator(node: object, opts?: object): void; -export function assertDoExpression(node: object, opts?: object): void; -export function assertExportDefaultSpecifier(node: object, opts?: object): void; -export function assertExportNamespaceSpecifier(node: object, opts?: object): void; -export function assertRestProperty(node: object, opts?: object): void; -export function assertSpreadProperty(node: object, opts?: object): void; -export function assertExpression(node: object, opts?: object): void; -export function assertBinary(node: object, opts?: object): void; -export function assertScopable(node: object, opts?: object): void; -export function assertBlockParent(node: object, opts?: object): void; -export function assertBlock(node: object, opts?: object): void; -export function assertStatement(node: object, opts?: object): void; -export function assertTerminatorless(node: object, opts?: object): void; -export function assertCompletionStatement(node: object, opts?: object): void; -export function assertConditional(node: object, opts?: object): void; -export function assertLoop(node: object, opts?: object): void; -export function assertWhile(node: object, opts?: object): void; -export function assertExpressionWrapper(node: object, opts?: object): void; -export function assertFor(node: object, opts?: object): void; -export function assertForXStatement(node: object, opts?: object): void; -export function assertFunction(node: object, opts?: object): void; -export function assertFunctionParent(node: object, opts?: object): void; -export function assertPureish(node: object, opts?: object): void; -export function assertDeclaration(node: object, opts?: object): void; -export function assertLVal(node: object, opts?: object): void; -export function assertLiteral(node: object, opts?: object): void; -export function assertImmutable(node: object, opts?: object): void; -export function assertUserWhitespacable(node: object, opts?: object): void; -export function assertMethod(node: object, opts?: object): void; -export function assertObjectMember(node: object, opts?: object): void; -export function assertProperty(node: object, opts?: object): void; -export function assertUnaryLike(node: object, opts?: object): void; -export function assertPattern(node: object, opts?: object): void; -export function assertClass(node: object, opts?: object): void; -export function assertModuleDeclaration(node: object, opts?: object): void; -export function assertExportDeclaration(node: object, opts?: object): void; -export function assertModuleSpecifier(node: object, opts?: object): void; -export function assertFlow(node: object, opts?: object): void; -export function assertFlowBaseAnnotation(node: object, opts?: object): void; -export function assertFlowDeclaration(node: object, opts?: object): void; -export function assertJSX(node: object, opts?: object): void; -export function assertNumberLiteral(node: object, opts?: object): void; -export function assertRegexLiteral(node: object, opts?: object): void; +export function assertArrayExpression(node: object | null | undefined, opts?: object): void; +export function assertAssignmentExpression(node: object | null | undefined, opts?: object): void; +export function assertBinaryExpression(node: object | null | undefined, opts?: object): void; +export function assertDirective(node: object | null | undefined, opts?: object): void; +export function assertDirectiveLiteral(node: object | null | undefined, opts?: object): void; +export function assertBlockStatement(node: object | null | undefined, opts?: object): void; +export function assertBreakStatement(node: object | null | undefined, opts?: object): void; +export function assertCallExpression(node: object | null | undefined, opts?: object): void; +export function assertCatchClause(node: object | null | undefined, opts?: object): void; +export function assertConditionalExpression(node: object | null | undefined, opts?: object): void; +export function assertContinueStatement(node: object | null | undefined, opts?: object): void; +export function assertDebuggerStatement(node: object | null | undefined, opts?: object): void; +export function assertDoWhileStatement(node: object | null | undefined, opts?: object): void; +export function assertEmptyStatement(node: object | null | undefined, opts?: object): void; +export function assertExpressionStatement(node: object | null | undefined, opts?: object): void; +export function assertFile(node: object | null | undefined, opts?: object): void; +export function assertForInStatement(node: object | null | undefined, opts?: object): void; +export function assertForStatement(node: object | null | undefined, opts?: object): void; +export function assertFunctionDeclaration(node: object | null | undefined, opts?: object): void; +export function assertFunctionExpression(node: object | null | undefined, opts?: object): void; +export function assertIdentifier(node: object | null | undefined, opts?: object): void; +export function assertIfStatement(node: object | null | undefined, opts?: object): void; +export function assertLabeledStatement(node: object | null | undefined, opts?: object): void; +export function assertStringLiteral(node: object | null | undefined, opts?: object): void; +export function assertNumericLiteral(node: object | null | undefined, opts?: object): void; +export function assertNullLiteral(node: object | null | undefined, opts?: object): void; +export function assertBooleanLiteral(node: object | null | undefined, opts?: object): void; +export function assertRegExpLiteral(node: object | null | undefined, opts?: object): void; +export function assertLogicalExpression(node: object | null | undefined, opts?: object): void; +export function assertMemberExpression(node: object | null | undefined, opts?: object): void; +export function assertNewExpression(node: object | null | undefined, opts?: object): void; +export function assertProgram(node: object | null | undefined, opts?: object): void; +export function assertObjectExpression(node: object | null | undefined, opts?: object): void; +export function assertObjectMethod(node: object | null | undefined, opts?: object): void; +export function assertObjectProperty(node: object | null | undefined, opts?: object): void; +export function assertRestElement(node: object | null | undefined, opts?: object): void; +export function assertReturnStatement(node: object | null | undefined, opts?: object): void; +export function assertSequenceExpression(node: object | null | undefined, opts?: object): void; +export function assertSwitchCase(node: object | null | undefined, opts?: object): void; +export function assertSwitchStatement(node: object | null | undefined, opts?: object): void; +export function assertThisExpression(node: object | null | undefined, opts?: object): void; +export function assertThrowStatement(node: object | null | undefined, opts?: object): void; +export function assertTryStatement(node: object | null | undefined, opts?: object): void; +export function assertUnaryExpression(node: object | null | undefined, opts?: object): void; +export function assertUpdateExpression(node: object | null | undefined, opts?: object): void; +export function assertVariableDeclaration(node: object | null | undefined, opts?: object): void; +export function assertVariableDeclarator(node: object | null | undefined, opts?: object): void; +export function assertWhileStatement(node: object | null | undefined, opts?: object): void; +export function assertWithStatement(node: object | null | undefined, opts?: object): void; +export function assertAssignmentPattern(node: object | null | undefined, opts?: object): void; +export function assertArrayPattern(node: object | null | undefined, opts?: object): void; +export function assertArrowFunctionExpression(node: object | null | undefined, opts?: object): void; +export function assertClassBody(node: object | null | undefined, opts?: object): void; +export function assertClassDeclaration(node: object | null | undefined, opts?: object): void; +export function assertClassExpression(node: object | null | undefined, opts?: object): void; +export function assertExportAllDeclaration(node: object | null | undefined, opts?: object): void; +export function assertExportDefaultDeclaration(node: object | null | undefined, opts?: object): void; +export function assertExportNamedDeclaration(node: object | null | undefined, opts?: object): void; +export function assertExportSpecifier(node: object | null | undefined, opts?: object): void; +export function assertForOfStatement(node: object | null | undefined, opts?: object): void; +export function assertImportDeclaration(node: object | null | undefined, opts?: object): void; +export function assertImportDefaultSpecifier(node: object | null | undefined, opts?: object): void; +export function assertImportNamespaceSpecifier(node: object | null | undefined, opts?: object): void; +export function assertImportSpecifier(node: object | null | undefined, opts?: object): void; +export function assertMetaProperty(node: object | null | undefined, opts?: object): void; +export function assertClassMethod(node: object | null | undefined, opts?: object): void; +export function assertObjectPattern(node: object | null | undefined, opts?: object): void; +export function assertSpreadElement(node: object | null | undefined, opts?: object): void; +export function assertSuper(node: object | null | undefined, opts?: object): void; +export function assertTaggedTemplateExpression(node: object | null | undefined, opts?: object): void; +export function assertTemplateElement(node: object | null | undefined, opts?: object): void; +export function assertTemplateLiteral(node: object | null | undefined, opts?: object): void; +export function assertYieldExpression(node: object | null | undefined, opts?: object): void; +export function assertAnyTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertArrayTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertBooleanTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertBooleanLiteralTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertNullLiteralTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertClassImplements(node: object | null | undefined, opts?: object): void; +export function assertClassProperty(node: object | null | undefined, opts?: object): void; +export function assertDeclareClass(node: object | null | undefined, opts?: object): void; +export function assertDeclareFunction(node: object | null | undefined, opts?: object): void; +export function assertDeclareInterface(node: object | null | undefined, opts?: object): void; +export function assertDeclareModule(node: object | null | undefined, opts?: object): void; +export function assertDeclareTypeAlias(node: object | null | undefined, opts?: object): void; +export function assertDeclareVariable(node: object | null | undefined, opts?: object): void; +export function assertExistentialTypeParam(node: object | null | undefined, opts?: object): void; +export function assertFunctionTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertFunctionTypeParam(node: object | null | undefined, opts?: object): void; +export function assertGenericTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertInterfaceExtends(node: object | null | undefined, opts?: object): void; +export function assertInterfaceDeclaration(node: object | null | undefined, opts?: object): void; +export function assertIntersectionTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertMixedTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertNullableTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertNumericLiteralTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertNumberTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertStringLiteralTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertStringTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertThisTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertTupleTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertTypeofTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertTypeAlias(node: object | null | undefined, opts?: object): void; +export function assertTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertTypeCastExpression(node: object | null | undefined, opts?: object): void; +export function assertTypeParameter(node: object | null | undefined, opts?: object): void; +export function assertTypeParameterDeclaration(node: object | null | undefined, opts?: object): void; +export function assertTypeParameterInstantiation(node: object | null | undefined, opts?: object): void; +export function assertObjectTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertObjectTypeCallProperty(node: object | null | undefined, opts?: object): void; +export function assertObjectTypeIndexer(node: object | null | undefined, opts?: object): void; +export function assertObjectTypeProperty(node: object | null | undefined, opts?: object): void; +export function assertQualifiedTypeIdentifier(node: object | null | undefined, opts?: object): void; +export function assertUnionTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertVoidTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertJSXAttribute(node: object | null | undefined, opts?: object): void; +export function assertJSXClosingElement(node: object | null | undefined, opts?: object): void; +export function assertJSXElement(node: object | null | undefined, opts?: object): void; +export function assertJSXEmptyExpression(node: object | null | undefined, opts?: object): void; +export function assertJSXExpressionContainer(node: object | null | undefined, opts?: object): void; +export function assertJSXIdentifier(node: object | null | undefined, opts?: object): void; +export function assertJSXMemberExpression(node: object | null | undefined, opts?: object): void; +export function assertJSXNamespacedName(node: object | null | undefined, opts?: object): void; +export function assertJSXOpeningElement(node: object | null | undefined, opts?: object): void; +export function assertJSXSpreadAttribute(node: object | null | undefined, opts?: object): void; +export function assertJSXText(node: object | null | undefined, opts?: object): void; +export function assertNoop(node: object | null | undefined, opts?: object): void; +export function assertParenthesizedExpression(node: object | null | undefined, opts?: object): void; +export function assertAwaitExpression(node: object | null | undefined, opts?: object): void; +export function assertBindExpression(node: object | null | undefined, opts?: object): void; +export function assertDecorator(node: object | null | undefined, opts?: object): void; +export function assertDoExpression(node: object | null | undefined, opts?: object): void; +export function assertExportDefaultSpecifier(node: object | null | undefined, opts?: object): void; +export function assertExportNamespaceSpecifier(node: object | null | undefined, opts?: object): void; +export function assertRestProperty(node: object | null | undefined, opts?: object): void; +export function assertSpreadProperty(node: object | null | undefined, opts?: object): void; +export function assertExpression(node: object | null | undefined, opts?: object): void; +export function assertBinary(node: object | null | undefined, opts?: object): void; +export function assertScopable(node: object | null | undefined, opts?: object): void; +export function assertBlockParent(node: object | null | undefined, opts?: object): void; +export function assertBlock(node: object | null | undefined, opts?: object): void; +export function assertStatement(node: object | null | undefined, opts?: object): void; +export function assertTerminatorless(node: object | null | undefined, opts?: object): void; +export function assertCompletionStatement(node: object | null | undefined, opts?: object): void; +export function assertConditional(node: object | null | undefined, opts?: object): void; +export function assertLoop(node: object | null | undefined, opts?: object): void; +export function assertWhile(node: object | null | undefined, opts?: object): void; +export function assertExpressionWrapper(node: object | null | undefined, opts?: object): void; +export function assertFor(node: object | null | undefined, opts?: object): void; +export function assertForXStatement(node: object | null | undefined, opts?: object): void; +export function assertFunction(node: object | null | undefined, opts?: object): void; +export function assertFunctionParent(node: object | null | undefined, opts?: object): void; +export function assertPureish(node: object | null | undefined, opts?: object): void; +export function assertDeclaration(node: object | null | undefined, opts?: object): void; +export function assertLVal(node: object | null | undefined, opts?: object): void; +export function assertLiteral(node: object | null | undefined, opts?: object): void; +export function assertImmutable(node: object | null | undefined, opts?: object): void; +export function assertUserWhitespacable(node: object | null | undefined, opts?: object): void; +export function assertMethod(node: object | null | undefined, opts?: object): void; +export function assertObjectMember(node: object | null | undefined, opts?: object): void; +export function assertProperty(node: object | null | undefined, opts?: object): void; +export function assertUnaryLike(node: object | null | undefined, opts?: object): void; +export function assertPattern(node: object | null | undefined, opts?: object): void; +export function assertClass(node: object | null | undefined, opts?: object): void; +export function assertModuleDeclaration(node: object | null | undefined, opts?: object): void; +export function assertExportDeclaration(node: object | null | undefined, opts?: object): void; +export function assertModuleSpecifier(node: object | null | undefined, opts?: object): void; +export function assertFlow(node: object | null | undefined, opts?: object): void; +export function assertFlowBaseAnnotation(node: object | null | undefined, opts?: object): void; +export function assertFlowDeclaration(node: object | null | undefined, opts?: object): void; +export function assertJSX(node: object | null | undefined, opts?: object): void; +export function assertNumberLiteral(node: object | null | undefined, opts?: object): void; +export function assertRegexLiteral(node: object | null | undefined, opts?: object): void; -export function assertTSAnyKeyword(node: object, opts?: object): void; -export function assertTSArrayType(node: object, opts?: object): void; -export function assertTSAsExpression(node: object, opts?: object): void; -export function assertTSBooleanKeyword(node: object, opts?: object): void; -export function assertTSCallSignatureDeclaration(node: object, opts?: object): void; -export function assertTSConstructSignatureDeclaration(node: object, opts?: object): void; -export function assertTSConstructorType(node: object, opts?: object): void; -export function assertTSDeclareFunction(node: object, opts?: object): void; -export function assertTSDeclareMethod(node: object, opts?: object): void; -export function assertTSEnumDeclaration(node: object, opts?: object): void; -export function assertTSEnumMember(node: object, opts?: object): void; -export function assertTSExportAssignment(node: object, opts?: object): void; -export function assertTSExpressionWithTypeArguments(node: object, opts?: object): void; -export function assertTSExternalModuleReference(node: object, opts?: object): void; -export function assertTSFunctionType(node: object, opts?: object): void; -export function assertTSImportEqualsDeclaration(node: object, opts?: object): void; -export function assertTSIndexSignature(node: object, opts?: object): void; -export function assertTSIndexedAccessType(node: object, opts?: object): void; -export function assertTSInterfaceBody(node: object, opts?: object): void; -export function assertTSInterfaceDeclaration(node: object, opts?: object): void; -export function assertTSIntersectionType(node: object, opts?: object): void; -export function assertTSLiteralType(node: object, opts?: object): void; -export function assertTSMappedType(node: object, opts?: object): void; -export function assertTSMethodSignature(node: object, opts?: object): void; -export function assertTSModuleBlock(node: object, opts?: object): void; -export function assertTSModuleDeclaration(node: object, opts?: object): void; -export function assertTSNamespaceExportDeclaration(node: object, opts?: object): void; -export function assertTSNeverKeyword(node: object, opts?: object): void; -export function assertTSNonNullExpression(node: object, opts?: object): void; -export function assertTSNullKeyword(node: object, opts?: object): void; -export function assertTSNumberKeyword(node: object, opts?: object): void; -export function assertTSObjectKeyword(node: object, opts?: object): void; -export function assertTSParameterProperty(node: object, opts?: object): void; -export function assertTSParenthesizedType(node: object, opts?: object): void; -export function assertTSPropertySignature(node: object, opts?: object): void; -export function assertTSQualifiedName(node: object, opts?: object): void; -export function assertTSStringKeyword(node: object, opts?: object): void; -export function assertTSSymbolKeyword(node: object, opts?: object): void; -export function assertTSThisType(node: object, opts?: object): void; -export function assertTSTupleType(node: object, opts?: object): void; -export function assertTSTypeAliasDeclaration(node: object, opts?: object): void; -export function assertTSTypeAnnotation(node: object, opts?: object): void; -export function assertTSTypeAssertion(node: object, opts?: object): void; -export function assertTSTypeLiteral(node: object, opts?: object): void; -export function assertTSTypeOperator(node: object, opts?: object): void; -export function assertTSTypeParameter(node: object, opts?: object): void; -export function assertTSTypeParameterDeclaration(node: object, opts?: object): void; -export function assertTSTypeParameterInstantiation(node: object, opts?: object): void; -export function assertTSTypePredicate(node: object, opts?: object): void; -export function assertTSTypeQuery(node: object, opts?: object): void; -export function assertTSTypeReference(node: object, opts?: object): void; -export function assertTSUndefinedKeyword(node: object, opts?: object): void; -export function assertTSUnionType(node: object, opts?: object): void; -export function assertTSVoidKeyword(node: object, opts?: object): void; +export function assertTSAnyKeyword(node: object | null | undefined, opts?: object): void; +export function assertTSArrayType(node: object | null | undefined, opts?: object): void; +export function assertTSAsExpression(node: object | null | undefined, opts?: object): void; +export function assertTSBooleanKeyword(node: object | null | undefined, opts?: object): void; +export function assertTSCallSignatureDeclaration(node: object | null | undefined, opts?: object): void; +export function assertTSConstructSignatureDeclaration(node: object | null | undefined, opts?: object): void; +export function assertTSConstructorType(node: object | null | undefined, opts?: object): void; +export function assertTSDeclareFunction(node: object | null | undefined, opts?: object): void; +export function assertTSDeclareMethod(node: object | null | undefined, opts?: object): void; +export function assertTSEnumDeclaration(node: object | null | undefined, opts?: object): void; +export function assertTSEnumMember(node: object | null | undefined, opts?: object): void; +export function assertTSExportAssignment(node: object | null | undefined, opts?: object): void; +export function assertTSExpressionWithTypeArguments(node: object | null | undefined, opts?: object): void; +export function assertTSExternalModuleReference(node: object | null | undefined, opts?: object): void; +export function assertTSFunctionType(node: object | null | undefined, opts?: object): void; +export function assertTSImportEqualsDeclaration(node: object | null | undefined, opts?: object): void; +export function assertTSIndexSignature(node: object | null | undefined, opts?: object): void; +export function assertTSIndexedAccessType(node: object | null | undefined, opts?: object): void; +export function assertTSInterfaceBody(node: object | null | undefined, opts?: object): void; +export function assertTSInterfaceDeclaration(node: object | null | undefined, opts?: object): void; +export function assertTSIntersectionType(node: object | null | undefined, opts?: object): void; +export function assertTSLiteralType(node: object | null | undefined, opts?: object): void; +export function assertTSMappedType(node: object | null | undefined, opts?: object): void; +export function assertTSMethodSignature(node: object | null | undefined, opts?: object): void; +export function assertTSModuleBlock(node: object | null | undefined, opts?: object): void; +export function assertTSModuleDeclaration(node: object | null | undefined, opts?: object): void; +export function assertTSNamespaceExportDeclaration(node: object | null | undefined, opts?: object): void; +export function assertTSNeverKeyword(node: object | null | undefined, opts?: object): void; +export function assertTSNonNullExpression(node: object | null | undefined, opts?: object): void; +export function assertTSNullKeyword(node: object | null | undefined, opts?: object): void; +export function assertTSNumberKeyword(node: object | null | undefined, opts?: object): void; +export function assertTSObjectKeyword(node: object | null | undefined, opts?: object): void; +export function assertTSParameterProperty(node: object | null | undefined, opts?: object): void; +export function assertTSParenthesizedType(node: object | null | undefined, opts?: object): void; +export function assertTSPropertySignature(node: object | null | undefined, opts?: object): void; +export function assertTSQualifiedName(node: object | null | undefined, opts?: object): void; +export function assertTSStringKeyword(node: object | null | undefined, opts?: object): void; +export function assertTSSymbolKeyword(node: object | null | undefined, opts?: object): void; +export function assertTSThisType(node: object | null | undefined, opts?: object): void; +export function assertTSTupleType(node: object | null | undefined, opts?: object): void; +export function assertTSTypeAliasDeclaration(node: object | null | undefined, opts?: object): void; +export function assertTSTypeAnnotation(node: object | null | undefined, opts?: object): void; +export function assertTSTypeAssertion(node: object | null | undefined, opts?: object): void; +export function assertTSTypeLiteral(node: object | null | undefined, opts?: object): void; +export function assertTSTypeOperator(node: object | null | undefined, opts?: object): void; +export function assertTSTypeParameter(node: object | null | undefined, opts?: object): void; +export function assertTSTypeParameterDeclaration(node: object | null | undefined, opts?: object): void; +export function assertTSTypeParameterInstantiation(node: object | null | undefined, opts?: object): void; +export function assertTSTypePredicate(node: object | null | undefined, opts?: object): void; +export function assertTSTypeQuery(node: object | null | undefined, opts?: object): void; +export function assertTSTypeReference(node: object | null | undefined, opts?: object): void; +export function assertTSUndefinedKeyword(node: object | null | undefined, opts?: object): void; +export function assertTSUnionType(node: object | null | undefined, opts?: object): void; +export function assertTSVoidKeyword(node: object | null | undefined, opts?: object): void; diff --git a/types/babel-types/tsconfig.json b/types/babel-types/tsconfig.json index 92d7d6442e..f4a6179f99 100644 --- a/types/babel-types/tsconfig.json +++ b/types/babel-types/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/babel__core/babel__core-tests.ts b/types/babel__core/babel__core-tests.ts index ba51ac21be..b44e45c605 100644 --- a/types/babel__core/babel__core-tests.ts +++ b/types/babel__core/babel__core-tests.ts @@ -39,3 +39,59 @@ babel.transformFromAstAsync(parsedAst!, sourceCode, options).then(transformFromA const { code, map, ast } = transformFromAstAsyncResult!; const { body } = ast!.program; }); + +function checkOptions(_options: babel.TransformOptions) {} +function checkConfigFunction(_config: babel.ConfigFunction) {} + +checkOptions({ envName: 'banana' }); +// babel uses object destructuring default to provide the envName fallback so null is not allowed +// $ExpectError +checkOptions({ envName: null }); +checkOptions({ caller: { name: '@babel/register' } }); +checkOptions({ caller: { name: 'babel-jest', supportsStaticESM: false } }); +// don't add an index signature; users should augment the interface instead if they need to +// $ExpectError +checkOptions({ caller: { name: '', tomato: true } }); +checkOptions({ rootMode: 'upward-optional' }); +// $ExpectError +checkOptions({ rootMode: 'potato' }); + +// $ExpectError +checkConfigFunction(() => {}); +// you technically can do that though you probably shouldn't +checkConfigFunction(() => ({})); +checkConfigFunction(api => { + api.assertVersion(7); + api.assertVersion("^7.2"); + + api.cache.forever(); + api.cache.never(); + api.cache.using(() => true); + api.cache.using(() => 1); + api.cache.using(() => '1'); + api.cache.using(() => null); + api.cache.using(() => undefined); + // $ExpectError + api.cache.using(() => ({})); + api.cache.invalidate(() => 2); + + // $ExpectType string + api.env(); + + api.env('development'); + api.env(['production', 'test']); + // $ExpectType 42 + api.env(name => 42); + + // $ExpectType string + api.version; + + return { + shouldPrintComment(comment) { + // $ExpectType string + comment; + + return true; + } + }; +}); diff --git a/types/babel__core/index.d.ts b/types/babel__core/index.d.ts index 66501d24db..3875d40d71 100644 --- a/types/babel__core/index.d.ts +++ b/types/babel__core/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for @babel/core 7.0 +// Type definitions for @babel/core 7.1 // Project: https://github.com/babel/babel/tree/master/packages/babel-core, https://babeljs.io // Definitions by: Troy Gerwien // Marvin Hagemeister // Melvin Groenhoff +// Jessica Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 @@ -54,6 +55,15 @@ export interface TransformOptions { */ root?: string | null; + /** + * This option, combined with the "root" value, defines how Babel chooses its project root. + * The different modes define different ways that Babel can process the "root" value to get + * the final project root. + * + * @see https://babeljs.io/docs/en/next/options#rootmode + */ + rootMode?: 'root' | 'upward' | 'upward-optional'; + /** * The config file to load Babel's config from. Defaults to searching for "babel.config.js" inside the "root" folder. `false` will disable searching for config files. * @@ -82,7 +92,7 @@ export interface TransformOptions { * * Default: env vars */ - envName?: string | null; + envName?: string; /** * Enable code generation @@ -112,6 +122,14 @@ export interface TransformOptions { */ cwd?: string | null; + /** + * Utilities may pass a caller object to identify themselves to Babel and + * pass capability-related flags for use by configs, presets and plugins. + * + * @see https://babeljs.io/docs/en/next/options#caller + */ + caller?: TransformCaller; + /** * This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { \/* specific options *\/ } } }` * which will use those options when the `envName` is `production` @@ -284,6 +302,14 @@ export interface TransformOptions { wrapPluginVisitorMethod?: ((pluginAlias: string, visitorType: "enter" | "exit", callback: (path: NodePath, state: any) => void) => (path: NodePath, state: any) => void) | null; } +export interface TransformCaller { + // the only required property + name: string; + // e.g. set to true by `babel-loader` and false by `babel-jest` + supportsStaticESM?: boolean; + // augment this with a "declare module '@babel/core' { ... }" if you need more keys +} + export type FileResultCallback = (err: Error | null, result: BabelFileResult | null) => any; /** @@ -528,4 +554,129 @@ export interface CreateConfigItemOptions { */ export function createConfigItem(value: PluginTarget | [PluginTarget, PluginOptions] | [PluginTarget, PluginOptions, string | undefined], options?: CreateConfigItemOptions): ConfigItem; +// NOTE: the documentation says the ConfigAPI also exposes @babel/core's exports, but it actually doesn't +/** + * @see https://babeljs.io/docs/en/next/config-files#config-function-api + */ +export interface ConfigAPI { + /** + * The version string for the Babel version that is loading the config file. + * + * @see https://babeljs.io/docs/en/next/config-files#apiversion + */ + version: string; + /** + * @see https://babeljs.io/docs/en/next/config-files#apicache + */ + cache: SimpleCacheConfigurator; + /** + * @see https://babeljs.io/docs/en/next/config-files#apienv + */ + env: EnvFunction; + // undocumented; currently hardcoded to return 'false' + // async(): boolean + /** + * This API is used as a way to access the `caller` data that has been passed to Babel. + * Since many instances of Babel may be running in the same process with different `caller` values, + * this API is designed to automatically configure `api.cache`, the same way `api.env()` does. + * + * The `caller` value is available as the first parameter of the callback function. + * It is best used with something like this to toggle configuration behavior + * based on a specific environment: + * + * @example + * function isBabelRegister(caller?: { name: string }) { + * return !!(caller && caller.name === "@babel/register") + * } + * api.caller(isBabelRegister) + * + * @see https://babeljs.io/docs/en/next/config-files#apicallercb + */ + caller(callerCallback: (caller: TransformOptions['caller']) => T): T; + /** + * While `api.version` can be useful in general, it's sometimes nice to just declare your version. + * This API exposes a simple way to do that with: + * + * @example + * api.assertVersion(7) // major version only + * api.assertVersion("^7.2") + * + * @see https://babeljs.io/docs/en/next/config-files#apiassertversionrange + */ + assertVersion(versionRange: number | string): boolean; + // NOTE: this is an undocumented reexport from "@babel/parser" but it's missing from its types + // tokTypes: typeof tokTypes +} + +/** + * JS configs are great because they can compute a config on the fly, + * but the downside there is that it makes caching harder. + * Babel wants to avoid re-executing the config function every time a file is compiled, + * because then it would also need to re-execute any plugin and preset functions + * referenced in that config. + * + * To avoid this, Babel expects users of config functions to tell it how to manage caching + * within a config file. + * + * @see https://babeljs.io/docs/en/next/config-files#apicache + */ +export interface SimpleCacheConfigurator { + // there is an undocumented call signature that is a shorthand for forever()/never()/using(). + // (ever: boolean): void + // (callback: CacheCallback): T + /** + * Permacache the computed config and never call the function again. + */ + forever(): void; + /** + * Do not cache this config, and re-execute the function every time. + */ + never(): void; + /** + * Any time the using callback returns a value other than the one that was expected, + * the overall config function will be called again and a new entry will be added to the cache. + * + * @example + * api.cache.using(() => process.env.NODE_ENV) + */ + using(callback: SimpleCacheCallback): T; + /** + * Any time the using callback returns a value other than the one that was expected, + * the overall config function will be called again and all entries in the cache will + * be replaced with the result. + * + * @example + * api.cache.invalidate(() => process.env.NODE_ENV) + */ + invalidate(callback: SimpleCacheCallback): T; +} + +// https://github.com/babel/babel/blob/v7.3.3/packages/babel-core/src/config/caching.js#L231 +export type SimpleCacheKey = string | boolean | number | null | undefined; +export type SimpleCacheCallback = () => T; + +/** + * Since `NODE_ENV` is a fairly common way to toggle behavior, Babel also includes an API function + * meant specifically for that. This API is used as a quick way to check the `"envName"` that Babel + * was loaded with, which takes `NODE_ENV` into account if no other overriding environment is set. + * + * @see https://babeljs.io/docs/en/next/config-files#apienv + */ +export interface EnvFunction { + /** + * @returns the current `envName` string + */ + (): string; + /** + * @returns `true` if the `envName` is `===` any of the given strings + */ + (envName: string | ReadonlyArray): boolean; + // the official documentation is misleading for this one... + // this just passes the callback to `cache.using` but with an additional argument. + // it returns its result instead of necessarily returning a boolean. + (envCallback: (envName: NonNullable) => T): T; +} + +export type ConfigFunction = (api: ConfigAPI) => TransformOptions; + export as namespace babel; diff --git a/types/baidu-app/index.d.ts b/types/baidu-app/index.d.ts index ff71f9c012..ea9454d471 100644 --- a/types/baidu-app/index.d.ts +++ b/types/baidu-app/index.d.ts @@ -4287,7 +4287,7 @@ declare namespace swan { Methods, Props > = object & - ComponentOptions Data), Methods, Props> & + ComponentOptions & ThisType>>; interface ComponentRelation { diff --git a/types/bit-twiddle/bit-twiddle-tests.ts b/types/bit-twiddle/bit-twiddle-tests.ts new file mode 100644 index 0000000000..6f2f155c3b --- /dev/null +++ b/types/bit-twiddle/bit-twiddle-tests.ts @@ -0,0 +1,23 @@ +import * as bitTwiddle from "bit-twiddle"; + +bitTwiddle.INT_BITS; +bitTwiddle.INT_MAX; +bitTwiddle.INT_MIN; + +bitTwiddle.sign(5); +bitTwiddle.abs(-5); +bitTwiddle.min(1, 6); +bitTwiddle.max(6, 1); +bitTwiddle.isPow2(3); +bitTwiddle.log2(3); +bitTwiddle.log10(3); +bitTwiddle.popCount(4); +bitTwiddle.countTrailingZeros(3.0000003); +bitTwiddle.nextPow2(31.315); +bitTwiddle.prevPow2(31.315); +bitTwiddle.parity(123); +bitTwiddle.interleave2(12, 24); +bitTwiddle.deinterleave2(24, 12); +bitTwiddle.interleave3(24, 12, 6); +bitTwiddle.deinterleave3(24, 12); +bitTwiddle.nextCombination(41.935); diff --git a/types/bit-twiddle/index.d.ts b/types/bit-twiddle/index.d.ts new file mode 100644 index 0000000000..e89e9500b0 --- /dev/null +++ b/types/bit-twiddle/index.d.ts @@ -0,0 +1,101 @@ +// Type definitions for bit-twiddle 1.0 +// Project: https://github.com/mikolalysenko/bit-twiddle +// Definitions by: Adam Zerella +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.3 + +export const INT_BITS: number; +export const INT_MAX: number; +export const INT_MIN: number; + +/** + * Computes the sign of the integer. + */ +export function sign(value: number): number; + +/** + * Returns the absolute value of the integer. + */ +export function abs(value: number): number; + +/** + * Computes the minimum of integers x and y. + */ +export function min(x: number, y: number): number; + +/** + * Computes the maximum of integers x and y. + */ +export function max(x: number, y: number): number; + +/** + * Returns true if value is a power of 2, otherwise false. + */ +export function isPow2(value: number): boolean; + +/** + * Returns an integer approximation of the log-base 2 of value. + */ +export function log2(value: number): number; + +/** + * Returns an integer approximation of the log-base 10 of value. + */ +export function log10(value: number): number; + +/** + * Counts the number of bits set in value. + */ +export function popCount(value: number): number; + +/** + * Counts the number of trailing zeros. + */ +export function countTrailingZeros(value: number): number; + +/** + * Rounds value up to the next power of 2. + */ +export function nextPow2(value: number): number; + +/** + * Rounds value down to the previous power of 2. + */ +export function prevPow2(value: number): number; + +/** + * Computes the parity of the bits in value. + */ +export function parity(value: number): number; + +/** + * Reverses the bits of value. + */ +export function reverse(value: number): number; + +/** + * Interleaves a pair of 16 bit integers. Useful for fast quadtree style indexing. + * @see http://en.wikipedia.org/wiki/Z-order_curve + */ +export function interleave2(x: number, y: number): number; + +/** + * Deinterleaves the bits of value, returns the nth part. + * If both x and y are 16 bit. + */ +export function deinterleave2(x: number, y: number): number; + +/** + * Interleaves a triple of 10 bit integers. Useful for fast octree indexing. + */ +export function interleave3(x: number, y: number, z: number): number; + +/** + * Same deal as deinterleave2, only for triples instead of pairs. + */ +export function deinterleave3(x: number, y: number): number; + +/** + * Returns next combination ordered colexicographically. + */ +export function nextCombination(x: number): number; diff --git a/types/bit-twiddle/tsconfig.json b/types/bit-twiddle/tsconfig.json new file mode 100644 index 0000000000..f1b094fd42 --- /dev/null +++ b/types/bit-twiddle/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [ + + ], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bit-twiddle-tests.ts" + ] +} diff --git a/types/bit-twiddle/tslint.json b/types/bit-twiddle/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/bit-twiddle/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/bluebird-global/index.d.ts b/types/bluebird-global/index.d.ts index da33188dd1..8924a941df 100644 --- a/types/bluebird-global/index.d.ts +++ b/types/bluebird-global/index.d.ts @@ -113,12 +113,15 @@ import Bluebird = require("bluebird"); declare global { + type IterateFunction = (item: T, index: number, arrayLength: number) => (R | PromiseLike); /* * Patch all instance method */ interface Promise { - all: Bluebird["all"]; - any: Bluebird["any"]; + all(this: Promise>): Bluebird; + all(): Bluebird; + any(this: Promise>): Bluebird; + any(): Bluebird; asCallback: Bluebird["asCallback"]; bind: Bluebird["bind"]; call: Bluebird["call"]; @@ -128,9 +131,9 @@ declare global { delay: Bluebird["delay"]; disposer: Bluebird["disposer"]; done: Bluebird["done"]; - each: Bluebird["each"]; + each(this: Promise>, iterator: IterateFunction): Bluebird; error: Bluebird["error"]; - filter: Bluebird["filter"]; + filter(this: Promise>, filterer: IterateFunction, options?: Bluebird.ConcurrencyOption): Bluebird; // finally: Bluebird["finally"]; // Provided by lib.es2018.promise.d.ts get: Bluebird["get"]; isCancelled: Bluebird["isCancelled"]; @@ -139,17 +142,18 @@ declare global { isRejected: Bluebird["isRejected"]; isResolved: Bluebird["isResolved"]; lastly: Bluebird["lastly"]; - map: Bluebird["map"]; - mapSeries: Bluebird["mapSeries"]; + map(this: Promise>, mapper: IterateFunction, options?: Bluebird.ConcurrencyOption): Bluebird; + mapSeries(this: Promise>, iterator: IterateFunction): Bluebird; nodeify: Bluebird["nodeify"]; props: Bluebird["props"]; - race: Bluebird["race"]; + race(this: Promise>): Bluebird; + race(): Bluebird; reason: Bluebird["reason"]; - reduce: Bluebird["reduce"]; + reduce(this: Promise>, reducer: (memo: U, item: Q, index: number, arrayLength: number) => (U | PromiseLike), initialValue?: U): Bluebird; reflect: Bluebird["reflect"]; return: Bluebird["return"]; - some: Bluebird["some"]; - spread: Bluebird["spread"]; + some(this: Promise>, count: number): Bluebird; + spread(this: Bluebird>, fulfilledHandler: (...values: Q[]) => (U | PromiseLike)): Bluebird; suppressUnhandledRejections: Bluebird["suppressUnhandledRejections"]; tap: Bluebird["tap"]; tapCatch: Bluebird["tapCatch"]; diff --git a/types/bluebird/index.d.ts b/types/bluebird/index.d.ts index 24c2b79a32..13a11c2e3e 100644 --- a/types/bluebird/index.d.ts +++ b/types/bluebird/index.d.ts @@ -37,8 +37,6 @@ type Constructor = new (...args: any[]) => E; type CatchFilter = ((error: E) => boolean) | (object & E); -type IterableItem = R extends Iterable ? U : never; -type IterableOrNever = Extract>; type Resolvable = R | PromiseLike; type IterateFunction = (item: T, index: number, arrayLength: number) => Resolvable; @@ -352,7 +350,7 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { * }); * */ - call(propertyName: U, ...args: any[]): Bluebird any ? ReturnType : never>; + call(this: Bluebird, propertyName: U, ...args: any[]): Bluebird any ? ReturnType : never>; /** * This is a convenience method for doing: @@ -562,12 +560,17 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { /** * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. */ - spread(fulfilledHandler: (...values: Array>) => Resolvable): Bluebird; + spread(this: Bluebird>, fulfilledHandler: (...values: Q[]) => Resolvable): Bluebird; /** * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - all(): Bluebird>; + all(this: Bluebird>): Bluebird; + + /** + * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + all(): Bluebird; /** * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. @@ -578,42 +581,59 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { /** * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - any(): Bluebird>; + any(this: Bluebird>): Bluebird; + + /** + * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + any(): Bluebird; /** + * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - some(count: number): Bluebird>; + some(this: Bluebird>, count: number): Bluebird; + + /** + * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + some(count: number): Bluebird; /** * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - race(): Bluebird>; + race(this: Bluebird>): Bluebird; + + /** + * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + race(): Bluebird; /** * Same as calling `Bluebird.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - map(mapper: IterateFunction, U>, options?: Bluebird.ConcurrencyOption): Bluebird ? U[] : never>; + map(this: Bluebird>, mapper: IterateFunction, options?: Bluebird.ConcurrencyOption): Bluebird; /** * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - reduce(reducer: (memo: U, item: IterableItem, index: number, arrayLength: number) => Resolvable, initialValue?: U): Bluebird ? U : never>; + reduce(this: Bluebird>, reducer: (memo: U, item: Q, index: number, arrayLength: number) => Resolvable, initialValue?: U): Bluebird; /** * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - filter(filterer: IterateFunction, boolean>, options?: Bluebird.ConcurrencyOption): Bluebird>; + filter(this: Bluebird>, filterer: IterateFunction, options?: Bluebird.ConcurrencyOption): Bluebird; /** * Same as calling ``Bluebird.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - each(iterator: IterateFunction, any>): Bluebird>; + each(this: Bluebird>, iterator: IterateFunction): Bluebird; /** * Same as calling ``Bluebird.mapSeries(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - mapSeries(iterator: IterateFunction, U>): Bluebird ? U[] : never>; + mapSeries(this: Bluebird>, iterator: IterateFunction): Bluebird; /** * Cancel this `promise`. Will not do anything if this promise is already settled or if the cancellation feature has not been enabled diff --git a/types/camljs/camljs-tests.ts b/types/camljs/camljs-tests.ts index 12afd10fbb..034949175c 100644 --- a/types/camljs/camljs-tests.ts +++ b/types/camljs/camljs-tests.ts @@ -1,4 +1,4 @@ - +import CamlBuilder from 'camljs' var caml = new CamlBuilder().Where() .Any( @@ -53,3 +53,37 @@ caml = CamlBuilder.Expression() .ToString(); caml = new CamlBuilder().Where().DateTimeField("Created").GreaterThan(new Date(Date.UTC(2013,0,1))).ToString(); + +// Aggregations and extended syntax of GroupBy +var query = new CamlBuilder() + .View(["Category", { count: "ID" }, { sum: "Amount" }]) + .Query() + .GroupBy("Category", true, 100) + .ToString(); + +// ContentTypeId field +var query = new CamlBuilder() + .Where() + .TextField("Title").EqualTo("Document") + .And() + .ContentTypeIdField().BeginsWith("0x101") + .ToString(); + +// joins +var query = new CamlBuilder() + .View(["Title", "Country", "Population"]) + .LeftJoin("Country", "Country").Select("y4r6", "Population") + .Query() + .Where() + .NumberField("Population").LessThan(10) + .ToString(); + +// RowLimit & Scope +var camlBuilder1 = new CamlBuilder() + .View(["ID", "Created"]) + .RowLimit(20, true) + .Scope(CamlBuilder.ViewScope.RecursiveAll) + .Query() + .Where() + .TextField("Title").BeginsWith("A") + .ToString(); diff --git a/types/camljs/index.d.ts b/types/camljs/index.d.ts index 73bbe03767..b8f4021ded 100644 --- a/types/camljs/index.d.ts +++ b/types/camljs/index.d.ts @@ -1,8 +1,8 @@ // Type definitions for camljs -// Project: http://camljs.codeplex.com -// Definitions by: Andrey Markeev +// Project: https://github.com/andrei-markeev/camljs +// Definitions by: Andrey Markeev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.7 declare class CamlBuilder { constructor(); @@ -10,25 +10,43 @@ declare class CamlBuilder { Where(): CamlBuilder.IFieldExpression; /** Generate tag for SP.CamlQuery @param viewFields If omitted, default view fields are requested; otherwise, only values for the fields with the specified internal names are returned. - Specifying view fields is a good practice, as it decreases traffic between server and client. */ - View(viewFields?: string[]): CamlBuilder.IView; + Specifying view fields is a good practice, as it decreases traffic between server and client. + Additionally you can specify aggregated fields, e.g. { count: "" }, { sum: "" }, etc.. */ + View(viewFields?: CamlBuilder.ViewField[]): CamlBuilder.IView; /** Generate tag for SPServices */ ViewFields(viewFields: string[]): CamlBuilder.IFinalizableToString; /** Use for: 1. SPServices CAMLQuery attribute 2. Creating partial expressions 3. In conjunction with Any & All clauses - */ + */ static Expression(): CamlBuilder.IFieldExpression; static FromXml(xml: string): CamlBuilder.IRawQuery; } -declare namespace CamlBuilder { - interface IView extends IJoinable, IFinalizable { +declare module CamlBuilder { + type Aggregation = { + count: string; + } | { + sum: string; + } | { + avg: string; + } | { + max: string; + } | { + min: string; + } | { + stdev: string; + } | { + var: string; + }; + type ViewField = string | Aggregation; + interface IView extends IFinalizable { + /** Define query */ Query(): IQuery; + /** Define maximum amount of returned records */ RowLimit(limit: number, paged?: boolean): IView; + /** Define view scope */ Scope(scope: ViewScope): IView; - } - interface IJoinable { /** Join the list you're querying with another list. Joins are only allowed through a lookup field relation. @param lookupFieldInternalName Internal name of the lookup field, that points to the list you're going to join in. @@ -40,22 +58,39 @@ declare namespace CamlBuilder { @alias alias for the joined list */ LeftJoin(lookupFieldInternalName: string, alias: string): IJoin; } + interface IJoinable { + /** Join the list you're querying with another list. + Joins are only allowed through a lookup field relation. + @param lookupFieldInternalName Internal name of the lookup field, that points to the list you're going to join in. + @param alias Alias for the joined list + @param fromList (optional) List where the lookup column resides - use it only for nested joins */ + InnerJoin(lookupFieldInternalName: string, alias: string, fromList?: string): IJoin; + /** Join the list you're querying with another list. + Joins are only allowed through a lookup field relation. + @param lookupFieldInternalName Internal name of the lookup field, that points to the list you're going to join in. + @param alias Alias for the joined list + @param fromList (optional) List where the lookup column resides - use it only for nested joins */ + LeftJoin(lookupFieldInternalName: string, alias: string, fromList?: string): IJoin; + } interface IJoin extends IJoinable { /** Select projected field for using in the main Query body @param remoteFieldAlias By this alias, the field can be used in the main Query body. */ Select(remoteFieldInternalName: string, remoteFieldAlias: string): IProjectableView; } - interface IProjectableView extends IView { + interface IProjectableView extends IJoinable { + /** Define query */ + Query(): IQuery; + /** Define maximum amount of returned records */ + RowLimit(limit: number, paged?: boolean): IView; + /** Define view scope */ + Scope(scope: ViewScope): IView; /** Select projected field for using in the main Query body @param remoteFieldAlias By this alias, the field can be used in the main Query body. */ Select(remoteFieldInternalName: string, remoteFieldAlias: string): IProjectableView; } enum ViewScope { - /** */ Recursive = 0, - /** */ RecursiveAll = 1, - /** */ FilesOnly = 2, } interface IQuery extends IGroupable { @@ -85,8 +120,9 @@ declare namespace CamlBuilder { } interface IGroupable extends ISortable { /** Adds GroupBy clause to the query. - @param collapse If true, only information about the groups is retrieved, otherwise items are also retrieved. */ - GroupBy(fieldInternalName: any): IGroupedQuery; + @param collapse If true, only information about the groups is retrieved, otherwise items are also retrieved. + @param groupLimit Return only first N groups */ + GroupBy(fieldInternalName: any, collapse?: boolean, groupLimit?: number): IGroupedQuery; } interface IExpression extends IGroupable { /** Adds And clause to the query. */ @@ -113,6 +149,12 @@ declare namespace CamlBuilder { Any(conditions: IExpression[]): IExpression; /** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Text */ TextField(internalName: string): ITextFieldExpression; + /** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is ContentTypeId */ + ContentTypeIdField(internalName?: string): ITextFieldExpression; + /** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Choice */ + ChoiceField(internalName: string): ITextFieldExpression; + /** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Computed */ + ComputedField(internalName: string): ITextFieldExpression; /** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is Boolean */ BooleanField(internalName: string): IBooleanFieldExpression; /** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is URL */ @@ -360,7 +402,7 @@ declare namespace CamlBuilder { Year = 4, } class Internal { - static createView(viewFields?: string[]): IView; + static createView(viewFields?: ViewField[]): IView; static createViewFields(viewFields: string[]): IFinalizableToString; static createWhere(): IFieldExpression; static createExpression(): IFieldExpression; @@ -401,3 +443,4 @@ declare namespace CamlBuilder { }; } } +export = CamlBuilder; diff --git a/types/camljs/tsconfig.json b/types/camljs/tsconfig.json index 5fbe5605e9..ed88508fc3 100644 --- a/types/camljs/tsconfig.json +++ b/types/camljs/tsconfig.json @@ -14,7 +14,8 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true }, "files": [ "index.d.ts", diff --git a/types/canvas-confetti/canvas-confetti-tests.ts b/types/canvas-confetti/canvas-confetti-tests.ts index d29e57fbdb..2415b91b85 100644 --- a/types/canvas-confetti/canvas-confetti-tests.ts +++ b/types/canvas-confetti/canvas-confetti-tests.ts @@ -43,3 +43,12 @@ confetti({ y: 0.6 } }); + +const canvas = document.createElement('canvas'); +const myConfetti = confetti.create(canvas); + +myConfetti(); + +myConfetti({ + particleCount: 150 +}); diff --git a/types/canvas-confetti/index.d.ts b/types/canvas-confetti/index.d.ts index 3dddc6d750..f9dd65ea12 100644 --- a/types/canvas-confetti/index.d.ts +++ b/types/canvas-confetti/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for canvas-confetti 0.0 +// Type definitions for canvas-confetti 0.1 // Project: https://github.com/catdad/canvas-confetti#readme // Definitions by: Martin Tracey // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -81,6 +81,14 @@ declare namespace confetti { */ y?: number; } + interface GlobalOptions { + resize: boolean; + } + + function create( + canvas: HTMLCanvasElement, + options?: GlobalOptions + ): (options?: Options) => Promise | null; } export = confetti; diff --git a/types/canvas-confetti/tsconfig.json b/types/canvas-confetti/tsconfig.json index 33c159b3e3..e83fb2ef8b 100644 --- a/types/canvas-confetti/tsconfig.json +++ b/types/canvas-confetti/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 86073ec888..21b6f9d8d1 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -87,7 +87,8 @@ export namespace policies { interface DecisionInfo { decision: number; - consistency: number; + consistency?: number; + useCurrentHost?: boolean; } interface RequestInfo { @@ -115,8 +116,8 @@ export namespace policies { onReadTimeout(requestInfo: RequestInfo, consistency: types.consistencies, received: number, blockFor: number, isDataPresent: boolean): DecisionInfo; onUnavailable(requestInfo: RequestInfo, consistency: types.consistencies, required: number, alive: number): DecisionInfo; onWriteTimeout(requestInfo: RequestInfo, consistency: types.consistencies, received: number, blockFor: number, writeType: string): DecisionInfo; - rethrowResult(): { decision: retryDecision }; - retryResult(consistency?: types.consistencies, useCurrentHost?: boolean): { decision: retryDecision, consistency: types.consistencies, useCurrentHost: boolean }; + rethrowResult(): DecisionInfo; + retryResult(consistency?: types.consistencies, useCurrentHost?: boolean): DecisionInfo; } } diff --git a/types/chai-enzyme/index.d.ts b/types/chai-enzyme/index.d.ts index 783b7fce2f..b238b194c5 100644 --- a/types/chai-enzyme/index.d.ts +++ b/types/chai-enzyme/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/producthunt/chai-enzyme // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.1 /// diff --git a/types/chromecast-caf-receiver/cast.framework.messages.d.ts b/types/chromecast-caf-receiver/cast.framework.messages.d.ts index 1846fd4840..b6e66ff4db 100644 --- a/types/chromecast-caf-receiver/cast.framework.messages.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.messages.d.ts @@ -1441,6 +1441,12 @@ export interface MediaInformation { * The media tracks. */ tracks?: Track[]; + + /** + * VMAP ad request configuration. Used if breaks and breakClips are not + * provided. + */ + vmapAdsRequest?: VastAdsRequest; } /** diff --git a/types/commercetools__enzyme-extensions/index.d.ts b/types/commercetools__enzyme-extensions/index.d.ts index 7c009f8e95..cf7362f0e9 100644 --- a/types/commercetools__enzyme-extensions/index.d.ts +++ b/types/commercetools__enzyme-extensions/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/commercetools/enzyme-extensions // Definitions by: Christian Rackerseder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.1 import * as enzyme from 'enzyme'; diff --git a/types/connect-datadog/index.d.ts b/types/connect-datadog/index.d.ts index c3aad8aac7..df18c0c208 100644 --- a/types/connect-datadog/index.d.ts +++ b/types/connect-datadog/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for connect-datadog 0.0 -// Project: https://github.com/AppPress/node-connect-datadog +// Project: https://github.com/datadog/node-connect-datadog // Definitions by: Moshe Good // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 diff --git a/types/cordova-sqlite-storage/index.d.ts b/types/cordova-sqlite-storage/index.d.ts index 6ba48b08d2..02d63be0c3 100644 --- a/types/cordova-sqlite-storage/index.d.ts +++ b/types/cordova-sqlite-storage/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for cordova-sqlite-storage 1.5 -// Project: https://github.com/litehelpers/Cordova-sqlite-storage +// Project: https://github.com/xpbrew/cordova-sqlite-storage // Definitions by: rafw87 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/cote/cote-tests.ts b/types/cote/cote-tests.ts index 1851654625..d4af3ce95e 100644 --- a/types/cote/cote-tests.ts +++ b/types/cote/cote-tests.ts @@ -35,6 +35,7 @@ class Readme { }); const req = { + __subset: 'subset', type: 'randomRequest', payload: { val: Math.floor(Math.random() * 10) @@ -52,7 +53,8 @@ class Readme { name: 'Random Responder', namespace: 'rnd', key: 'a certain key', - respondsTo: ['randomRequest'] + respondsTo: ['randomRequest'], + subset: 'subset' }); interface RandomRequest { diff --git a/types/cote/index.d.ts b/types/cote/index.d.ts index 4c959af76b..93f5b7d63f 100644 --- a/types/cote/index.d.ts +++ b/types/cote/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cote 0.17 +// Type definitions for cote 0.19 // Project: https://github.com/dashersw/cote#readme // Definitions by: makepost // Labat Robin @@ -115,6 +115,11 @@ export interface ResponderAdvertisement extends Advertisement { * Request types that a Responder can listen to. */ respondsTo?: string[]; + + /** + * Advertisement attribute that lets you target a subgroup of responders using the __subset property of a request. + */ + subset?: string; } export class Publisher extends Component { diff --git a/types/cron/cron-tests.ts b/types/cron/cron-tests.ts index 21e28f9c0f..d146fe6a61 100644 --- a/types/cron/cron-tests.ts +++ b/types/cron/cron-tests.ts @@ -1,5 +1,7 @@ import cron = require('cron'); +import moment = require('moment'); + var CronJob = cron.CronJob; var CronTime = cron.CronTime; @@ -34,6 +36,16 @@ var job = new CronJob(new Date(), () => { timeZone /* Time zone of this job. */ ); +// Another example with Moment +var job = new CronJob(moment(), () => { + /* runs once at the specified moment. */ + }, () => { + /* This function is executed when the job stops */ + }, + true, /* Start the job right now */ + timeZone /* Time zone of this job. */ +); + // For good measure var job = new CronJob({ cronTime: '00 30 11 * * 1-5', @@ -48,7 +60,8 @@ var job = new CronJob({ timeZone: 'America/Los_Angeles' }); console.log(job.lastDate()); -console.log(job.nextDates(1)); +console.log(job.nextDates());// Should be a Moment object +console.log(job.nextDates(1));// Should be an array of Moment object console.log(job.running); job.setTime(new CronTime('00 30 11 * * 1-2')); job.start(); @@ -67,4 +80,5 @@ try { // Check cronTime fomat new CronTime('* * * * * *'); new CronTime(new Date()); +new CronTime(moment()); diff --git a/types/cron/index.d.ts b/types/cron/index.d.ts index 596a9536ca..b508c0d1fd 100644 --- a/types/cron/index.d.ts +++ b/types/cron/index.d.ts @@ -4,6 +4,8 @@ // Lundarl Gholoi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import { Moment } from 'moment'; + export declare class CronTime { /** * Create a new ```CronTime```. @@ -11,13 +13,14 @@ export declare class CronTime { * @param zone Timezone name. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). * @param utcOffset UTC offset. Don't use both ```zone``` and ```utcOffset``` together or weird things may happen. */ - constructor(source: string | Date, zone?: string, utcOffset?: string | number); + constructor(source: string | Date | Moment, zone?: string, utcOffset?: string | number); /** * Tells you when ```CronTime``` will be run. * @param i Indicate which turn of run after now. If not given return next run time. */ - public sendAt(i?: number): Date; + public sendAt(): Moment; + public sendAt(i?: number): Moment[]; /** * Get the number of milliseconds in the future at which to fire our callbacks. */ @@ -28,7 +31,7 @@ export declare interface CronJobParameters { /** * The time to fire off your job. This can be in the form of cron syntax or a JS ```Date``` object. */ - cronTime: string | Date; + cronTime: string | Date | Moment; /** * The function to fire at the specified time. If an ```onComplete``` callback was provided, ```onTick``` will receive it as an argument. ```onTick``` may call ```onComplete``` when it has finished its work. */ @@ -85,7 +88,7 @@ export declare class CronJob { * @param utcOffset This allows you to specify the offset of your timezone rather than using the ```timeZone``` param. Probably don't use both ```timeZone``` and ```utcOffset``` together or weird things may happen. * @param unrefTimeout If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at [timers#timers_timeout_unref](https://nodejs.org/api/timers.html#timers_timeout_unref) from the NodeJS docs. */ - constructor(cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean); + constructor(cronTime: string | Date | Moment, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean); /** * Create a new ```CronJob```. * @param options Job parameters. @@ -113,7 +116,8 @@ export declare class CronJob { * Tells you when a ```CronTime``` will be run. * @param i Indicate which turn of run after now. If not given return next run time. */ - public nextDates(i?: number): Date; + public nextDates(): Moment; + public nextDates(i?: number): Moment[]; /** * Add another ```onTick``` function. * @param callback Target function. @@ -122,8 +126,8 @@ export declare class CronJob { } export declare var job: - ((cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean) => CronJob) + ((cronTime: string | Date | Moment, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean) => CronJob) | ((options: CronJobParameters) => CronJob); -export declare var time: (source: string | Date, zone?: string) => CronTime; -export declare var sendAt: (cronTime: CronTime) => Date; -export declare var timeout: (cronTime: CronTime) => number; +export declare var time: (source: string | Date | Moment, zone?: string) => CronTime; +export declare var sendAt: (cronTime: string | Date | Moment) => Moment; +export declare var timeout: (cronTime: string | Date | Moment) => number; diff --git a/types/dd-trace/package.json b/types/cron/package.json similarity index 60% rename from types/dd-trace/package.json rename to types/cron/package.json index 90deb3c97b..19e5fb0d14 100644 --- a/types/dd-trace/package.json +++ b/types/cron/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "opentracing": ">=0.14.1" + "moment": ">=2.14.0" } } diff --git a/types/d3-array/d3-array-tests.ts b/types/d3-array/d3-array-tests.ts index 11f208f869..b0d00d5d20 100644 --- a/types/d3-array/d3-array-tests.ts +++ b/types/d3-array/d3-array-tests.ts @@ -608,7 +608,8 @@ const testObject = { }; const p1: Array = d3Array.permute(testObject, ['name', 'val', 'when', 'more']); -const p2: Array = d3Array.permute(testObject, ['when', 'more']); +// $ExpectType: Array +const p2 = d3Array.permute(testObject, ['when', 'more']); // $ExpectError const p3 = d3Array.permute(testObject, ['when', 'unknown']); diff --git a/types/dd-trace/dd-trace-tests.ts b/types/dd-trace/dd-trace-tests.ts deleted file mode 100644 index cee1b6e3ee..0000000000 --- a/types/dd-trace/dd-trace-tests.ts +++ /dev/null @@ -1,56 +0,0 @@ -import * as tracer from "dd-trace"; -import SpanContext = require("dd-trace/src/opentracing/span_context"); - -tracer.init({ - enabled: true, - service: "MyLovelyService", - hostname: "localhost", - port: 8126, - env: "dev", - logger: { - debug: msg => {}, - error: err => {}, - } -}); - -function useWebFrameworkPlugin(plugin: "express" | "hapi" | "koa" | "restify") { - tracer.use(plugin, { - service: "incoming-request", - headers: ["User-Agent"], - validateStatus: code => code !== 418, - }); -} - -tracer.use("graphql", { - depth: 1, - // Can’t use spread operator here due to https://github.com/Microsoft/TypeScript/issues/10727 - // tslint:disable-next-line:prefer-object-spread - variables: variables => Object.assign({}, variables, { password: "REDACTED" }), -}); - -tracer.use("http", { - splitByDomain: true, -}); - -tracer - .trace("web.request", { - service: "my_service", - childOf: new SpanContext({ traceId: 1337, spanId: 42 }), // childOf must be an instance of this type. See: https://github.com/DataDog/dd-trace-js/blob/master/src/opentracing/tracer.js#L99 - tags: { - env: "dev", - }, - }) - .then(span => { - span.setTag("my_tag", "my_value"); - span.finish(); - }); - -const parentScope = tracer.scopeManager().active(); -const span = tracer.startSpan("memcached", { - childOf: parentScope && parentScope.span(), - tags: { - "service.name": "my-memcached", - "resource.name": "get", - "span.type": "memcached", - }, -}); diff --git a/types/dd-trace/index.d.ts b/types/dd-trace/index.d.ts deleted file mode 100644 index a55b7f8de7..0000000000 --- a/types/dd-trace/index.d.ts +++ /dev/null @@ -1,275 +0,0 @@ -// Type definitions for dd-trace-js 0.7 -// Project: https://github.com/DataDog/dd-trace-js -// Definitions by: Colin Bradley -// Eloy Durán -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 - -// Prettified with: -// $ prettier --parser typescript --tab-width 4 --semi --trailing-comma es5 --write --print-width 120 types/dd-trace/{,*}/*.ts* - -import { Tracer, Span, SpanContext } from "opentracing"; -import DatadogSpanContext = require("./src/opentracing/span_context"); - -declare var trace: TraceProxy; -export = trace; - -declare class TraceProxy extends Tracer { - /** - * Initializes the tracer. This should be called before importing other libraries. - */ - init(options?: TracerOptions): this; - - /** - * Enable and optionally configure a plugin. - * @param plugin The name of a built-in plugin. - * @param config Configuration options. - */ - use

(plugin: P, config: PluginConfiguration[P]): this; - - /** - * Initiate a trace and creates a new span. - * @param operationName The operation name to be used for this span. - * @param options Configuration options. These will take precedence over environment variables. - */ - trace(operationName: string, options: TraceOptions): Promise; - - /** - * Initiate a trace and creates a new span. - * @param operationName The operation name to be used for this span. - * @param options Configuration options. These will take precedence over environment variables. - */ - trace(operationName: string, options: TraceOptions, callback: (span: Span) => void): void; - - /** - * Get the span from the current context. - * @returns The current span or null if outside a trace context. - */ - currentSpan(): Span | null; - - /** - * Get the scope manager to manager context propagation for the tracer. - */ - scopeManager(): ScopeManager; -} - -interface TracerOptions { - /** - * Whether to enable the tracer. - * @default true - */ - enabled?: boolean; - - /** - * Enable debug logging in the tracer. - * @default false - */ - debug?: boolean; - - /** - * The service name to be used for this program. - */ - service?: string; - - /** - * The address of the trace agent that the tracer will submit to. - * @default 'localhost' - */ - hostname?: string; - - /** - * The port of the trace agent that the tracer will submit to. - * @default 8126 - */ - port?: number | string; - - /** - * Set an application’s environment e.g. prod, pre-prod, stage. - */ - env?: string; - - /** - * Percentage of spans to sample as a float between 0 and 1. - * @default 1 - */ - sampleRate?: number; - - /** - * Interval in milliseconds at which the tracer will submit traces to the agent. - * @default 2000 - */ - flushInterval?: number; - - /** - * Experimental features can be enabled all at once by using true or individually using key / value pairs. - * @default {} - */ - experimental?: ExperimentalOptions | boolean; - - /** - * Whether to load all built-in plugins. - * @default true - */ - plugins?: boolean; - - /** - * Custom logger to be used by the tracer (if debug = true), - * should support debug() and error() methods - * see https://datadog.github.io/dd-trace-js/#custom-logging__anchor - */ - logger?: { - debug: (message: string) => void; - error: (err: Error) => void; - }; - - /** - * Global tags that should be assigned to every span. - */ - tags?: { [key: string]: any }; -} - -interface ExperimentalOptions {} - -interface TraceOptions { - /** - * The service name to be used for this span. - * The service name from the tracer will be used if this is not provided. - */ - service?: string; - - /** - * The resource name to be used for this span. - * The operation name will be used if this is not provided. - */ - resource?: string; - - /** - * The span type to be used for this span. - */ - type?: string; - - /** - * The parent span or span context for the new span. Generally this is not needed as it will be - * fetched from the current context. - * If creating your own, this must be an instance of DatadogSpanContext from ./src/opentracing/span_context - * See: https://github.com/DataDog/dd-trace-js/blob/master/src/opentracing/tracer.js#L99 - */ - childOf?: Span | SpanContext | DatadogSpanContext; - - /** - * Global tags that should be assigned to every span. - */ - tags?: { [key: string]: any } | string; -} - -declare class ScopeManager { - /** - * Get the current active scope or null if there is none. - * - * @todo The dd-trace source returns null, but opentracing's childOf span - * option is typed as taking undefined or a scope, so using undefined - * here instead. - */ - active(): Scope | undefined; - - /** - * Activate a new scope wrapping the provided span. - * - * @param span The span for which to activate the new scope. - * @param finishSpanOnClose Whether to automatically finish the span when the scope is closed. - */ - activate(span: Span, finishSpanOnClose?: boolean): Scope; -} - -declare class Scope { - /** - * Get the span wrapped by this scope. - */ - span(): Span; - - /** - * Close the scope, and finish the span if the scope was created with `finishSpanOnClose` set to true. - */ - close(): void; -} - -type Plugin = - | "amqp10" - | "amqplib" - | "bluebird" - | "elasticsearch" - | "express" - | "graphql" - | "hapi" - | "http" - | "ioredis" - | "koa" - | "memcached" - | "mongodb-core" - | "mysql" - | "mysql2" - | "pg" - | "q" - | "redis" - | "restify" - | "when"; - -interface BasePluginOptions { - /** - * The service name to be used for this plugin. - */ - service?: string; -} - -interface BaseWebFrameworkPluginOptions extends BasePluginOptions { - /** - * An array of headers to include in the span metadata. - */ - headers?: string[]; - - /** - * Callback function to determine if there was an error. It should take a - * status code as its only parameter and return `true` for success or `false` - * for errors. - */ - validateStatus?: (code: number) => boolean; -} - -interface ExpressPluginOptions extends BaseWebFrameworkPluginOptions {} - -interface HapiPluginOptions extends BaseWebFrameworkPluginOptions {} - -interface KoaPluginOptions extends BaseWebFrameworkPluginOptions {} - -interface RestifyPluginOptions extends BaseWebFrameworkPluginOptions {} - -interface GraphQLPluginOptions extends BasePluginOptions { - /** - * The maximum depth of fields/resolvers to instrument. Set to `0` to only - * instrument the operation or to -1 to instrument all fields/resolvers. - */ - depth?: number; - - /** - * A callback to enable recording of variables. By default, no variables are - * recorded. For example, using `variables => variables` would record all - * variables. - */ - variables?: (variables: T) => Partial; -} - -interface HTTPPluginOptions extends BasePluginOptions { - /** - * Use the remote endpoint host as the service name instead of the default. - */ - splitByDomain?: boolean; -} - -type PluginConfiguration = { [K in Plugin]: BasePluginOptions } & { - express: ExpressPluginOptions; - graphql: GraphQLPluginOptions; - hapi: HapiPluginOptions; - http: HTTPPluginOptions; - koa: KoaPluginOptions; - restify: RestifyPluginOptions; -}; diff --git a/types/dd-trace/src/opentracing/span_context.d.ts b/types/dd-trace/src/opentracing/span_context.d.ts deleted file mode 100644 index 7e2b06dd4d..0000000000 --- a/types/dd-trace/src/opentracing/span_context.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { SpanContext } from 'opentracing'; - -declare class DatadogSpanContext extends SpanContext { - /** - * Used to create references to parent spans. - * See: https://github.com/DataDog/dd-trace-js/blob/master/src/opentracing/tracer.js#L99 - */ - constructor(props: SpanContextLike); -} - -interface SpanContextLike { - traceId: number; - - spanId: number; - - parentId?: number | null; - - sampled?: boolean; - - baggageItems?: { [key: string]: string }; - - trace?: { - started: number[], - finished: number[] - }; -} - -export = DatadogSpanContext; diff --git a/types/detect-browser/detect-browser-tests.ts b/types/detect-browser/detect-browser-tests.ts deleted file mode 100644 index 7453ed044a..0000000000 --- a/types/detect-browser/detect-browser-tests.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { BrowserName, BrowserInfo, detect } from 'detect-browser'; -const browser = detect(); - -if (browser) { - const name: string | undefined = browser.name; - const version: string | undefined = browser.version; - const os: string | undefined | null = browser.os; - const bot: true | undefined = browser.bot; -} - -const browserInfos: BrowserInfo[] = []; - -// Those that can happen when 'detect' hits on a browser - -browserInfos.push( - { - name: "chrome", - version: "1.2.3", - os: null - } -); - -browserInfos.push( - { - name: "edge", - version: "24.5.3", - os: "Sun OS" - } -); - -browserInfos.push( - { - name: "edge", - version: "13.0", - os: "Windows 10", - bot: true - } -); - -// Those that could be returned when it's a bot - -browserInfos.push( - { - name: "facebook", - version: "1.0.2", - os: "Linux", - bot: true - } -); - -browserInfos.push( - { - name: "crios", - version: "2.9.4", - os: undefined, - bot: true - } -); - -browserInfos.push( - { - bot: true - } -); diff --git a/types/detect-browser/index.d.ts b/types/detect-browser/index.d.ts deleted file mode 100644 index 943484b013..0000000000 --- a/types/detect-browser/index.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -// Type definitions for detect-browser 3.0 -// Project: https://github.com/DamonOehlman/detect-browser -// Definitions by: Rogier Schouten -// Brian Caruso -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export {}; - -export type BrowserName = - "aol" | - "android" | - "bb10" | - "chrome" | - "crios" | - "edge" | - "facebook" | - "firefox" | - "fxios" | - "ie" | - "instagram" | - "ios" | - "ios-webview" | - "kakaotalk" | - "node" | - "opera" | - "phantomjs" | - "safari" | - "samsung" | - "vivaldi" | - "yandexbrowser"; - -export interface BrowserInfo { - name?: string; - version?: string; - os?: string | null; - bot?: true; -} - -export function detect(): null | false | BrowserInfo; -export function detectOS(userAgentString: string): null | string; -export function parseUserAgent(userAgentString: string): null | BrowserInfo; -export function getNodeVersion(): false | BrowserInfo; diff --git a/types/detect-browser/tslint.json b/types/detect-browser/tslint.json deleted file mode 100644 index dc8ddaa586..0000000000 --- a/types/detect-browser/tslint.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "indent": [ - true, - "spaces", - 4 - ] - } -} diff --git a/types/discord-rpc/index.d.ts b/types/discord-rpc/index.d.ts index 2d63e363b7..dbb6beeb39 100644 --- a/types/discord-rpc/index.d.ts +++ b/types/discord-rpc/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for discord-rpc 3.0 // Project: https://github.com/discordjs/RPC#readme // Definitions by: Jason Bothell +// Jack Baron // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { EventEmitter } from 'events'; @@ -66,6 +67,10 @@ export class Client extends EventEmitter { subscribe(event: string, args: any, callback: (data: any) => void): Promise; destroy(): Promise; + + on(event: 'ready' | 'connected', listener: () => void): this; + once(event: 'ready' | 'connected', listener: () => void): this; + off(event: 'ready' | 'connected', listener: () => void): this; } export interface RPCClientOptions { diff --git a/types/drivelist/index.d.ts b/types/drivelist/index.d.ts index d2acd039df..808cdf10af 100644 --- a/types/drivelist/index.d.ts +++ b/types/drivelist/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for drivelist 6.4 -// Project: https://github.com/resin-io-modules/drivelist +// Project: https://github.com/balena-io-modules/drivelist // Definitions by: Xiao Deng // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/ejs/tsconfig.json b/types/ejs/tsconfig.json index ea91455364..8724ff1613 100644 --- a/types/ejs/tsconfig.json +++ b/types/ejs/tsconfig.json @@ -12,6 +12,9 @@ "typeRoots": [ "../" ], + "paths": { + "lru-cache": ["lru-cache/v4"] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true @@ -20,4 +23,4 @@ "index.d.ts", "ejs-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/emojione/index.d.ts b/types/emojione/index.d.ts index 92399fdf9a..21d4726c2f 100644 --- a/types/emojione/index.d.ts +++ b/types/emojione/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for emojione 2.2 -// Project: https://github.com/Ranks/emojione, http://www.emojione.com +// Project: https://github.com/Ranks/emojione, https://www.emojione.com // Definitions by: Danilo Bargen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/enzyme-adapter-react-15.4/index.d.ts b/types/enzyme-adapter-react-15.4/index.d.ts index 2496fb1719..a6ea2334c2 100644 --- a/types/enzyme-adapter-react-15.4/index.d.ts +++ b/types/enzyme-adapter-react-15.4/index.d.ts @@ -2,7 +2,7 @@ // Project: http://airbnb.io/enzyme/ // Definitions by: Nabeelah Ali // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.1 import { EnzymeAdapter } from 'enzyme'; diff --git a/types/enzyme-adapter-react-15/index.d.ts b/types/enzyme-adapter-react-15/index.d.ts index 77312f3da0..891afc3c21 100644 --- a/types/enzyme-adapter-react-15/index.d.ts +++ b/types/enzyme-adapter-react-15/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/airbnb/enzyme, http://airbnb.io/enzyme // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.1 import { EnzymeAdapter } from 'enzyme'; diff --git a/types/enzyme-adapter-react-16/index.d.ts b/types/enzyme-adapter-react-16/index.d.ts index 257b292055..7208117e71 100644 --- a/types/enzyme-adapter-react-16/index.d.ts +++ b/types/enzyme-adapter-react-16/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/airbnb/enzyme, http://airbnb.io/enzyme // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.1 import { EnzymeAdapter } from 'enzyme'; diff --git a/types/enzyme-async-helpers/index.d.ts b/types/enzyme-async-helpers/index.d.ts index 595f29aa71..e5004f4c25 100644 --- a/types/enzyme-async-helpers/index.d.ts +++ b/types/enzyme-async-helpers/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/zth/enzyme-async-helpers // Definitions by: Kim Ehrenpohl // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.1 import { ReactWrapper, EnzymeSelector } from 'enzyme'; diff --git a/types/enzyme-redux/index.d.ts b/types/enzyme-redux/index.d.ts index e231119b89..de3693fc6a 100644 --- a/types/enzyme-redux/index.d.ts +++ b/types/enzyme-redux/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Knegusen/enzyme-redux#readme // Definitions by: Dennis Axelsson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.1 import { ReactWrapper, ShallowWrapper } from 'enzyme'; import { ReactElement } from 'react'; diff --git a/types/enzyme-to-json/index.d.ts b/types/enzyme-to-json/index.d.ts index 1a8cafb23a..f7c4d75da3 100644 --- a/types/enzyme-to-json/index.d.ts +++ b/types/enzyme-to-json/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/adriantoine/enzyme-to-json#readme // Definitions by: Joscha Feth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.1 import { ReactWrapper, ShallowWrapper } from 'enzyme'; diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 87b4d032e8..14cfd6443c 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -10,7 +10,7 @@ import { ShallowRendererProps, ComponentClass as EnzymeComponentClass } from "enzyme"; -import { Component, ReactElement, HTMLAttributes, ComponentClass, StatelessComponent } from "react"; +import { Component, ReactElement, ReactNode, HTMLAttributes, ComponentClass, StatelessComponent } from "react"; // Help classes/interfaces interface MyComponentProps { @@ -35,6 +35,10 @@ interface MyComponentState { stateProperty: string; } +interface MyRenderPropProps { + children: (params: string) => ReactNode; +} + function toComponentType(Component: ComponentClass | StatelessComponent): ComponentClass | StatelessComponent { return Component; } @@ -59,6 +63,8 @@ class AnotherComponent extends Component { } } +class MyRenderPropComponent extends Component {} + const MyStatelessComponent = (props: StatelessProps) => ; const AnotherStatelessComponent = (props: AnotherStatelessProps) => ; @@ -477,6 +483,11 @@ function ShallowWrapperTest() { shallowWrapper = new ShallowWrapper(, undefined, { lifecycleExperimental: true }); shallowWrapper = new ShallowWrapper(, shallowWrapper, { lifecycleExperimental: true }); } + + function test_renderProp() { + let shallowWrapper = new ShallowWrapper(

} />); + shallowWrapper = shallowWrapper.renderProp('children')('test'); + } } // ReactWrapper diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 257beb21fc..71238871c7 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Enzyme 3.1 +// Type definitions for Enzyme 3.9 // Project: https://github.com/airbnb/enzyme // Definitions by: Marian Palkus // Cap3 @@ -8,8 +8,9 @@ // MartynasZilinskas // Torgeir Hovden // Martin Hochel +// Christian Rackerseder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.1 /// import { ReactElement, Component, AllHTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; @@ -363,6 +364,8 @@ export interface CommonWrapper

> { length: number; } +export type Parameters = T extends (...args: infer A) => any ? A : never; + // tslint:disable-next-line no-empty-interface export interface ShallowWrapper

extends CommonWrapper { } export class ShallowWrapper

{ @@ -447,6 +450,11 @@ export class ShallowWrapper

{ * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ShallowWrapper; + + /** + * Returns a wrapper of the node rendered by the provided render prop. + */ + renderProp(prop: PropName): (...params: Parameters) => ShallowWrapper; } // tslint:disable-next-line no-empty-interface diff --git a/types/ethereumjs-abi/ethereumjs-abi-tests.ts b/types/ethereumjs-abi/ethereumjs-abi-tests.ts index f48cdd323c..28626b6304 100644 --- a/types/ethereumjs-abi/ethereumjs-abi-tests.ts +++ b/types/ethereumjs-abi/ethereumjs-abi-tests.ts @@ -1,5 +1,17 @@ -import { methodID, soliditySHA256, soliditySHA3 } from 'ethereumjs-abi'; +import * as abi from 'ethereumjs-abi'; -methodID('foo', ['uint256', 'string']); -soliditySHA3(['uint256', 'string'], [0, 'Alice']); -soliditySHA256(['uint256', 'string'], [0, 'Alice']); +const types = ['uint256', 'string']; +const values = [0, 'Alice']; +const signature = 'foo(uint256,string):(uint256)'; +abi.eventID('foo', types); +abi.methodID('foo', types); +abi.soliditySHA3(types, values); +abi.soliditySHA256(types, values); +abi.solidityRIPEMD160(types, values); +const simpleEncoded = abi.simpleEncode(signature, ...values); +abi.simpleDecode(signature, simpleEncoded); +const rawEncoded = abi.rawEncode(types, values); +abi.rawDecode(types, rawEncoded); +abi.solidityPack(types, values); +const serpentSig = abi.toSerpent(['int256', 'bytes']); +abi.fromSerpent(serpentSig); diff --git a/types/ethereumjs-abi/index.d.ts b/types/ethereumjs-abi/index.d.ts index 98ea94a6fa..6380068984 100644 --- a/types/ethereumjs-abi/index.d.ts +++ b/types/ethereumjs-abi/index.d.ts @@ -1,12 +1,21 @@ // Type definitions for ethereumjs-abi 0.6 // Project: https://github.com/ethereumjs/ethereumjs-abi, https://github.com/axic/ethereumjs-abi // Definitions by: Leonid Logvinov +// Artur Kozak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// export function soliditySHA3(argTypes: string[], args: any[]): Buffer; export function soliditySHA256(argTypes: string[], args: any[]): Buffer; +export function solidityRIPEMD160(argTypes: string[], args: any[]): Buffer; +export function eventID(name: string, types: string[]): Buffer; export function methodID(name: string, types: string[]): Buffer; export function simpleEncode(signature: string, ...args: any[]): Buffer; -export function rawDecode(signature: string[], data: Buffer): any[]; +export function simpleDecode(signature: string, data: Buffer): any[]; +export function rawEncode(types: string[], values: any[]): Buffer; +export function rawDecode(types: string[], data: Buffer): any[]; +export function stringify(types: string[], values: any[]): string; +export function solidityPack(types: string[], values: any[]): Buffer; +export function fromSerpent(signature: string): string[]; +export function toSerpent(types: string[]): string; diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 10045e57e6..f2ce8d8197 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -412,6 +412,7 @@ async () => { { resize: { width: 300 } }, { resize: { height: 300 } }, { resize: { height: 300, width: 300 } }, + { crop: { originX: 0, originY: 0, height: 300, width: 300 } } ], { compress: 0.75 }); diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 8b488f9b59..7e75c1b7d6 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -1952,14 +1952,16 @@ export namespace ImageManipulator { } interface Flip { - flip?: { vertical?: boolean; horizontal?: boolean }; + flip: { vertical?: boolean; horizontal?: boolean }; } interface Crop { - originX: number; - originY: number; - width: number; - height: number; + crop: { + originX: number; + originY: number; + width: number; + height: number; + }; } interface ImageResult { diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 5cc59d0941..e309af96a4 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -2302,6 +2302,15 @@ interface IObjectOptions { * Describes the object's corner position in canvas object absolute properties. */ aCoords?: {bl: Point, br: Point, tl: Point, tr: Point}; + + /** + * Describe object's corner position in canvas element coordinates. properties are tl,mt,tr,ml,mr,bl,mb,br,mtr for + * the main controls. each property is an object with x, y and corner. The `corner` property contains in a similar + * manner the 4 points of the interactive area of the corner. The coordinates depends from this properties: width, + * height, scaleX, scaleY skewX, skewY, angle, strokeWidth, viewportTransform, top, left, padding. The coordinates + * get updated with @method setCoords. You can calculate them without updating with @method calcCoords; + */ + oCoords?: { tl: Point, mt: Point, tr: Point, ml: Point, mr: Point, bl: Point, mb: Point, br: Point, mtr: Point } } export interface Object extends IObservable, IObjectOptions, IObjectAnimation { } export class Object { diff --git a/types/fabric/index.d.ts b/types/fabric/index.d.ts index e8d31aef56..435a8eb6d2 100644 --- a/types/fabric/index.d.ts +++ b/types/fabric/index.d.ts @@ -7,6 +7,7 @@ // Brian Martinson // Rogerio Teixeira // Bradley Hill +// Glenn Gartner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 export import fabric = require("./fabric-impl"); diff --git a/types/got/index.d.ts b/types/got/index.d.ts index 0c847d6489..a9f289b831 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -36,6 +36,7 @@ declare class HTTPError extends StdError { statusCode: number; statusMessage: string; headers: http.IncomingHttpHeaders; + body: Buffer | string | object; } declare class MaxRedirectsError extends StdError { diff --git a/types/gulp-gh-pages/gulp-gh-pages-tests.ts b/types/gulp-gh-pages/gulp-gh-pages-tests.ts index e541f18508..6fee2842e0 100644 --- a/types/gulp-gh-pages/gulp-gh-pages-tests.ts +++ b/types/gulp-gh-pages/gulp-gh-pages-tests.ts @@ -19,5 +19,8 @@ gulp.src("test.css") gulp.src("test.css") .pipe(ghPages({push: false})); +gulp.src("test.css") + .pipe(ghPages({ force: true })); + gulp.src("test.css") .pipe(ghPages({message: "master"})); diff --git a/types/gulp-gh-pages/index.d.ts b/types/gulp-gh-pages/index.d.ts index f01b9890f1..782f9e9b56 100644 --- a/types/gulp-gh-pages/index.d.ts +++ b/types/gulp-gh-pages/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for gulp-gh-pages // Project: https://github.com/rowoot/gulp-gh-pages // Definitions by: Asana +// Ntnyq // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -12,6 +13,7 @@ interface Options { branch?: string; cacheDir?: string; push?: boolean; + force?: boolean; message?: string; } diff --git a/types/handlebars-helpers/package.json b/types/handlebars-helpers/package.json new file mode 100644 index 0000000000..bd9f09c2c3 --- /dev/null +++ b/types/handlebars-helpers/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "handlebars": ">=4.1.0" + } +} diff --git a/types/handlebars-helpers/tsconfig.json b/types/handlebars-helpers/tsconfig.json index e822854459..6b03737014 100644 --- a/types/handlebars-helpers/tsconfig.json +++ b/types/handlebars-helpers/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es2015" ], "noImplicitAny": true, "noImplicitThis": false, diff --git a/types/hexo/package.json b/types/hexo/package.json new file mode 100644 index 0000000000..f06689a6b9 --- /dev/null +++ b/types/hexo/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "moment": "^2.19.4" + } +} diff --git a/types/imap-simple/index.d.ts b/types/imap-simple/index.d.ts index 398bcb6a26..f346d51e52 100644 --- a/types/imap-simple/index.d.ts +++ b/types/imap-simple/index.d.ts @@ -55,7 +55,7 @@ export class ImapSimple extends NodeJS.EventEmitter { getBoxes(callback: (err: Error, boxes: Imap.MailBoxes) => void): void; getBoxes(): Promise; - /** Search for and retrieve mail in the previously opened mailbox. */ + /** Search for and retrieve mail in the currently open mailbox. */ search(searchCriteria: any[], fetchOptions: Imap.FetchOptions, callback: (err: Error, messages: Message[]) => void): void; search(searchCriteria: any[], fetchOptions: Imap.FetchOptions): Promise; diff --git a/types/indefinite/indefinite-tests.ts b/types/indefinite/indefinite-tests.ts new file mode 100644 index 0000000000..881a09f666 --- /dev/null +++ b/types/indefinite/indefinite-tests.ts @@ -0,0 +1,9 @@ +import { indefinite } from "indefinite"; + +const anApple = indefinite("apple"); // "an apple" +const aBanana = indefinite('banana'); // "a banana" +const AnApple = indefinite('apple', { capitalize: true }); // "An apple" +const anEight = indefinite("8"); // "an 8" +const anEightAsNumber = indefinite(8); // "an 8" +const a1892 = indefinite("1892"); // "a 1892" -> read "a one thousand eight hundred ninety-two" +const a1892AsColloquial = indefinite("1892", { numbers: "colloquial" }); // "an 1892" -> read "an eighteen ninety-two" diff --git a/types/indefinite/index.d.ts b/types/indefinite/index.d.ts new file mode 100644 index 0000000000..50f5fdbbf4 --- /dev/null +++ b/types/indefinite/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for indefinite 2.2 +// Project: https://github.com/tandrewnichols/indefinite +// Definitions by: omaishar +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Options { + capitalize?: boolean; + caseInsensitive?: boolean; + numbers?: "colloquial"; +} +export function indefinite(word: string | number, opts?: Options): string; diff --git a/types/p-map/tsconfig.json b/types/indefinite/tsconfig.json similarity index 75% rename from types/p-map/tsconfig.json rename to types/indefinite/tsconfig.json index ed62309b29..94477767e2 100644 --- a/types/p-map/tsconfig.json +++ b/types/indefinite/tsconfig.json @@ -7,17 +7,17 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true }, "files": [ "index.d.ts", - "p-map-tests.ts" + "indefinite-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/internal-ip/tslint.json b/types/indefinite/tslint.json similarity index 100% rename from types/internal-ip/tslint.json rename to types/indefinite/tslint.json diff --git a/types/ink-spinner/package.json b/types/ink-spinner/package.json new file mode 100644 index 0000000000..6c2f5b70e4 --- /dev/null +++ b/types/ink-spinner/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "chalk": "^2.1.0" + } +} diff --git a/types/inquirer/index.d.ts b/types/inquirer/index.d.ts index 5d976e896d..74aee08ed3 100644 --- a/types/inquirer/index.d.ts +++ b/types/inquirer/index.d.ts @@ -81,6 +81,7 @@ declare namespace inquirer { * Possible values: *
    *
  • input
  • + *
  • number
  • *
  • confirm
  • *
  • list
  • *
  • rawlist
  • diff --git a/types/internal-ip/index.d.ts b/types/internal-ip/index.d.ts deleted file mode 100644 index 1bed7e9059..0000000000 --- a/types/internal-ip/index.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Type definitions for internal-ip 3.0 -// Project: https://github.com/sindresorhus/internal-ip#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export const v6: IPGetterFn; -export const v4: IPGetterFn; - -export interface IPGetterFn { // tslint:disable-line:interface-name - (): Promise; - sync(): string | null; -} diff --git a/types/internal-ip/internal-ip-tests.ts b/types/internal-ip/internal-ip-tests.ts deleted file mode 100644 index 1b383de2f3..0000000000 --- a/types/internal-ip/internal-ip-tests.ts +++ /dev/null @@ -1,15 +0,0 @@ -import * as internalIp from 'internal-ip'; - -internalIp.v6().then(ip => { - // $ExpectType string | null - ip; -}); -// $ExpectType string | null -internalIp.v6.sync(); - -internalIp.v4().then(ip => { - // $ExpectType string | null - ip; -}); -// $ExpectType string | null -internalIp.v4.sync(); diff --git a/types/internal-ip/v2/index.d.ts b/types/internal-ip/v2/index.d.ts deleted file mode 100644 index a82dd8c913..0000000000 --- a/types/internal-ip/v2/index.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// Type definitions for internal-ip 2.0 -// Project: https://github.com/sindresorhus/internal-ip#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export function v6(): Promise; -export function v4(): Promise; diff --git a/types/internal-ip/v2/internal-ip-tests.ts b/types/internal-ip/v2/internal-ip-tests.ts deleted file mode 100644 index e94ec9f510..0000000000 --- a/types/internal-ip/v2/internal-ip-tests.ts +++ /dev/null @@ -1,10 +0,0 @@ -import * as internalIp from 'internal-ip'; - -let str: string; -internalIp.v6().then(ip => { - str = ip; -}); - -internalIp.v4().then(ip => { - str = ip; -}); diff --git a/types/is-blank/index.d.ts b/types/is-blank/index.d.ts new file mode 100644 index 0000000000..eedfa5bd6d --- /dev/null +++ b/types/is-blank/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for is-blank 2.1 +// Project: https://github.com/johnotander/is-blank#readme +// Definitions by: Christian Gambardella +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function isBlank(input: any): boolean; +export = isBlank; diff --git a/types/is-blank/is-blank-tests.ts b/types/is-blank/is-blank-tests.ts new file mode 100644 index 0000000000..367571922a --- /dev/null +++ b/types/is-blank/is-blank-tests.ts @@ -0,0 +1,17 @@ +import isBlank = require('is-blank'); + +isBlank([]); // => true +isBlank({}); // => true +isBlank(0); // => true +isBlank(() => {}); // => true +isBlank(null); // => true +isBlank(undefined); // => true +isBlank(''); // => true +isBlank(' '); // => true +isBlank('\r\t\n '); // => true + +isBlank(['a', 'b']); // => false +isBlank({ a: 'b' }); // => false +isBlank('string'); // => false +isBlank(42); // => false +isBlank((a: number, b: number) => a + b); diff --git a/types/p-pipe/tsconfig.json b/types/is-blank/tsconfig.json similarity index 94% rename from types/p-pipe/tsconfig.json rename to types/is-blank/tsconfig.json index 46cabfcfeb..58f358a499 100644 --- a/types/p-pipe/tsconfig.json +++ b/types/is-blank/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "p-pipe-tests.ts" + "is-blank-tests.ts" ] } diff --git a/types/internal-ip/v2/tslint.json b/types/is-blank/tslint.json similarity index 100% rename from types/internal-ip/v2/tslint.json rename to types/is-blank/tslint.json diff --git a/types/is-natural-number/index.d.ts b/types/is-natural-number/index.d.ts new file mode 100644 index 0000000000..37f8e19a26 --- /dev/null +++ b/types/is-natural-number/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for is-natural-number 4.0 +// Project: https://github.com/shinnn/is-natural-number.js +// Definitions by: Adam Zerella +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Options { + /** + * Setting this option true makes 0 regarded as a natural number. + */ + includeZero: boolean; +} + +/** + * Rreturns true if the first argument is one of the natural numbers. + * If not, or the argument is not a number, it returns false. + */ +declare function isNaturalNumber(number: number|string, option?: Options): boolean; + +export = isNaturalNumber; diff --git a/types/is-natural-number/is-natural-number-tests.ts b/types/is-natural-number/is-natural-number-tests.ts new file mode 100644 index 0000000000..ac0f0db8eb --- /dev/null +++ b/types/is-natural-number/is-natural-number-tests.ts @@ -0,0 +1,6 @@ +import isNaturalNumber = require("is-natural-number"); + +isNaturalNumber(5); +isNaturalNumber("5"); +isNaturalNumber(0, {includeZero: true}); +isNaturalNumber("0", {includeZero: true}); diff --git a/types/is-natural-number/tsconfig.json b/types/is-natural-number/tsconfig.json new file mode 100644 index 0000000000..0d7327abc4 --- /dev/null +++ b/types/is-natural-number/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [ + + ], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-natural-number-tests.ts" + ] +} diff --git a/types/p-map/tslint.json b/types/is-natural-number/tslint.json similarity index 100% rename from types/p-map/tslint.json rename to types/is-natural-number/tslint.json diff --git a/types/is-odd/index.d.ts b/types/is-odd/index.d.ts new file mode 100644 index 0000000000..e912f69557 --- /dev/null +++ b/types/is-odd/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for is-odd 3.0 +// Project: https://github.com/jonschlinkert/is-odd +// Definitions by: Adam Zerella +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Return true if a given number is odd or not. + */ +declare function isOdd(value: number|string): boolean; + +export = isOdd; diff --git a/types/is-odd/is-odd-tests.ts b/types/is-odd/is-odd-tests.ts new file mode 100644 index 0000000000..0717501894 --- /dev/null +++ b/types/is-odd/is-odd-tests.ts @@ -0,0 +1,4 @@ +import isOdd = require("is-odd"); + +isOdd(5); +isOdd("5"); diff --git a/types/is-odd/tsconfig.json b/types/is-odd/tsconfig.json new file mode 100644 index 0000000000..163790caf2 --- /dev/null +++ b/types/is-odd/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [ + + ], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-odd-tests.ts" + ] +} diff --git a/types/is-odd/tslint.json b/types/is-odd/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/is-odd/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/isotope-layout/index.d.ts b/types/isotope-layout/index.d.ts index 5662da48f7..e10c0ea7c7 100644 --- a/types/isotope-layout/index.d.ts +++ b/types/isotope-layout/index.d.ts @@ -284,6 +284,10 @@ declare global { * Get the Isotope instance from a jQuery object. Isotope instances are useful to access Isotope properties. */ data(methodName: 'isotope'): Isotope; + /** + * Filters, sorts, and lays out items. + */ + isotope(): JQuery; /** * Lays out specified items. * @param elements Array of Isotope.Items diff --git a/types/isotope-layout/isotope-layout-tests.ts b/types/isotope-layout/isotope-layout-tests.ts index d37475cefa..c39b8851db 100644 --- a/types/isotope-layout/isotope-layout-tests.ts +++ b/types/isotope-layout/isotope-layout-tests.ts @@ -81,6 +81,7 @@ $grid = $('.grid').isotope({ }); // test methods using jquery +$grid.isotope(); $grid.isotope('addItems', $('.items')); $grid.isotope('appended', $('.items')[0]); $grid.isotope('hideItemElements', [ new HTMLElement() ]); diff --git a/types/jasmine-enzyme/index.d.ts b/types/jasmine-enzyme/index.d.ts index d64a73e6f6..4884aa2152 100644 --- a/types/jasmine-enzyme/index.d.ts +++ b/types/jasmine-enzyme/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/formidablelabs/enzyme-matchers/packages/jasmine-enzyme // Definitions by: Umar Bolatov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.1 /// /// diff --git a/types/jenkins/index.d.ts b/types/jenkins/index.d.ts index 4e1c42fa3e..1155b430b0 100644 --- a/types/jenkins/index.d.ts +++ b/types/jenkins/index.d.ts @@ -15,7 +15,7 @@ declare namespace create { log(name: string, n: number, start: number, callback: (err: Error, data: any) => void): void; log(name: string, n: number, start: number, type: 'text' | 'html', callback: (err: Error, data: any) => void): void; log(name: string, n: number, start: number, type: 'text' | 'html', meta: boolean, callback: (err: Error, data: any) => void): void; - logStream(name: string, n: number, type?: 'text' | 'html', delay?: number): NodeJS.ReadableStream; + logStream(name: string, n: number, options?: { type?: 'text' | 'html', delay?: number }): NodeJS.ReadableStream; stop(name: string, n: number, callback: (err: Error) => void): void; term(name: string, n: number, callback: (err: Error) => void): void; }; diff --git a/types/jenkins/jenkins-tests.ts b/types/jenkins/jenkins-tests.ts index 93fc61bb07..8f3ffe4555 100644 --- a/types/jenkins/jenkins-tests.ts +++ b/types/jenkins/jenkins-tests.ts @@ -34,6 +34,20 @@ log.on('end', () => { console.log('end'); }); +const log2 = jenkins.build.logStream('example', 1, { type: 'html', delay: 2 * 1000 }); + +log2.on('data', (text: string) => { + process.stdout.write(text); +}); + +log2.on('error', (err: Error) => { + console.log('error', err); +}); + +log2.on('end', () => { + console.log('end'); +}); + jenkins.build.stop('example', 1, (err) => { if (err) throw err; }); diff --git a/types/jest-environment-puppeteer/index.d.ts b/types/jest-environment-puppeteer/index.d.ts index 79c25e32d8..bcc37c8f9e 100644 --- a/types/jest-environment-puppeteer/index.d.ts +++ b/types/jest-environment-puppeteer/index.d.ts @@ -1,14 +1,43 @@ -// Type definitions for jest-environment-puppeteer 2.2 +// Type definitions for jest-environment-puppeteer 4.0 // Project: https://github.com/smooth-code/jest-puppeteer/tree/master/packages/jest-environment-puppeteer // Definitions by: Josh Goldberg +// Ifiok Jr. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import { Browser, Page } from "puppeteer"; +import { Browser, Page, BrowserContext } from 'puppeteer'; + +interface JestPuppeteer { + /** + * Reset global.page + * + * ```ts + * beforeEach(async () => { + * await jestPuppeteer.resetPage() + * }) + * ``` + */ + resetPage(): Promise; + + /** + * Suspends test execution and gives you opportunity to see what's going on in the browser + * - Jest is suspended (no timeout) + * - A debugger instruction to Chromium, if Puppeteer has been launched with { devtools: true } it will stop + * + * ```ts + * it('should put test in debug mode', async () => { + * await jestPuppeteer.debug() + * }) + * ``` + */ + debug(): Promise; +} declare global { const browser: Browser; + const context: BrowserContext; const page: Page; + const jestPuppeteer: JestPuppeteer; } -export { }; +export {}; diff --git a/types/jest-environment-puppeteer/jest-environment-puppeteer-tests.ts b/types/jest-environment-puppeteer/jest-environment-puppeteer-tests.ts index 3de8c3661a..fb424d580b 100644 --- a/types/jest-environment-puppeteer/jest-environment-puppeteer-tests.ts +++ b/types/jest-environment-puppeteer/jest-environment-puppeteer-tests.ts @@ -2,3 +2,7 @@ import * as puppeteer from "puppeteer"; const myBrowser: puppeteer.Browser = browser; const myPage: puppeteer.Page = page; +const myContext: puppeteer.BrowserContext = context; + +jestPuppeteer.debug(); +jestPuppeteer.resetPage(); diff --git a/types/jest-specific-snapshot/index.d.ts b/types/jest-specific-snapshot/index.d.ts index 0e0a43d895..25c168f5d2 100644 --- a/types/jest-specific-snapshot/index.d.ts +++ b/types/jest-specific-snapshot/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/igor-dv/jest-specific-snapshot#readme // Definitions by: Janeene Beeforth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 3.1 /// diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index f0382d2cb5..da84c876af 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -220,9 +220,10 @@ declare namespace jest { * spy.mockRestore(); * }); */ - function spyOn>(object: T, method: M, accessType: 'get'): SpyInstance; - function spyOn>(object: T, method: M, accessType: 'set'): SpyInstance; - function spyOn>(object: T, method: M): T[M] extends (...args: any[]) => any ? SpyInstance, ArgsType> : never; + function spyOn>>(object: T, method: M, accessType: 'get'): SpyInstance[M], []>; + function spyOn>>(object: T, method: M, accessType: 'set'): SpyInstance[M]]>; + function spyOn>>(object: T, method: M): Required[M] extends (...args: any[]) => any ? + SpyInstance[M]>, ArgsType[M]>> : never; /** * Indicates that the module system should never return a mocked version of * the specified module from require() (e.g. that it should always return the real module). @@ -263,10 +264,11 @@ declare namespace jest { } interface Each { - (cases: any[]): (name: string, fn: (...args: any[]) => any) => void; + (cases: any[]): (name: string, fn: (...args: any[]) => any, timeout?: number) => void; (strings: TemplateStringsArray, ...placeholders: any[]): ( name: string, - fn: (arg: any) => any + fn: (arg: any) => any, + timeout?: number ) => void; } @@ -1625,6 +1627,7 @@ declare namespace jest { numPendingTests: number; numPendingTestSuites: number; numRuntimeErrorTestSuites: number; + numTodoTests: number; numTotalTests: number; numTotalTestSuites: number; snapshot: SnapshotSummary; diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index 69e68ab6f7..039d996f5c 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -349,11 +349,15 @@ const mockContextVoid = jest.fn().mock; const mockContextString = jest.fn(() => "").mock; jest.fn().mockClear(); - jest.fn().mockReset(); - jest.fn().mockRestore(); +jest.fn().mockImplementation((test: number) => test); +jest.fn().mockResolvedValue(1); +interface SpyInterface { + prop?: number; + method?: (arg1: boolean) => void; +} const spiedTarget = { returnsVoid(): void { }, setValue(value: string): void { @@ -363,7 +367,6 @@ const spiedTarget = { return ""; } }; - class SpiedTargetClass { private _value = 3; private _value2 = ''; @@ -380,6 +383,7 @@ class SpiedTargetClass { this._value2 = value2; } } + const spiedTarget2 = new SpiedTargetClass(); // $ExpectError @@ -425,11 +429,17 @@ const spy5 = jest.spyOn(spiedTarget2, "value", "get"); spy5.mockReturnValue('5'); // $ExpectType SpyInstance -const spy6 = jest.spyOn(spiedTarget2, "value", "set"); +jest.spyOn(spiedTarget2, "value", "set"); -// should compile -jest.fn().mockImplementation((test: number) => test); -jest.fn().mockResolvedValue(1); +let spyInterfaceImpl: SpyInterface = {}; +// $ExpectError +jest.spyOn(spyInterfaceImpl, "method", "get"); +// $ExpectError +jest.spyOn(spyInterfaceImpl, "prop"); +// $ExpectType SpyInstance +jest.spyOn(spyInterfaceImpl, "prop", "get"); +// $ExpectType SpyInstance +jest.spyOn(spyInterfaceImpl, "method"); interface Type1 { a: number; } interface Type2 { b: number; } @@ -1360,6 +1370,14 @@ test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( } ); +test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( + ".add(%i, %i)", + (a, b, expected) => { + expect(a + b).toBe(expected); + }, + 5000 +); + test.each` a | b | expected ${1} | ${1} | ${2} @@ -1369,6 +1387,15 @@ test.each` expect(a + b).toBe(expected); }); +test.each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`("returns $expected when $a is added $b", ({ a, b, expected }: Case) => { + expect(a + b).toBe(expected); +}, 5000); + test.only.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( ".add(%i, %i)", (a, b, expected) => { diff --git a/types/jss/index.d.ts b/types/jss/index.d.ts index edcb0ba95f..5326e3f6d7 100644 --- a/types/jss/index.d.ts +++ b/types/jss/index.d.ts @@ -104,7 +104,7 @@ export interface RuleOptions { index: number; className: string; } -export declare class SheetsRegistry { +export class SheetsRegistry { constructor(); registry: ReadonlyArray; readonly index: number; @@ -122,7 +122,7 @@ export type CreateStyleSheetOptions = Partial<{ generateClassName: GenerateClassName; classNamePrefix: string; }>; -export declare class JSS { +export class JSS { constructor(options?: Partial); createStyleSheet( styles: Partial>, diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 8b173c0887..ac0000ad9a 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -1111,6 +1111,7 @@ knex('users') // // Migrations // +const name = "test"; const config = { directory: "./migrations", extension: "js", diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index 8bf99b79db..39eb527c2e 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -12,13 +12,30 @@ // TypeScript Version: 2.3 interface KnockoutSubscribableFunctions { - notifySubscribers(valueToWrite?: T, event?: string): void; + /** + * Notify subscribers of knockout "change" event. This doesn't acctually change the observable value. + * @param eventValue A value to be sent with the event. + * @param event The knockout event. + */ + notifySubscribers(eventValue?: T, event?: "change"): void; + /** + * Notify subscribers of a knockout or user defined event. + * @param eventValue A value to be sent with the event. + * @param event The knockout or user defined event name. + */ + notifySubscribers(eventValue: U, event: string): void; } interface KnockoutComputedFunctions { } interface KnockoutObservableFunctions { + /** + * Used by knockout to decide if value of observable has changed and should notify subscribers. Returns true if instances are primitives, and false if are objects. + * If your observable holds an object, this can be overwritten to return equality based on your needs. + * @param a previous value. + * @param b next value. + */ equalityComparer(a: T, b: T): boolean; } @@ -57,7 +74,7 @@ interface KnockoutObservableArrayFunctions extends KnockoutReadonlyObservable pop(): T; /** * Adds a new item to the end of array. - * @param items Items to be added + * @param items Items to be added. */ push(...items: T[]): void; /** @@ -66,7 +83,7 @@ interface KnockoutObservableArrayFunctions extends KnockoutReadonlyObservable shift(): T; /** * Inserts a new item at the beginning of the array. - * @param items Items to be added + * @param items Items to be added. */ unshift(...items: T[]): number; /** @@ -85,24 +102,24 @@ interface KnockoutObservableArrayFunctions extends KnockoutReadonlyObservable // Ko specific /** - * Replaces the first value that equals oldItem with newItem - * @param oldItem Item to be replaced - * @param newItem Replacing item + * Replaces the first value that equals oldItem with newItem. + * @param oldItem Item to be replaced. + * @param newItem Replacing item. */ replace(oldItem: T, newItem: T): void; /** * Removes all values that equal item and returns them as an array. - * @param item The item to be removed + * @param item The item to be removed. */ remove(item: T): T[]; /** * Removes all values and returns them as an array. - * @param removeFunction A function used to determine true if item should be removed and fasle otherwise + * @param removeFunction A function used to determine true if item should be removed and fasle otherwise. */ remove(removeFunction: (item: T) => boolean): T[]; /** - * Removes all values that equal any of the supplied items - * @param items Items to be removed + * Removes all values that equal any of the supplied items. + * @param items Items to be removed. */ removeAll(items: T[]): T[]; /** @@ -140,45 +157,45 @@ interface KnockoutSubscribableStatic { interface KnockoutSubscription { /** - * Terminates a subscription + * Terminates a subscription. */ dispose(): void; } interface KnockoutSubscribable extends KnockoutSubscribableFunctions { /** - * Registers to be notified after the observable's value changes - * @param callback Function that is called whenever the notification happens - * @param target Defines the value of 'this' in the callback function - * @param event The name of the event to receive notification for + * Registers to be notified after the observable's value changes. + * @param callback Function that is called whenever the notification happens. + * @param target Defines the value of 'this' in the callback function. + * @param event The knockout event name. */ subscribe(callback: (newValue: T) => void, target?: any, event?: "change"): KnockoutSubscription; /** - * Registers to be notified before the observable's value changes - * @param callback Function that is called whenever the notification happens - * @param target Defines the value of 'this' in the callback function - * @param event The name of the event to receive notification for + * Registers to be notified before the observable's value changes. + * @param callback Function that is called whenever the notification happens. + * @param target Defines the value of 'this' in the callback function. + * @param event The knockout event name. */ subscribe(callback: (newValue: T) => void, target: any, event: "beforeChange"): KnockoutSubscription; /** - * Registers to be notified when the observable's value changes - * @param callback Function that is called whenever the notification happens - * @param target Defines the value of 'this' in the callback function - * @param event The name of the event to receive notification for + * Registers to be notified when a knockout or user defined event happens. + * @param callback Function that is called whenever the notification happens. eventValue can be anything. No relation to underlying observable. + * @param target Defines the value of 'this' in the callback function. + * @param event The knockout or user defined event name. */ - subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + subscribe(callback: (eventValue: U) => void, target: any, event: string): KnockoutSubscription; /** - * Customizes observables basic functionality + * Customizes observables basic functionality. * @param requestedExtenders Name of the extender feature and its value, e.g. { notify: 'always' }, { rateLimit: 50 } */ extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable; /** - * Gets total number of subscribers + * Gets total number of subscribers. */ getSubscriptionsCount(): number; /** - * Gets number of subscribers of a particular event - * @param event Event name + * Gets number of subscribers of a particular event. + * @param event Event name. */ getSubscriptionsCount(event: string): number; } @@ -187,26 +204,32 @@ interface KnockoutComputedStatic { fn: KnockoutComputedFunctions; /** - * Creates computed observable + * Creates computed observable. */ (): KnockoutComputed; /** - * Creates computed observable - * @param evaluatorFunction Function that computes the observable value - * @param context Defines the value of 'this' when evaluating the computed observable - * @param options An object with further properties for the computed observable + * Creates computed observable. + * @param evaluatorFunction Function that computes the observable value. + * @param context Defines the value of 'this' when evaluating the computed observable. + * @param options An object with further properties for the computed observable. */ (evaluatorFunction: () => T, context?: any, options?: KnockoutComputedOptions): KnockoutComputed; /** - * Creates computed observable - * @param options An object that defines the computed observable options and behavior - * @param context Defines the value of 'this' when evaluating the computed observable + * Creates computed observable. + * @param options An object that defines the computed observable options and behavior. + * @param context Defines the value of 'this' when evaluating the computed observable. */ (options: KnockoutComputedDefine, context?: any): KnockoutComputed; } interface KnockoutReadonlyComputed extends KnockoutReadonlyObservable { + /** + * Returns whether the computed observable may be updated in the future. A computed observable is inactive if it has no dependencies. + */ isActive(): boolean; + /** + * Returns the current number of dependencies of the computed observable. + */ getDependenciesCount(): number; } @@ -220,15 +243,7 @@ interface KnockoutComputed extends KnockoutReadonlyComputed, KnockoutObser */ dispose(): void; /** - * Returns whether the computed observable may be updated in the future. A computed observable is inactive if it has no dependencies. - */ - isActive(): boolean; - /** - * Returns the current number of dependencies of the computed observable. - */ - getDependenciesCount(): number; - /** - * Customizes observables basic functionality + * Customizes observables basic functionality. * @param requestedExtenders Name of the extender feature and it's value, e.g. { notify: 'always' }, { rateLimit: 50 } */ extend(requestedExtenders: { [key: string]: any; }): KnockoutComputed; @@ -249,19 +264,19 @@ interface KnockoutReadonlyObservableArray extends KnockoutReadonlyObservable< subscribe(callback: (newValue: KnockoutArrayChange[]) => void, target: any, event: "arrayChange"): KnockoutSubscription; subscribe(callback: (newValue: T[]) => void, target: any, event: "beforeChange"): KnockoutSubscription; subscribe(callback: (newValue: T[]) => void, target?: any, event?: "change"): KnockoutSubscription; - subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + subscribe(callback: (newValue: U) => void, target: any, event: string): KnockoutSubscription; } /* - NOTE: In theory this should extend both Observable and ReadonlyObservableArray, + NOTE: In theory this should extend both KnockoutObservable and KnockoutReadonlyObservableArray, but can't since they both provide conflicting typings of .subscribe. - So it extends Observable and duplicates the subscribe definitions, which should be kept in sync + So it extends KnockoutObservable and duplicates the subscribe definitions, which should be kept in sync */ interface KnockoutObservableArray extends KnockoutObservable, KnockoutObservableArrayFunctions { subscribe(callback: (newValue: KnockoutArrayChange[]) => void, target: any, event: "arrayChange"): KnockoutSubscription; subscribe(callback: (newValue: T[]) => void, target: any, event: "beforeChange"): KnockoutSubscription; subscribe(callback: (newValue: T[]) => void, target?: any, event?: "change"): KnockoutSubscription; - subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + subscribe(callback: (newValue: U) => void, target: any, event: string): KnockoutSubscription; extend(requestedExtenders: { [key: string]: any; }): KnockoutObservableArray; } @@ -281,9 +296,8 @@ interface KnockoutObservableStatic { interface KnockoutReadonlyObservable extends KnockoutSubscribable, KnockoutObservableFunctions { (): T; - /** - * Returns the current value of the computed observable without creating a dependency + * Returns the current value of the computed observable without creating a dependency. */ peek(): T; valueHasMutated?: { (): void; }; @@ -294,6 +308,10 @@ interface KnockoutObservable extends KnockoutReadonlyObservable { (value: T): void; // Since .extend does arbitrary thing to an observable, it's not safe to do on a readonly observable + /** + * Customizes observables basic functionality. + * @param requestedExtenders Name of the extender feature and it's value, e.g. { notify: 'always' }, { rateLimit: 50 } + */ extend(requestedExtenders: { [key: string]: any; }): KnockoutObservable; } @@ -301,7 +319,7 @@ interface KnockoutComputedOptions { /** * Makes the computed observable writable. This is a function that receives values that other code is trying to write to your computed observable. * It’s up to you to supply custom logic to handle the incoming values, typically by writing the values to some underlying observable(s). - * @param value + * @param value Value being written to the computer observable. */ write?(value: T): void; /** @@ -347,8 +365,19 @@ interface KnockoutBindingContext { $component: any; $componentTemplateNodes: Node[]; - extend(properties: any): any; - createChildContext(dataItemOrAccessor: any, dataItemAlias?: any, extendCallback?: Function): any; + /** + * Clones the current Binding Context, adding extra properties to it. + * @param properties object with properties to be added in the binding context. + */ + extend(properties: { [key: string]: any; } | (() => { [key: string]: any; })): KnockoutBindingContext; + /** + * This returns a new binding context whose viewmodel is the first parameter and whose $parentContext is the current bindingContext. + * @param dataItemOrAccessor The binding context of the children. + * @param dataItemAlias An alias for the data item in descendant contexts. + * @param extendCallback Function to be called. + * @param options Further options. + */ + createChildContext(dataItemOrAccessor: any, dataItemAlias?: string, extendCallback?: Function, options?: { "exportDependencies": boolean }): any; } interface KnockoutAllBindingsAccessor { @@ -405,7 +434,7 @@ interface KnockoutBindingHandlers { } interface KnockoutMemoization { - memoize(callback: () => string): string; + memoize(callback: Function): string; unmemoize(memoId: string, callbackParams: any[]): boolean; unmemoizeDomNodeAndDescendants(domNode: any, extraCallbackParamsArray: any[]): boolean; parseMemoText(memoText: string): string; @@ -640,63 +669,100 @@ interface KnockoutStatic { computed: KnockoutComputedStatic; /** - * Creates a pure computed observable - * @param evaluatorFunction Function that computes the observable value - * @param context Defines the value of 'this' when evaluating the computed observable + * Creates a pure computed observable. + * @param evaluatorFunction Function that computes the observable value. + * @param context Defines the value of 'this' when evaluating the computed observable. */ pureComputed(evaluatorFunction: () => T, context?: any): KnockoutComputed; /** - * Creates a pure computed observable - * @param options An object that defines the computed observable options and behavior - * @param context Defines the value of 'this' when evaluating the computed observable + * Creates a pure computed observable. + * @param options An object that defines the computed observable options and behavior. + * @param context Defines the value of 'this' when evaluating the computed observable. */ pureComputed(options: KnockoutComputedDefine, context?: any): KnockoutComputed; observableArray: KnockoutObservableArrayStatic; - contextFor(node: any): any; + /** + * Evaluates if instance is a KnockoutSubscribable. + * @param instance Instance to be evaluated. + */ isSubscribable(instance: any): instance is KnockoutSubscribable; - toJSON(viewModel: any, replacer?: Function, space?: any): string; - + /** + * Clones object substituting each observable for it's underlying value. Uses browser JSON.stringify internally to stringify the result. + * @param viewModel Object with observables to be converted. + * @param replacer A Function or array of names that alters the behavior of the stringification process. + * @param space Used to insert white space into the output JSON string for readability purposes. + */ + toJSON(viewModel: any, replacer?: Function | [string | number], space?: string | number): string; + /** + * Clones object substituting for each observable the current value of that observable. + * @param viewModel Object with observables to be converted. + */ toJS(viewModel: any): any; /** * Determine if argument is an observable. Returns true for observables, observable arrays, and all computed observables. - * @param instance Object to be checked + * @param instance Object to be checked. */ isObservable(instance: any): instance is KnockoutObservable; /** * Determine if argument is an observable. Returns true for observables, observable arrays, and all computed observables. - * @param instance Object to be checked + * @param instance Object to be checked. */ isObservable(instance: KnockoutObservable | T): instance is KnockoutObservable; /** * Determine if argument is a writable observable. Returns true for observables, observable arrays, and writable computed observables. - * @param instance Object to be checked + * @param instance Object to be checked. */ isWriteableObservable(instance: any): instance is KnockoutObservable; /** * Determine if argument is a writable observable. Returns true for observables, observable arrays, and writable computed observables. - * @param instance Object to be checked + * @param instance Object to be checked. */ isWriteableObservable(instance: KnockoutObservable | T): instance is KnockoutObservable; /** - * Determine if argument is a computed observable - * @param instance Object to be checked + * Determine if argument is a computed observable. + * @param instance Object to be checked. */ isComputed(instance: any): instance is KnockoutComputed; /** - * Determine if argument is a computed observable - * @param instance Object to be checked + * Determine if argument is a computed observable. + * @param instance Object to be checked. */ isComputed(instance: KnockoutObservable | T): instance is KnockoutComputed; - dataFor(node: any): any; + /** + * Returns the data that was available for binding against the element. + * @param node Html node that contains the binding context. + */ + dataFor(node: Node): any; + /** + * Returns the entire binding context that was available to the DOM element. + * @param node Html node that contains the binding context. + */ + contextFor(node: Node): any; + /** + * Removes a node from the DOM. + * @param node Node to be removed. + */ removeNode(node: Node): void; + /** + * Used internally by Knockout to clean up data/computeds that it created related to the element. It does not remove any event handlers added by bindings. + * @param node Node to be cleaned. + */ cleanNode(node: Node): Node; renderTemplate(template: Function, viewModel: any, options?: any, target?: any, renderMode?: any): any; renderTemplate(template: string, viewModel: any, options?: any, target?: any, renderMode?: any): any; - unwrap(value: KnockoutObservable | T): T; - unwrap(value: KnockoutObservableArray | T[]): T[]; + /** + * Returns the underlying value of the Knockout Observable or in case of plain js object, return the object. Use this to easily accept both observable and plain values. + * @param instance observable to be unwraped if it's an Observable. + */ + unwrap(instance: KnockoutObservable | T): T; + /** + * Gets the array inside the KnockoutObservableArray. + * @param instance observable to be unwraped. + */ + unwrap(instance: KnockoutObservableArray | T[]): T[]; /** * Get information about the current computed property during the execution of a computed observable’s evaluator function. @@ -783,10 +849,10 @@ interface KnockoutStatic { renderTemplateForEach(template: any, arrayOrObservableArray: KnockoutObservable, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; /** - * Executes a callback function inside a computed observable, without creating a dependecy between it and the observables inside the function + * Executes a callback function inside a computed observable, without creating a dependecy between it and the observables inside the function. * @param callback Function to be called. - * @param callbackTarget Defines the value of 'this' in the callback function - * @param callbackArgs Arguments for the callback Function + * @param callbackTarget Defines the value of 'this' in the callback function. + * @param callbackArgs Arguments for the callback Function. */ ignoreDependencies(callback: () => T, callbackTarget?: any, callbackArgs?: any): T; @@ -924,9 +990,25 @@ declare namespace KnockoutComponentTypes { } interface Loader { + /** + * Define this if: you want to supply configurations programmatically based on names, e.g., to implement a naming convention. + * @see {@link https://knockoutjs.com/documentation/component-loaders.html} + */ getConfig?(componentName: string, callback: (result: ComponentConfig | null) => void): void; + /** + * Define this if: you want to take control over how component configurations are interpreted, e.g., if you do not want to use the standard 'viewModel/template' pair format. + * @see {@link https://knockoutjs.com/documentation/component-loaders.html} + */ loadComponent?(componentName: string, config: ComponentConfig, callback: (result: Definition | null) => void): void; + /** + * Define this if: you want to use custom logic to supply DOM nodes for a given template configuration (e.g., using an ajax request to fetch a template by URL). + * @see {@link https://knockoutjs.com/documentation/component-loaders.html} + */ loadTemplate?(componentName: string, templateConfig: any, callback: (result: Node[] | null) => void): void; + /** + * Define this if: you want to use custom logic to supply a viewmodel factory for a given viewmodel configuration (e.g., integrating with a third-party module loader or dependency injection system). + * @see {@link https://knockoutjs.com/documentation/component-loaders.html} + */ loadViewModel?(componentName: string, viewModelConfig: any, callback: (result: any) => void): void; suppressLoaderExceptions?: boolean; } @@ -941,7 +1023,7 @@ interface KnockoutComponents { /** * Registers a component, in the default component loader, to be used by name in the component binding. - * @param componentName Component name. + * @param componentName Component name. Will be used for your custom HTML tag name. * @param config Component configuration. */ register(componentName: string, config: KnockoutComponentTypes.Config | KnockoutComponentTypes.EmptyConfig): void; @@ -956,7 +1038,7 @@ interface KnockoutComponents { */ unregister(componentName: string): void; /** - * Searchs each registered component loader by component name, and returns the viewmodel/template declaration via callback parameter + * Searchs each registered component loader by component name, and returns the viewmodel/template declaration via callback parameter. * @param componentName Component name. * @param callback Function to be called with the viewmodel/template declaration parameter. */ @@ -968,6 +1050,10 @@ interface KnockoutComponents { clearCachedDefinition(componentName: string): void defaultLoader: KnockoutComponentTypes.Loader; loaders: KnockoutComponentTypes.Loader[]; + /** + * Returns the registered component name for a HTML element. Can be overwriten to to control dynamically which HTML element map to which component name. + * @param node html element that corresponds to a custom component. + */ getComponentNameForNode(node: Node): string; } diff --git a/types/koa-bouncer/index.d.ts b/types/koa-bouncer/index.d.ts index af3a8b6693..91b4973893 100644 --- a/types/koa-bouncer/index.d.ts +++ b/types/koa-bouncer/index.d.ts @@ -30,10 +30,10 @@ declare namespace KoaBouncer { isNotIn(arr: any[], tip?: string): Validator isArray(tip?: string): Validator eq(otherVal: string, tip?: string): Validator - gt(otherVal: string, tip?: string): Validator - gte(otherVal: string, tip?: string): Validator - lt(otherVal: string, tip?: string): Validator - lte(otherVal: string, tip?: string): Validator + gt(otherVal: number, tip?: string): Validator + gte(otherVal: number, tip?: string): Validator + lt(otherVal: number, tip?: string): Validator + lte(otherVal: number, tip?: string): Validator isLength(min: number, max: number, tip?: string): Validator defaultTo(valueOrFunction: any): Validator isString(tip?: string): Validator diff --git a/types/koa-bouncer/koa-bouncer-tests.ts b/types/koa-bouncer/koa-bouncer-tests.ts index 0f91658a85..05f84e1b21 100644 --- a/types/koa-bouncer/koa-bouncer-tests.ts +++ b/types/koa-bouncer/koa-bouncer-tests.ts @@ -29,6 +29,9 @@ router.post('/users', async (ctx) => { .isString() .eq(ctx.vals.password1, 'Passwords must match') + ctx.validateBody('age') + .gte(18, 'Must be 18 or older') + console.log(ctx.vals) }) diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index 4df53d0e8b..823cc48059 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -193,6 +193,17 @@ declare class Router { path: string | RegExp | (string | RegExp)[], ...middleware: Array> ): Router; + get( + name: string, + path: string | RegExp, + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; + get( + path: string | RegExp | (string | RegExp)[], + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; /** * HTTP post method @@ -206,6 +217,17 @@ declare class Router { path: string | RegExp | (string | RegExp)[], ...middleware: Array> ): Router; + post( + name: string, + path: string | RegExp, + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; + post( + path: string | RegExp | (string | RegExp)[], + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; /** * HTTP put method @@ -219,6 +241,17 @@ declare class Router { path: string | RegExp | (string | RegExp)[], ...middleware: Array> ): Router; + put( + name: string, + path: string | RegExp, + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; + put( + path: string | RegExp | (string | RegExp)[], + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; /** * HTTP link method @@ -232,6 +265,17 @@ declare class Router { path: string | RegExp | (string | RegExp)[], ...middleware: Array> ): Router; + link( + name: string, + path: string | RegExp, + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; + link( + path: string | RegExp | (string | RegExp)[], + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; /** * HTTP unlink method @@ -245,6 +289,17 @@ declare class Router { path: string | RegExp | (string | RegExp)[], ...middleware: Array> ): Router; + unlink( + name: string, + path: string | RegExp, + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; + unlink( + path: string | RegExp | (string | RegExp)[], + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; /** * HTTP delete method @@ -258,6 +313,17 @@ declare class Router { path: string | RegExp | (string | RegExp)[], ...middleware: Array> ): Router; + delete( + name: string, + path: string | RegExp, + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; + delete( + path: string | RegExp | (string | RegExp)[], + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; /** * Alias for `router.delete()` because delete is a reserved word @@ -271,6 +337,17 @@ declare class Router { path: string | RegExp | (string | RegExp)[], ...middleware: Array> ): Router; + del( + name: string, + path: string | RegExp, + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; + del( + path: string | RegExp | (string | RegExp)[], + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; /** * HTTP head method @@ -284,6 +361,17 @@ declare class Router { path: string | RegExp | (string | RegExp)[], ...middleware: Array> ): Router; + head( + name: string, + path: string | RegExp, + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; + head( + path: string | RegExp | (string | RegExp)[], + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; /** * HTTP options method @@ -297,6 +385,17 @@ declare class Router { path: string | RegExp | (string | RegExp)[], ...middleware: Array> ): Router; + options( + name: string, + path: string | RegExp, + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; + options( + path: string | RegExp | (string | RegExp)[], + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; /** * HTTP path method @@ -310,6 +409,17 @@ declare class Router { path: string | RegExp | (string | RegExp)[], ...middleware: Array> ): Router; + patch( + name: string, + path: string | RegExp, + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; + patch( + path: string | RegExp | (string | RegExp)[], + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; /** * Register route with all methods. @@ -323,6 +433,17 @@ declare class Router { path: string | RegExp | (string | RegExp)[], ...middleware: Array> ): Router; + all( + name: string, + path: string | RegExp, + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; + all( + path: string | RegExp | (string | RegExp)[], + middleware: Koa.Middleware, + routeHandler: Router.IMiddleware + ): Router; /** * Set the path prefix for a Router instance that was already initialized. diff --git a/types/koa-router/koa-router-tests.ts b/types/koa-router/koa-router-tests.ts index 96fa0d1751..1759504f7b 100644 --- a/types/koa-router/koa-router-tests.ts +++ b/types/koa-router/koa-router-tests.ts @@ -125,3 +125,66 @@ app2.use((ctx: Context, next: any) => { }); app2.listen(8000); + +// Prepending middlewares tests + +type IBlah = { blah: string; } +type IWooh = { wooh: string; } + +const router4 = new Router({prefix: "/users"}); + +router4.get('/', + (ctx: Koa.ParameterizedContext, next) => { + ctx.state.blah = "blah"; + ctx.state.wooh = "wooh"; + return next(); + }, + (ctx, next) => { + console.log(ctx.state.blah); + console.log(ctx.state.wooh); + console.log(ctx.state.foo); + ctx.body = 'Hello World!'; + return next(); + }) + +const middleware1: Koa.Middleware = (ctx, next) => { + ctx.state.blah = "blah"; +} + +const middleware2: Koa.Middleware = (ctx, next) => { + ctx.state.wooh = "blah"; +} + +const emptyMiddleware: Koa.Middleware<{}> = (ctx, next) => { +} + +function routeHandler1(ctx: Koa.ParameterizedContext): void { + ctx.body = "234"; +} + +function routeHandler2(ctx: Koa.ParameterizedContext): void { + ctx.body = "234"; +} + +function routeHandler3(ctx: Koa.ParameterizedContext<{}>): void { + ctx.body = "234"; +} + +function routeHandler4(ctx: Router.RouterContext): void { + ctx.body = "234"; +} + +const middleware3 = compose([middleware1, middleware2]); + +router4.get('/foo', middleware3, routeHandler1); +router4.post('/foo', middleware1, routeHandler2); +router4.put('/foo', middleware2, routeHandler3); + +router4.patch("foo", '/foo', middleware3, routeHandler1); +router4.delete('/foo', middleware1, routeHandler2); +router4.head('/foo', middleware2, routeHandler3); + +router4.post('/foo', emptyMiddleware, emptyMiddleware, routeHandler4); +router4.post('/foo', emptyMiddleware, emptyMiddleware, emptyMiddleware, routeHandler4); +router4.get('name', '/foo', emptyMiddleware, emptyMiddleware, routeHandler4); +router4.get('name', '/foo', emptyMiddleware, emptyMiddleware, emptyMiddleware, routeHandler4); \ No newline at end of file diff --git a/types/koa-sslify/index.d.ts b/types/koa-sslify/index.d.ts index 0bf6c0a1ff..418b330586 100644 --- a/types/koa-sslify/index.d.ts +++ b/types/koa-sslify/index.d.ts @@ -1,25 +1,80 @@ -// Type definitions for koa-sslify 2.1 +// Type definitions for koa-sslify 4.0 // Project: https://github.com/turboMaCk/koa-sslify#readme // Definitions by: Matthew Bull +// Mihkel Sokk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as koa from 'koa'; +import * as koa from "koa"; declare namespace sslify { - interface Options { - trustProtoHeader?: boolean; - trustAzureHeader?: boolean; - port?: number; - hostname?: string; - ignoreUrl?: boolean; - temporary?: boolean; - redirectMethods?: string[]; - internalRedirectMethods?: string[]; - specCompliantDisallow?: boolean; - } + interface Options { + /** + * Function used to test if request is secure + */ + resolver?: (ctx: koa.Context) => boolean; + /** + * Hostname for redirect (uses request host if not set) + */ + hostname?: string; + /** + * Port of HTTPS server + */ + port?: number; + /** + * Avoid :443 port in redirect url + */ + skipDefaultPort?: boolean; + /** + * Ignore url path (redirect to domain) + */ + ignoreUrl?: boolean; + /** + * Temporary mode (use 307 Temporary Redirect) + */ + temporary?: boolean; + /** + * Whitelist methods that should be redirected + */ + redirectMethods?: string[]; + /** + * Status returned for disallowed methods + */ + disallowStatus?: number; + } + + /** + * Default HTTPS resolver + * This works when using node.js TLS support + */ + function httpsResolver(ctx: koa.Context): boolean; + + /** + * x-forwarded-proto header resolver + * common for heroku gcp (ingress) etc + */ + function xForwardedProtoResolver(ctx: koa.Context): boolean; + + /** + * Azure resolver + * Azure is using `x-att-ssl` header + */ + function azureResolver(ctx: koa.Context): boolean; + + /** + * Custom proto header factory + */ + function customProtoHeaderResolver( + header: string + ): (ctx: koa.Context) => boolean; + + /** + * Resolver for `Forwarded` header + * see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded + */ + function forwardedResolver(ctx: koa.Context): boolean; } -declare function sslify(options: sslify.Options): koa.Middleware; +declare function sslify(options?: sslify.Options): koa.Middleware; export = sslify; diff --git a/types/koa-sslify/koa-sslify-tests.ts b/types/koa-sslify/koa-sslify-tests.ts index c8dae23bb4..7c87c7c705 100644 --- a/types/koa-sslify/koa-sslify-tests.ts +++ b/types/koa-sslify/koa-sslify-tests.ts @@ -1,40 +1,50 @@ import Koa = require('koa'); import sslify = require('koa-sslify'); +new Koa().use(sslify()); + new Koa().use(sslify({})); new Koa().use(sslify({ - trustAzureHeader: true, + resolver: sslify.xForwardedProtoResolver, })); new Koa().use(sslify({ - trustProtoHeader: true, + resolver: sslify.azureResolver, })); new Koa().use(sslify({ - specCompliantDisallow: true, + resolver: sslify.customProtoHeaderResolver('x-protocol'), })); new Koa().use(sslify({ - port: 1234, + resolver: sslify.forwardedResolver, })); new Koa().use(sslify({ - hostname: 'my-host', + disallowStatus: 405, })); new Koa().use(sslify({ - temporary: false, + port: 1234, })); new Koa().use(sslify({ - internalRedirectMethods: ['GET'], + hostname: 'my-host', })); new Koa().use(sslify({ - redirectMethods: ['GET'], + temporary: false, })); new Koa().use(sslify({ - ignoreUrl: true, + redirectMethods: ['GET'], +})); + +new Koa().use(sslify({ + skipDefaultPort: false, +})); + +new Koa().use(sslify({ + ignoreUrl: true, })); diff --git a/types/koa-sslify/tsconfig.json b/types/koa-sslify/tsconfig.json index 775b453de9..8c1672161b 100644 --- a/types/koa-sslify/tsconfig.json +++ b/types/koa-sslify/tsconfig.json @@ -1,23 +1,16 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6" - ], + "lib": ["es6"], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, - "files": [ - "index.d.ts", - "koa-sslify-tests.ts" - ] -} \ No newline at end of file + "files": ["index.d.ts", "koa-sslify-tests.ts"] +} diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index f99f76817d..708b8af387 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -626,7 +626,7 @@ export interface PathOptions extends InteractiveLayerOptions { opacity?: number; lineCap?: LineCapShape; lineJoin?: LineJoinShape; - dashArray?: string; + dashArray?: string | number[]; dashOffset?: string; fill?: boolean; fillColor?: string; @@ -1134,14 +1134,15 @@ export interface PopupOptions extends DivOverlayOptions { maxWidth?: number; minWidth?: number; maxHeight?: number; + keepInView?: boolean; + closeButton?: boolean; autoPan?: boolean; autoPanPaddingTopLeft?: PointExpression; autoPanPaddingBottomRight?: PointExpression; autoPanPadding?: PointExpression; - keepInView?: boolean; - closeButton?: boolean; autoClose?: boolean; closeOnClick?: boolean; + closeOnEscapeKey?: boolean; } export type Content = string | HTMLElement; @@ -1534,6 +1535,9 @@ export interface MarkerOptions extends InteractiveLayerOptions { opacity?: number; riseOnHover?: boolean; riseOffset?: number; + autoPan?: boolean; + autoPanSpeed?: number; + autoPanPadding?: PointExpression; } export class Marker

    extends Layer { diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index 2e0f139e9d..99ac56dd7f 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -506,7 +506,10 @@ export class MyNewControl extends L.Control { L.marker([1, 2], { icon: L.icon({ iconUrl: 'my-icon.png' - }) + }), + autoPan: true, + autoPanPadding: [10, 20], + autoPanSpeed: 5, }).bindPopup('

    Hi

    '); L.marker([1, 2], { diff --git a/types/lru-cache/index.d.ts b/types/lru-cache/index.d.ts index ed40619b11..2e5e8f562d 100644 --- a/types/lru-cache/index.d.ts +++ b/types/lru-cache/index.d.ts @@ -1,23 +1,127 @@ -// Type definitions for lru-cache 4.1 +// Type definitions for lru-cache 5.1 // Project: https://github.com/isaacs/node-lru-cache // Definitions by: Bart van der Schoor // BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -export = LRU; +declare class LRUCache { + constructor(options?: LRUCache.Options); + constructor(max: number); -declare const LRU: LRU; + /** + * Return total length of objects in cache taking into account `length` options function. + */ + readonly length: number; -interface LRU { - (opts?: LRU.Options): LRU.Cache; - (max: number): LRU.Cache; - new (opts?: LRU.Options): LRU.Cache; - new (max: number): LRU.Cache; + /** + * Return total quantity of objects currently in cache. Note, + * that `stale` (see options) items are returned as part of this item count. + */ + readonly itemCount: number; + + /** + * Same as Options.allowStale. + */ + allowStale: boolean; + + /** + * Same as Options.length. + */ + lengthCalculator(value: V): number; + + /** + * Same as Options.max. Resizes the cache when the `max` changes. + */ + max: number; + + /** + * Same as Options.maxAge. Resizes the cache when the `maxAge` changes. + */ + maxAge: number; + + /** + * Will update the "recently used"-ness of the key. They do what you think. + * `maxAge` is optional and overrides the cache `maxAge` option if provided. + */ + set(key: K, value: V, maxAge?: number): boolean; + + /** + * Will update the "recently used"-ness of the key. They do what you think. + * `maxAge` is optional and overrides the cache `maxAge` option if provided. + * + * If the key is not found, will return `undefined`. + */ + get(key: K): V | undefined; + + /** + * Returns the key value (or `undefined` if not found) without updating + * the "recently used"-ness of the key. + * + * (If you find yourself using this a lot, you might be using the wrong + * sort of data structure, but there are some use cases where it's handy.) + */ + peek(key: K): V | undefined; + + /** + * Check if a key is in the cache, without updating the recent-ness + * or deleting it for being stale. + */ + has(key: K): boolean; + + /** + * Deletes a key out of the cache. + */ + del(key: K): void; + + /** + * Clear the cache entirely, throwing away all values. + */ + reset(): void; + + /** + * Manually iterates over the entire cache proactively pruning old entries. + */ + prune(): void; + + /** + * Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, + * in order of recent-ness. (Ie, more recently used items are iterated over first.) + */ + forEach(callbackFn: (this: T, value: V, key: K, cache: this) => void, thisArg?: T): void; + + /** + * The same as `cache.forEach(...)` but items are iterated over in reverse order. + * (ie, less recently used items are iterated over first.) + */ + rforEach(callbackFn: (this: T, value: V, key: K, cache: this) => void, thisArg?: T): void; + + /** + * Return an array of the keys in the cache. + */ + keys(): K[]; + + /** + * Return an array of the values in the cache. + */ + values(): V[]; + + /** + * Return an array of the cache entries ready for serialization and usage with `destinationCache.load(arr)`. + */ + dump(): Array>; + + /** + * Loads another cache entries array, obtained with `sourceCache.dump()`, + * into the cache. The destination cache is reset before loading new entries + * + * @param cacheEntries Obtained from `sourceCache.dump()` + */ + load(cacheEntries: ReadonlyArray>): void; } -declare namespace LRU { - interface Options { +declare namespace LRUCache { + interface Options { /** * The maximum size of the cache, checked by applying the length * function to all values in the cache. Not setting this is kind of silly, @@ -69,123 +173,21 @@ declare namespace LRU { * not when it is overwritten. */ noDisposeOnSet?: boolean; + + /** + * When using time-expiring entries with `maxAge`, setting this to `true` will make each + * item's effective time update to the current time whenever it is retrieved from cache, + * causing it to not expire. (It can still fall out of cache based on recency of use, of + * course.) + */ + updateAgeOnGet?: boolean; } - interface Cache { - /** - * Return total length of objects in cache taking into account `length` options function. - */ - readonly length: number; - - /** - * Return total quantity of objects currently in cache. Note, - * that `stale` (see options) items are returned as part of this item count. - */ - readonly itemCount: number; - - /** - * Same as Options.allowStale. - */ - allowStale: boolean; - - /** - * Same as Options.length. - */ - lengthCalculator(value: V): number; - - /** - * Same as Options.max. Resizes the cache when the `max` changes. - */ - max: number; - - /** - * Same as Options.maxAge. Resizes the cache when the `maxAge` changes. - */ - maxAge: number; - - /** - * Will update the "recently used"-ness of the key. They do what you think. - * `maxAge` is optional and overrides the cache `maxAge` option if provided. - */ - set(key: K, value: V, maxAge?: number): boolean; - - /** - * Will update the "recently used"-ness of the key. They do what you think. - * `maxAge` is optional and overrides the cache `maxAge` option if provided. - * - * If the key is not found, will return `undefined`. - */ - get(key: K): V | undefined; - - /** - * Returns the key value (or `undefined` if not found) without updating - * the "recently used"-ness of the key. - * - * (If you find yourself using this a lot, you might be using the wrong - * sort of data structure, but there are some use cases where it's handy.) - */ - peek(key: K): V | undefined; - - /** - * Check if a key is in the cache, without updating the recent-ness - * or deleting it for being stale. - */ - has(key: K): boolean; - - /** - * Deletes a key out of the cache. - */ - del(key: K): void; - - /** - * Clear the cache entirely, throwing away all values. - */ - reset(): void; - - /** - * Manually iterates over the entire cache proactively pruning old entries. - */ - prune(): void; - - /** - * Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, - * in order of recent-ness. (Ie, more recently used items are iterated over first.) - */ - forEach(callbackFn: (this: T, value: V, key: K, cache: this) => void, thisArg?: T): void; - - /** - * The same as `cache.forEach(...)` but items are iterated over in reverse order. - * (ie, less recently used items are iterated over first.) - */ - rforEach(callbackFn: (this: T, value: V, key: K, cache: this) => void, thisArg?: T): void; - - /** - * Return an array of the keys in the cache. - */ - keys(): K[]; - - /** - * Return an array of the values in the cache. - */ - values(): V[]; - - /** - * Return an array of the cache entries ready for serialization and usage with `destinationCache.load(arr)`. - */ - dump(): Array>; - - /** - * Loads another cache entries array, obtained with `sourceCache.dump()`, - * into the cache. The destination cache is reset before loading new entries - * - * @param cacheEntries Obtained from `sourceCache.dump()` - */ - load(cacheEntries: ReadonlyArray>): void; - } - - interface LRUEntry { + interface Entry { k: K; v: V; e: number; } } + +export = LRUCache; diff --git a/types/lru-cache/lru-cache-tests.ts b/types/lru-cache/lru-cache-tests.ts index c7d3977f7f..73d7c1ba6a 100644 --- a/types/lru-cache/lru-cache-tests.ts +++ b/types/lru-cache/lru-cache-tests.ts @@ -1,4 +1,4 @@ -import LRU = require('lru-cache'); +import LRUCache = require('lru-cache'); const num = 1; @@ -10,9 +10,9 @@ const foo = { foo() {} }; -const cache = LRU(); -cache; // $ExpectType Cache -LRU({ // $ExpectType Cache +const cache = new LRUCache(); +cache; // $ExpectType LRUCache +new LRUCache({ // $ExpectType LRUCache max: num, maxAge: num, length(value) { @@ -26,9 +26,9 @@ LRU({ // $ExpectType Cache stale: false, noDisposeOnSet: false, }); -LRU(num); // $ExpectType Cache -new LRU(); // $ExpectType Cache -new LRU({ // $ExpectType Cache +new LRUCache(num); // $ExpectType LRUCache +new LRUCache(); // $ExpectType LRUCache +new LRUCache({ // $ExpectType LRUCache max: num, maxAge: num, length: (value) => { @@ -38,7 +38,7 @@ new LRU({ // $ExpectType Cache stale: false, noDisposeOnSet: false, }); -new LRU(num); // $ExpectType Cache +new LRUCache(num); // $ExpectType LRUCache cache.length; // $ExpectType number cache.length = 1; // $ExpectError @@ -80,26 +80,26 @@ cache.prune(); cache.forEach(function(value, key, cache) { value; // $ExpectType Foo key; // $ExpectType string - cache; // $ExpectType Cache - this; // $ExpectType Cache + cache; // $ExpectType LRUCache + this; // $ExpectType LRUCache }); cache.forEach(function(value, key, cache) { value; // $ExpectType Foo key; // $ExpectType string - cache; // $ExpectType Cache + cache; // $ExpectType LRUCache this; // $ExpectType { foo(): void; } }, foo); cache.rforEach(function(value, key, cache) { value; // $ExpectType Foo key; // $ExpectType string - cache; // $ExpectType Cache - this; // $ExpectType Cache + cache; // $ExpectType LRUCache + this; // $ExpectType LRUCache }); cache.rforEach(function(value, key, cache) { value; // $ExpectType Foo key; // $ExpectType string - cache; // $ExpectType Cache + cache; // $ExpectType LRUCache this; // $ExpectType { foo(): void; } }, foo); @@ -107,5 +107,5 @@ cache.keys(); // $ExpectType string[] cache.values(); // $ExpectType Foo[] const dump = cache.dump(); -dump; // $ExpectType LRUEntry[] +dump; // $ExpectType Entry[] cache.load(dump); diff --git a/types/lru-cache/tsconfig.json b/types/lru-cache/tsconfig.json index de5c387339..c7d3687334 100644 --- a/types/lru-cache/tsconfig.json +++ b/types/lru-cache/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "lru-cache-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/lru-cache/tslint.json b/types/lru-cache/tslint.json index 71ee04c4e1..f93cf8562a 100644 --- a/types/lru-cache/tslint.json +++ b/types/lru-cache/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-unnecessary-generics": false - } + "extends": "dtslint/dt.json" } diff --git a/types/lru-cache/v4/index.d.ts b/types/lru-cache/v4/index.d.ts new file mode 100644 index 0000000000..ed40619b11 --- /dev/null +++ b/types/lru-cache/v4/index.d.ts @@ -0,0 +1,191 @@ +// Type definitions for lru-cache 4.1 +// Project: https://github.com/isaacs/node-lru-cache +// Definitions by: Bart van der Schoor +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export = LRU; + +declare const LRU: LRU; + +interface LRU { + (opts?: LRU.Options): LRU.Cache; + (max: number): LRU.Cache; + new (opts?: LRU.Options): LRU.Cache; + new (max: number): LRU.Cache; +} + +declare namespace LRU { + interface Options { + /** + * The maximum size of the cache, checked by applying the length + * function to all values in the cache. Not setting this is kind of silly, + * since that's the whole purpose of this lib, but it defaults to `Infinity`. + */ + max?: number; + + /** + * Maximum age in ms. Items are not pro-actively pruned out as they age, + * but if you try to get an item that is too old, it'll drop it and return + * undefined instead of giving it to you. + */ + maxAge?: number; + + /** + * Function that is used to calculate the length of stored items. + * If you're storing strings or buffers, then you probably want to do + * something like `function(n, key){return n.length}`. The default + * is `function(){return 1}`, which is fine if you want to store + * `max` like-sized things. The item is passed as the first argument, + * and the key is passed as the second argument. + */ + length?(value: V, key?: K): number; + + /** + * Function that is called on items when they are dropped from the cache. + * This can be handy if you want to close file descriptors or do other + * cleanup tasks when items are no longer accessible. Called with `key, value`. + * It's called before actually removing the item from the internal cache, + * so if you want to immediately put it back in, you'll have to do that in + * a `nextTick` or `setTimeout` callback or it won't do anything. + */ + dispose?(key: K, value: V): void; + + /** + * By default, if you set a `maxAge`, it'll only actually pull stale items + * out of the cache when you `get(key)`. (That is, it's not pre-emptively + * doing a `setTimeout` or anything.) If you set `stale:true`, it'll return + * the stale value before deleting it. If you don't set this, then it'll + * return `undefined` when you try to get a stale entry, + * as if it had already been deleted. + */ + stale?: boolean; + + /** + * By default, if you set a `dispose()` method, then it'll be called whenever + * a `set()` operation overwrites an existing key. If you set this option, + * `dispose()` will only be called when a key falls out of the cache, + * not when it is overwritten. + */ + noDisposeOnSet?: boolean; + } + + interface Cache { + /** + * Return total length of objects in cache taking into account `length` options function. + */ + readonly length: number; + + /** + * Return total quantity of objects currently in cache. Note, + * that `stale` (see options) items are returned as part of this item count. + */ + readonly itemCount: number; + + /** + * Same as Options.allowStale. + */ + allowStale: boolean; + + /** + * Same as Options.length. + */ + lengthCalculator(value: V): number; + + /** + * Same as Options.max. Resizes the cache when the `max` changes. + */ + max: number; + + /** + * Same as Options.maxAge. Resizes the cache when the `maxAge` changes. + */ + maxAge: number; + + /** + * Will update the "recently used"-ness of the key. They do what you think. + * `maxAge` is optional and overrides the cache `maxAge` option if provided. + */ + set(key: K, value: V, maxAge?: number): boolean; + + /** + * Will update the "recently used"-ness of the key. They do what you think. + * `maxAge` is optional and overrides the cache `maxAge` option if provided. + * + * If the key is not found, will return `undefined`. + */ + get(key: K): V | undefined; + + /** + * Returns the key value (or `undefined` if not found) without updating + * the "recently used"-ness of the key. + * + * (If you find yourself using this a lot, you might be using the wrong + * sort of data structure, but there are some use cases where it's handy.) + */ + peek(key: K): V | undefined; + + /** + * Check if a key is in the cache, without updating the recent-ness + * or deleting it for being stale. + */ + has(key: K): boolean; + + /** + * Deletes a key out of the cache. + */ + del(key: K): void; + + /** + * Clear the cache entirely, throwing away all values. + */ + reset(): void; + + /** + * Manually iterates over the entire cache proactively pruning old entries. + */ + prune(): void; + + /** + * Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, + * in order of recent-ness. (Ie, more recently used items are iterated over first.) + */ + forEach(callbackFn: (this: T, value: V, key: K, cache: this) => void, thisArg?: T): void; + + /** + * The same as `cache.forEach(...)` but items are iterated over in reverse order. + * (ie, less recently used items are iterated over first.) + */ + rforEach(callbackFn: (this: T, value: V, key: K, cache: this) => void, thisArg?: T): void; + + /** + * Return an array of the keys in the cache. + */ + keys(): K[]; + + /** + * Return an array of the values in the cache. + */ + values(): V[]; + + /** + * Return an array of the cache entries ready for serialization and usage with `destinationCache.load(arr)`. + */ + dump(): Array>; + + /** + * Loads another cache entries array, obtained with `sourceCache.dump()`, + * into the cache. The destination cache is reset before loading new entries + * + * @param cacheEntries Obtained from `sourceCache.dump()` + */ + load(cacheEntries: ReadonlyArray>): void; + } + + interface LRUEntry { + k: K; + v: V; + e: number; + } +} diff --git a/types/lru-cache/v4/lru-cache-tests.ts b/types/lru-cache/v4/lru-cache-tests.ts new file mode 100644 index 0000000000..c7d3977f7f --- /dev/null +++ b/types/lru-cache/v4/lru-cache-tests.ts @@ -0,0 +1,111 @@ +import LRU = require('lru-cache'); + +const num = 1; + +interface Foo { + foo(): void; +} + +const foo = { + foo() {} +}; + +const cache = LRU(); +cache; // $ExpectType Cache +LRU({ // $ExpectType Cache + max: num, + maxAge: num, + length(value) { + value; // $ExpectType Foo + return num; + }, + dispose(key, value) { + key; // $ExpectType string + value; // $ExpectType Foo + }, + stale: false, + noDisposeOnSet: false, +}); +LRU(num); // $ExpectType Cache +new LRU(); // $ExpectType Cache +new LRU({ // $ExpectType Cache + max: num, + maxAge: num, + length: (value) => { + return num; + }, + dispose: (key, value) => {}, + stale: false, + noDisposeOnSet: false, +}); +new LRU(num); // $ExpectType Cache + +cache.length; // $ExpectType number +cache.length = 1; // $ExpectError + +cache.itemCount; // $ExpectType number +cache.itemCount = 1; // $ExpectError + +cache.allowStale; // $ExpectType boolean +cache.allowStale = true; + +cache.lengthCalculator; // $ExpectType (value: Foo) => number +cache.lengthCalculator = () => 1; + +cache.max; // $ExpectType number +cache.max = 1; + +cache.maxAge; // $ExpectType number +cache.maxAge = 1; + +cache.set('foo', foo); // $ExpectType boolean +cache.set(1, foo); // $ExpectError +cache.set('foo', 1); // $ExpectError + +cache.get('foo'); // $ExpectType Foo | undefined +cache.get(1); // $ExpectError + +cache.peek('foo'); // $ExpectType Foo | undefined +cache.peek(1); // $ExpectError + +cache.has('foo'); // $ExpectType boolean +cache.has(1); // $ExpectError + +cache.del('foo'); +cache.del(1); // $ExpectError + +cache.reset(); +cache.prune(); + +cache.forEach(function(value, key, cache) { + value; // $ExpectType Foo + key; // $ExpectType string + cache; // $ExpectType Cache + this; // $ExpectType Cache +}); +cache.forEach(function(value, key, cache) { + value; // $ExpectType Foo + key; // $ExpectType string + cache; // $ExpectType Cache + this; // $ExpectType { foo(): void; } +}, foo); + +cache.rforEach(function(value, key, cache) { + value; // $ExpectType Foo + key; // $ExpectType string + cache; // $ExpectType Cache + this; // $ExpectType Cache +}); +cache.rforEach(function(value, key, cache) { + value; // $ExpectType Foo + key; // $ExpectType string + cache; // $ExpectType Cache + this; // $ExpectType { foo(): void; } +}, foo); + +cache.keys(); // $ExpectType string[] +cache.values(); // $ExpectType Foo[] + +const dump = cache.dump(); +dump; // $ExpectType LRUEntry[] +cache.load(dump); diff --git a/types/internal-ip/v2/tsconfig.json b/types/lru-cache/v4/tsconfig.json similarity index 82% rename from types/internal-ip/v2/tsconfig.json rename to types/lru-cache/v4/tsconfig.json index bae5b7feb8..153f9c56aa 100644 --- a/types/internal-ip/v2/tsconfig.json +++ b/types/lru-cache/v4/tsconfig.json @@ -13,9 +13,7 @@ "../../" ], "paths": { - "internal-ip": [ - "internal-ip/v2" - ] + "lru-cache": ["lru-cache/v4"] }, "types": [], "noEmit": true, @@ -23,6 +21,6 @@ }, "files": [ "index.d.ts", - "internal-ip-tests.ts" + "lru-cache-tests.ts" ] } diff --git a/types/dd-trace/tslint.json b/types/lru-cache/v4/tslint.json similarity index 59% rename from types/dd-trace/tslint.json rename to types/lru-cache/v4/tslint.json index 4f44991c3c..71ee04c4e1 100644 --- a/types/dd-trace/tslint.json +++ b/types/lru-cache/v4/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "no-empty-interface": false + "no-unnecessary-generics": false } } diff --git a/types/mangopay2-nodejs-sdk/index.d.ts b/types/mangopay2-nodejs-sdk/index.d.ts index 516f1c44f9..78629b7232 100644 --- a/types/mangopay2-nodejs-sdk/index.d.ts +++ b/types/mangopay2-nodejs-sdk/index.d.ts @@ -1774,7 +1774,7 @@ declare namespace MangoPay { /** * This is the URL where to redirect users to proceed to 3D secure validation */ - SecureModeRedirectUrl: string; + SecureModeRedirectURL: string; /** * This is the URL where users are automatically redirected after 3D secure validation (if activated) @@ -2596,7 +2596,7 @@ declare namespace MangoPay { /** * This is the URL where to redirect users to proceed to 3D secure validation */ - SecureModeRedirectUrl: string; + SecureModeRedirectURL: string; } interface CreateCardDirectPayIn { diff --git a/types/material-ui/material-ui-tests.tsx b/types/material-ui/material-ui-tests.tsx index 9cc7143d9b..ac32788c4b 100644 --- a/types/material-ui/material-ui-tests.tsx +++ b/types/material-ui/material-ui-tests.tsx @@ -4227,7 +4227,7 @@ function wrapState(ComposedComponent: ComponentClass<__MaterialUI.List.Selectabl }; } -const SelectableList = wrapState(makeSelectable(List)); +const SelectableList = wrapState(makeSelectable<{}>(List)); const ListExampleSelectable = () => ( diff --git a/types/mem-fs-editor/tsconfig.json b/types/mem-fs-editor/tsconfig.json index 52623549e4..3f6396792c 100644 --- a/types/mem-fs-editor/tsconfig.json +++ b/types/mem-fs-editor/tsconfig.json @@ -12,6 +12,9 @@ "typeRoots": [ "../" ], + "paths": { + "lru-cache": ["lru-cache/v4"] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/meteor-universe-i18n/index.d.ts b/types/meteor-universe-i18n/index.d.ts index a577b0185e..1596ceef81 100644 --- a/types/meteor-universe-i18n/index.d.ts +++ b/types/meteor-universe-i18n/index.d.ts @@ -65,6 +65,7 @@ declare module "meteor/universe:i18n" { // events function onChangeLocale(callback: (locale: string) => void): void; + function offChangeLocale(callback: (locale: string) => void): void; } interface ReactComponentProps { diff --git a/types/mongoose-paginate-v2/index.d.ts b/types/mongoose-paginate-v2/index.d.ts index df4c1f7419..43848598b2 100644 --- a/types/mongoose-paginate-v2/index.d.ts +++ b/types/mongoose-paginate-v2/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for mongoose-paginate-v2 1.0 -// Project: https://github.com/aravindnc/mongoose-paginate-v2 +// Project: https://github.com/webgangster/mongoose-paginate-v2 // Definitions by: Linus Brolin // simonxca // woutgg diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 2a01b58a95..e51290b451 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -18,6 +18,7 @@ // Emmanuel Gautier // Frontend Monster // Ming Chen +// Olga Isakova // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -1060,12 +1061,25 @@ declare module "mongoose" { validateBeforeSave?: boolean; /** defaults to "__v" */ versionKey?: string | boolean; + /** + * By default, Mongoose will automatically + * select() any populated paths. + * To opt out, set selectPopulatedPaths to false. + */ + selectPopulatedPaths?: boolean; /** * skipVersioning allows excluding paths from * versioning (the internal revision will not be * incremented even if these paths are updated). */ skipVersioning?: any; + /** + * Validation errors in a single nested schema are reported + * both on the child and on the parent schema. + * Set storeSubdocValidationError to false on the child schema + * to make Mongoose only report the parent error. + */ + storeSubdocValidationError?: boolean; /** * If set timestamps, mongoose assigns createdAt * and updatedAt fields to your schema, the type @@ -1722,6 +1736,9 @@ declare module "mongoose" { * If later in the query chain a method returns Query, we will need to know type T. * So we save this type as the second type parameter in DocumentQuery. Since people have * been using Query, we set it as an alias of DocumentQuery. + * + * Furthermore, Query is used for function that has an option { rawResult: true }. + * for instance findOneAndUpdate. */ class Query extends DocumentQuery { } class DocumentQuery extends mquery { @@ -1864,7 +1881,7 @@ declare module "mongoose" { equals(val: T): this; /** Executes the query */ - exec(callback?: (err: any, res: T) => void): Promise; + exec(callback?: (err: NativeError, res: T) => void): Promise; exec(operation: string | Function, callback?: (err: any, res: T) => void): Promise; /** Specifies an $exists condition */ @@ -1895,10 +1912,16 @@ declare module "mongoose" { * Issues a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the * callback. Executes immediately if callback is passed. + * + * If mongoose option 'useFindAndModify': set to false it uses native findOneAndUpdate() rather than deprecated findAndModify(). + * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set */ findOneAndRemove(callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery & QueryHelpers; + findOneAndRemove(conditions: any, options: { rawResult: true } & QueryFindOneAndRemoveOptions, + callback?: (error: any, doc: mongodb.FindAndModifyWriteOpResultObject, result: any) => void) + : Query> & QueryHelpers; findOneAndRemove(conditions: any, options: QueryFindOneAndRemoveOptions, callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery & QueryHelpers; @@ -1906,6 +1929,9 @@ declare module "mongoose" { * Issues a mongodb findAndModify update command. * Finds a matching document, updates it according to the update arg, passing any options, and returns * the found document (if any) to the callback. The query executes immediately if callback is passed. + * + * If mongoose option 'useFindAndModify': set to false it uses native findOneAndUpdate() rather than deprecated findAndModify(). + * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set */ findOneAndUpdate(callback?: (err: any, doc: DocType | null) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(update: any, @@ -1913,8 +1939,15 @@ declare module "mongoose" { findOneAndUpdate(query: any, update: any, callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(query: any, update: any, - options: { upsert: true, new: true } & QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: DocType, res: any) => void): DocumentQuery & QueryHelpers; + options: { rawResult: true } & { upsert: true } & { new: true } & QueryFindOneAndUpdateOptions, + callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject, res: any) => void) + : Query> & QueryHelpers; + findOneAndUpdate(query: any, update: any, + options: { upsert: true } & { new: true } & QueryFindOneAndUpdateOptions, + callback?: (err: any, doc: DocType, res: any) => void): DocumentQuery & QueryHelpers; + findOneAndUpdate(query: any, update: any, options: { rawResult: true } & QueryFindOneAndUpdateOptions, + callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject, res: any) => void) + : Query> & QueryHelpers; findOneAndUpdate(query: any, update: any, options: QueryFindOneAndUpdateOptions, callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery & QueryHelpers; @@ -2238,12 +2271,21 @@ declare module "mongoose" { class mquery { } interface QueryFindOneAndRemoveOptions { - /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ + /** + * if multiple docs are found by the conditions, sets the sort order to choose + * which doc to update + */ sort?: any; /** puts a time limit on the query - requires mongodb >= 2.6.0 */ maxTimeMS?: number; - /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ + /** sets the document fields to return */ + select?: any; + /** like select, it determines which fields to return */ + projection?: any; + /** if true, returns the raw result from the MongoDB driver */ rawResult?: boolean; + /** overwrites the schema's strict mode option for this update */ + strict?: boolean|string; } interface QueryFindOneAndUpdateOptions extends QueryFindOneAndRemoveOptions { @@ -2251,8 +2293,6 @@ declare module "mongoose" { new?: boolean; /** creates the object if it doesn't exist. defaults to false. */ upsert?: boolean; - /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ - fields?: any | string; /** if true, runs update validators on this command. Update validators validate the update operation against the model's schema. */ runValidators?: boolean; /** @@ -2270,6 +2310,8 @@ declare module "mongoose" { * Turn on this option to aggregate all the cast errors. */ multipleCastError?: boolean; + /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ + fields?: any | string; } interface QueryUpdateOptions extends ModelUpdateOptions { @@ -2998,17 +3040,21 @@ declare module "mongoose" { * findByIdAndRemove(id, ...) is equivalent to findOneAndRemove({ _id: id }, ...). * Finds a matching document, removes it, passing the found document (if any) to the callback. * Executes immediately if callback is passed, else a Query object is returned. + * + * If mongoose option 'useFindAndModify': set to false it uses native findOneAndUpdate() rather than deprecated findAndModify(). + * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set + * + * Note: same signatures as findByIdAndDelete + * * @param id value of _id to query by */ findByIdAndRemove(): DocumentQuery & QueryHelpers; findByIdAndRemove(id: any | number | string, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; - findByIdAndRemove(id: any | number | string, options: { - /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ - sort?: any; - /** sets the document fields to return */ - select?: any; - }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; + findByIdAndRemove(id: any | number | string, options: QueryFindOneAndRemoveOptions, + callback?: (err: any, res: mongodb.FindAndModifyWriteOpResultObject) => void) + : Query> & QueryHelpers; + findByIdAndRemove(id: any | number | string, options: QueryFindOneAndRemoveOptions, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** @@ -3016,31 +3062,44 @@ declare module "mongoose" { * findByIdAndDelete(id, ...) is equivalent to findByIdAndDelete({ _id: id }, ...). * Finds a matching document, removes it, passing the found document (if any) to the callback. * Executes immediately if callback is passed, else a Query object is returned. + * + * Note: same signatures as findByIdAndRemove + * * @param id value of _id to query by */ - findByIdAndDelete(): DocumentQuery; + findByIdAndDelete(): DocumentQuery & QueryHelpers; findByIdAndDelete(id: any | number | string, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; - findByIdAndDelete(id: any | number | string, options: { - /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ - sort?: any; - /** sets the document fields to return */ - select?: any; - }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; + findByIdAndDelete(id: any | number | string, options: QueryFindOneAndRemoveOptions, + callback?: (err: any, res: mongodb.FindAndModifyWriteOpResultObject) => void) + : Query> & QueryHelpers; + findByIdAndDelete(id: any | number | string, options: QueryFindOneAndRemoveOptions, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) * is equivalent to findOneAndUpdate({ _id: id }, ...). + * + * If mongoose option 'useFindAndModify': set to false it uses native findOneAndUpdate() rather than deprecated findAndModify(). + * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set + * * @param id value of _id to query by */ findByIdAndUpdate(): DocumentQuery & QueryHelpers; findByIdAndUpdate(id: any | number | string, update: any, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findByIdAndUpdate(id: any | number | string, update: any, - options: { upsert: true, new: true } & ModelFindByIdAndUpdateOptions, + options: { rawResult: true } & { upsert: true } & { new: true } & QueryFindOneAndUpdateOptions, callback?: (err: any, res: T) => void): DocumentQuery & QueryHelpers; findByIdAndUpdate(id: any | number | string, update: any, - options: ModelFindByIdAndUpdateOptions, + options: { upsert: true, new: true } & QueryFindOneAndUpdateOptions, + callback?: (err: any, res: mongodb.FindAndModifyWriteOpResultObject) => void) + : Query> & QueryHelpers; + findByIdAndUpdate(id: any | number | string, update: any, + options: { rawResult : true } & QueryFindOneAndUpdateOptions, + callback?: (err: any, res: mongodb.FindAndModifyWriteOpResultObject) => void) + : Query> & QueryHelpers; + findByIdAndUpdate(id: any | number | string, update: any, + options: QueryFindOneAndUpdateOptions, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** @@ -3059,62 +3118,62 @@ declare module "mongoose" { * Issue a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the callback. * Executes immediately if callback is passed else a Query object is returned. + * + * If mongoose option 'useFindAndModify': set to false it uses native findOneAndUpdate() rather than deprecated findAndModify(). + * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set + * + * Note: same signatures as findOneAndDelete + * */ findOneAndRemove(): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; - findOneAndRemove(conditions: any, options: { - /** - * if multiple docs are found by the conditions, sets the sort order to choose - * which doc to update - */ - sort?: any; - /** puts a time limit on the query - requires mongodb >= 2.6.0 */ - maxTimeMS?: number; - /** sets the document fields to return */ - select?: any; - }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; + findOneAndRemove(conditions: any, options: { rawResult: true } & QueryFindOneAndRemoveOptions, + callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject, res: any) => void) + : Query> & QueryHelpers; + findOneAndRemove(conditions: any, options: QueryFindOneAndRemoveOptions, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findOneAndDelete command. * Finds a matching document, removes it, passing the found document (if any) to the * callback. Executes immediately if callback is passed. + * + * Note: same signatures as findOneAndRemove + * */ findOneAndDelete(): DocumentQuery & QueryHelpers; findOneAndDelete(conditions: any, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; - findOneAndDelete(conditions: any, options: { - /** - * if multiple docs are found by the conditions, sets the sort order to choose - * which doc to update - */ - sort?: any; - /** puts a time limit on the query - requires mongodb >= 2.6.0 */ - maxTimeMS?: number; - /** sets the document fields to return */ - select?: any; - /** like select, it determines which fields to return */ - projection?: any; - /** if true, returns the raw result from the MongoDB driver */ - rawResult?: boolean; - /** overwrites the schema's strict mode option for this update */ - strict?: boolean|string; - }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; + findOneAndDelete(conditions: any, options: { rawResult: true } & QueryFindOneAndRemoveOptions, + callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject, res: any) => void) + : Query> & QueryHelpers; + findOneAndDelete(conditions: any, options: QueryFindOneAndRemoveOptions, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify update command. * Finds a matching document, updates it according to the update arg, passing any options, * and returns the found document (if any) to the callback. The query executes immediately * if callback is passed else a Query object is returned. + * ++ * If mongoose option 'useFindAndModify': set to false it uses native findOneAndUpdate() rather than the deprecated findAndModify(). ++ * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-set */ findOneAndUpdate(): DocumentQuery & QueryHelpers; findOneAndUpdate(conditions: any, update: any, callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(conditions: any, update: any, - options: { upsert: true, new: true } & ModelFindOneAndUpdateOptions, + options: { rawResult : true } & { upsert: true, new: true } & QueryFindOneAndUpdateOptions, + callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject, res: any) => void) + : Query> & QueryHelpers; + findOneAndUpdate(conditions: any, update: any, + options: { upsert: true, new: true } & QueryFindOneAndUpdateOptions, callback?: (err: any, doc: T, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(conditions: any, update: any, - options: ModelFindOneAndUpdateOptions, + options: { rawResult: true } & QueryFindOneAndUpdateOptions, + callback?: (err: any, doc: mongodb.FindAndModifyWriteOpResultObject, res: any) => void) + : Query> & QueryHelpers; + findOneAndUpdate(conditions: any, update: any, + options: QueryFindOneAndUpdateOptions, callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery & QueryHelpers; /** @@ -3308,43 +3367,6 @@ declare module "mongoose" { session?: ClientSession | null; } - interface ModelFindByIdAndUpdateOptions extends ModelOptions { - /** true to return the modified document rather than the original. defaults to false */ - new?: boolean; - /** creates the object if it doesn't exist. defaults to false. */ - upsert?: boolean; - /** - * if true, runs update validators on this command. Update validators validate the - * update operation against the model's schema. - */ - runValidators?: boolean; - /** - * if this and upsert are true, mongoose will apply the defaults specified in the model's - * schema if a new document is created. This option only works on MongoDB >= 2.4 because - * it relies on MongoDB's $setOnInsert operator. - */ - setDefaultsOnInsert?: boolean; - /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ - sort?: any; - /** sets the document fields to return */ - select?: any; - /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ - rawResult?: boolean; - /** overwrites the schema's strict mode option for this update */ - strict?: boolean; - /** The context option lets you set the value of this in update validators to the underlying query. */ - context?: string; - } - - interface ModelFindOneAndUpdateOptions extends ModelFindByIdAndUpdateOptions { - /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ - fields?: any | string; - /** puts a time limit on the query - requires mongodb >= 2.6.0 */ - maxTimeMS?: number; - /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ - rawResult?: boolean; - } - interface ModelPopulateOptions { /** space delimited path(s) to populate */ path: string; diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 6d487dd14d..6eda6d5eb0 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -1021,7 +1021,7 @@ query.findOne(function (err, res) { query.findOneAndRemove({name: 'aa'}, { rawResult: true }, function (err, doc) { - doc.execPopulate(); + doc.lastErrorObject }).findOneAndRemove(); query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, { @@ -1911,6 +1911,14 @@ LocModel.findOneAndUpdate().exec().then(function (arg) { arg.openingTimes; } }); +LocModel.findOneAndUpdate( + // find a document with that filter + {name: "aa"}, + // document to insert when nothing was found + { $set: {name: "bb"} }, + // options + {upsert: true, new: true, runValidators: true, + rawResult: true, multipleCastError: true }); LocModel.geoSearch({}, { near: [1, 2], maxDistance: 22 diff --git a/types/mui-datatables/index.d.ts b/types/mui-datatables/index.d.ts index 2dffabbc53..1bdf9fc07f 100644 --- a/types/mui-datatables/index.d.ts +++ b/types/mui-datatables/index.d.ts @@ -105,7 +105,7 @@ export interface MUIDataTableColumnOptions { hint?: string; customHeadRender?: (columnMeta: MUIDataTableCustomHeadRenderer, updateDirection: (params: any) => any) => string; customBodyRender?: (value: any, tableMeta: MUIDataTableMeta, updateValue: (s: any, c: any, p: any) => any) => string | React.ReactNode; - setCellProps?: (cellValue: string, rowIndex: number, columnIndex: number) => string; + setCellProps?: (cellValue: string, rowIndex: number, columnIndex: number) => object; } export interface MUIDataTableOptions { @@ -117,7 +117,7 @@ export interface MUIDataTableOptions { textLabels?: MUIDataTableTextLabels; pagination?: boolean; selectableRows?: boolean; - IsRowSelectable?: (dataIndex: any) => boolean; + IsRowSelectable?: (dataIndex: number) => boolean; resizableColumns?: boolean; expandableRows?: boolean; renderExpandableRow?: (rowData: string[], rowMeta: { dataIndex: number; rowIndex: number }) => React.ReactNode; @@ -143,7 +143,7 @@ export interface MUIDataTableOptions { onRowsSelect?: (currentRowsSelected: any[], rowsSelected: any[]) => void; onRowsDelete?: (rowsDeleted: any[]) => void; onRowClick?: (rowData: string[], rowMeta: { dataIndex: number; rowIndex: number }) => void; - onCellClick?: (colIndex: number, rowIndex: number) => void; + onCellClick?: (colData: any, cellMeta: { colIndex: number, rowIndex: number, dataIndex: number }) => void; onChangePage?: (currentPage: number) => void; onChangeRowsPerPage?: (numberOfRows: number) => void; onSearchChange?: (searchText: string) => void; @@ -151,7 +151,7 @@ export interface MUIDataTableOptions { onColumnSortChange?: (changedColumn: string, direction: string) => void; onColumnViewChange?: (changedColumn: string, action: string) => void; onTableChange?: (action: string, tableState: object) => void; - setRowProps?: (row: any[], rowIndex: number) => any; + setRowProps?: (row: any[], rowIndex: number) => object; } export type MUIDataTableColumnDef = string | MUIDataTableColumn; diff --git a/types/mumath/index.d.ts b/types/mumath/index.d.ts new file mode 100644 index 0000000000..8967bafa4f --- /dev/null +++ b/types/mumath/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for mumath 3.3 +// Project: https://github.com/dfcreative/mumath +// Definitions by: Adam Zerella +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.3 + +/** + * Detects proper clamp min/max. + */ +export function clamp(value: number, left: number, right: number): number; + +/** + * Get closest value out of a set. + */ +export function closest(value: number, list: number[]): number; + +/** + * Check if one number is multiple of other + * Same as a % b === 0, but with precision check. + */ +export function isMultiple(a: number, b: number, eps?: number): boolean; + +/** + * Return quadratic length of a vector. + */ +export function len(a: number, b: number): number; + +/** + * Return value interpolated between x and y. + */ +export function lerp(x: number, y: number, ratio: number): number; + +/** + * An enhanced mod-loop, like fmod — loops value within a frame. + */ +export function mod(value: number, max: number, min?: number): number; + +/** + * Get order of magnitude for a number. + */ +export function order(value: number): number; + +/** + * Get precision from float: + */ +export function precision(value: number): number; + +/** + * Rounds value to optional step. + */ +export function round(value: number, step?: number): number; + +/** + * Get first scale out of a list of basic scales, aligned to the power. E. g. + * step(.37, [1, 2, 5]) → .5 step(456, [1, 2]) → 1000 + * Similar to closest, but takes all possible powers of scales. + */ +export function scale(value: number, list: number[]): number; + +/** + * Whether element is between left & right, including. + */ +export function within(value: number, left: number, right: number): number; diff --git a/types/mumath/mumath-tests.ts b/types/mumath/mumath-tests.ts new file mode 100644 index 0000000000..c0fed04336 --- /dev/null +++ b/types/mumath/mumath-tests.ts @@ -0,0 +1,25 @@ +import * as mumath from "mumath"; + +mumath.clamp(1, 2, 3); + +mumath.closest(5, [1, 7, 3, 6, 10]); + +mumath.isMultiple(5, 10, 1.000074); +mumath.isMultiple(5, 10); + +mumath.len(15, 1.0); + +mumath.lerp(1, 2, 3); + +mumath.mod(1, 2, 3); +mumath.mod(1, 2); + +mumath.order(5); + +mumath.precision(5.0000001); + +mumath.round(0.3, 0.5); + +mumath.scale(5.93, [1.0, 35, 10, 7.135]); + +mumath.within(5, 1, 10); diff --git a/types/mumath/tsconfig.json b/types/mumath/tsconfig.json new file mode 100644 index 0000000000..67aa9c2b29 --- /dev/null +++ b/types/mumath/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [ + + ], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mumath-tests.ts" + ] +} diff --git a/types/mumath/tslint.json b/types/mumath/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/mumath/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/mustache-express/tsconfig.json b/types/mustache-express/tsconfig.json index 9afb989b62..13c146f986 100644 --- a/types/mustache-express/tsconfig.json +++ b/types/mustache-express/tsconfig.json @@ -12,6 +12,9 @@ "typeRoots": [ "../" ], + "paths": { + "lru-cache": [ "lru-cache/v4" ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/next-server/dynamic.d.ts b/types/next-server/dynamic.d.ts index 2d06273bd5..61847c2d3c 100644 --- a/types/next-server/dynamic.d.ts +++ b/types/next-server/dynamic.d.ts @@ -7,9 +7,9 @@ import { type Omit = Pick>; -type AsyncComponent

    = Promise>; +type AsyncComponent

    = Promise | { default: React.ComponentType

    }>; type AsyncComponentLoader

    = () => AsyncComponent

    ; -type ModuleMapping = Record; +type ModuleMapping = Record; type LoadedModuleMapping = Record; interface NextDynamicOptions

    extends Omit { @@ -31,10 +31,10 @@ type DynamicComponent

    = React.ComponentType

    & LoadableComponent; * https://github.com/zeit/next.js/blob/7.0.0/lib/dynamic.js#L55 */ declare function dynamic

    ( - options: AsyncComponentLoader

    | AsyncComponent

    | NextDynamicOptions

    + asyncModuleOrOptions: AsyncComponentLoader

    | AsyncComponent

    | NextDynamicOptions

    ): DynamicComponent

    ; declare function dynamic

    ( - asyncModule: AsyncComponent

    , + asyncModule: AsyncComponentLoader

    | AsyncComponent

    , options: NextDynamicOptions

    ): DynamicComponent

    ; diff --git a/types/next-server/test/imports/no-default.tsx b/types/next-server/test/imports/no-default.tsx new file mode 100644 index 0000000000..1f406a3fe3 --- /dev/null +++ b/types/next-server/test/imports/no-default.tsx @@ -0,0 +1,7 @@ +import * as React from "react"; + +interface Props { + foo: string; +} + +export const MyComponent: React.SFC = ({ foo: text }) => {text}; diff --git a/types/next-server/test/imports/with-default.tsx b/types/next-server/test/imports/with-default.tsx new file mode 100644 index 0000000000..f448a16680 --- /dev/null +++ b/types/next-server/test/imports/with-default.tsx @@ -0,0 +1,11 @@ +import * as React from "react"; + +interface Props { + foo: boolean; +} + +export default class MyComponent extends React.Component { + render() { + return this.props.foo ?

    : null; + } +} diff --git a/types/next-server/test/next-server-dynamic-tests.tsx b/types/next-server/test/next-server-dynamic-tests.tsx index 07844cad08..ae4297e189 100644 --- a/types/next-server/test/next-server-dynamic-tests.tsx +++ b/types/next-server/test/next-server-dynamic-tests.tsx @@ -1,12 +1,7 @@ import * as React from "react"; import dynamic, { LoadingComponentProps } from "next-server/dynamic"; -// You'd typically do this via import('./MyComponent') -interface MyComponentProps { - foo: string; -} -const MyComponent: React.StatelessComponent = () =>
    I'm async!
    ; -const asyncComponent = Promise.resolve(MyComponent); +const asyncComponent = import('./imports/with-default'); // Examples from // https://github.com/zeit/next.js/#dynamic-import @@ -17,30 +12,31 @@ const LoadingComponent: React.StatelessComponent = ({ }) =>

    loading...

    ; // 1. Basic Usage (Also does SSR) -const DynamicComponent = dynamic(asyncComponent); -const dynamicComponentJSX = ; +const Test1 = dynamic(asyncComponent); +const test1JSX = ; // 1.1 Basic Usage (Loader function) -const DynamicComponent2 = dynamic(() => asyncComponent); -const dynamicComponent2JSX = ; +const Test1Func = dynamic(() => asyncComponent); +const test1FuncJSX = ; -// 2. With Custom Loading Component -const DynamicComponentWithCustomLoading = dynamic(asyncComponent, { - loading: LoadingComponent -}); -const dynamicComponentWithCustomLoadingJSX = ; - -// 3. With No SSR -const DynamicComponentWithNoSSR = dynamic(asyncComponent, { +// 2. With Custom Options +const Test2 = dynamic(() => asyncComponent, { + loading: LoadingComponent, ssr: false }); +const test2JSX = ; // 4. With Multiple Modules At Once -const HelloBundle = dynamic({ +// TODO: Mapped components still doesn't infer their props. +interface BundleComponentProps { + foo: string; +} + +const HelloBundle = dynamic({ modules: () => { const components = { - Hello1: asyncComponent, - Hello2: asyncComponent + Hello1: () => asyncComponent, + Hello2: () => asyncComponent }; return components; @@ -64,6 +60,6 @@ const LoadableComponent = dynamic({ }); // 6. No loading -const DynamicComponentWithNoLoading = dynamic(asyncComponent, { +const DynamicComponentWithNoLoading = dynamic(() => asyncComponent, { loading: () => null }); diff --git a/types/next-server/tsconfig.json b/types/next-server/tsconfig.json index 4d72dadef2..f05382ea65 100644 --- a/types/next-server/tsconfig.json +++ b/types/next-server/tsconfig.json @@ -33,6 +33,8 @@ "test/next-server-head-tests.tsx", "test/next-server-link-tests.tsx", "test/next-server-dynamic-tests.tsx", - "test/next-server-router-tests.tsx" + "test/next-server-router-tests.tsx", + "test/imports/no-default.tsx", + "test/imports/with-default.tsx" ] } diff --git a/types/next/test/next-constants-tests.ts b/types/next/test/next-constants-tests.ts deleted file mode 100644 index 64413ea97c..0000000000 --- a/types/next/test/next-constants-tests.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { - PHASE_DEVELOPMENT_SERVER, - IS_BUNDLED_PAGE_REGEX -} from "next/constants"; - -const isIndexPage = IS_BUNDLED_PAGE_REGEX.test( - "static/CjW0mFnyG80HdP4eSUiy7/pages/index.js" -); - -// Example taken from: https://github.com/cyrilwanner/next-compose-plugins/blob/a25b313899638912cc9defc0be072f4fe4a1e855/README.md -const config = (nextConfig: any = {}) => { - return { - ...nextConfig, - - // define in which phases this plugin should get applied. - // you can also use multiple phases or negate them. - // however, users can still overwrite them in their configuration if they really want to. - phases: [PHASE_DEVELOPMENT_SERVER], - - webpack(config: any, options: any) { - // do something here which only gets applied during development server phase - - if (typeof nextConfig.webpack === "function") { - return nextConfig.webpack(config, options); - } - - return config; - } - }; -}; diff --git a/types/next/test/next-dynamic-tests.tsx b/types/next/test/next-dynamic-tests.tsx deleted file mode 100644 index 3e929e5cd0..0000000000 --- a/types/next/test/next-dynamic-tests.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import * as React from "react"; -import dynamic, { LoadingComponentProps } from "next/dynamic"; - -// You'd typically do this via import('./MyComponent') -interface MyComponentProps { - foo: string; -} -const MyComponent: React.FunctionComponent = () =>
    I'm async!
    ; -const asyncComponent = Promise.resolve(MyComponent); - -// Examples from -// https://github.com/zeit/next.js/#dynamic-import - -const LoadingComponent: React.StatelessComponent = ({ - isLoading, - error -}) =>

    loading...

    ; - -// 1. Basic Usage (Also does SSR) -const DynamicComponent = dynamic(asyncComponent); -const dynamicComponentJSX = ; - -// 2. With Custom Loading Component -const DynamicComponentWithCustomLoading = dynamic(asyncComponent, { - loading: LoadingComponent -}); -const dynamicComponentWithCustomLoadingJSX = ; - -// 3. With No SSR -const DynamicComponentWithNoSSR = dynamic(asyncComponent, { - ssr: false -}); - -// 4. With Multiple Modules At Once -const HelloBundle = dynamic({ - modules: () => { - const components = { - Hello1: asyncComponent, - Hello2: asyncComponent - }; - - return components; - }, - render: (props, { Hello1, Hello2 }) => ( -
    -

    {props.foo}

    - - -
    - ) -}); -const helloBundleJSX = ; - -// 5. With plain Loadable options -const LoadableComponent = dynamic({ - loader: () => asyncComponent, - loading: LoadingComponent, - delay: 200, - timeout: 10000 -}); - -// 6. No loading -const DynamicComponentWithNoLoading = dynamic(asyncComponent, { - loading: () => null -}); diff --git a/types/next/test/next-head-tests.tsx b/types/next/test/next-head-tests.tsx deleted file mode 100644 index 735402ca9a..0000000000 --- a/types/next/test/next-head-tests.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import Head, * as head from "next/head"; -import * as React from "react"; - -const elements: JSX.Element[] = head.defaultHead(); -const jsx = {elements}; - -if (!Head.canUseDOM) { - Head.rewind().map(x => [x.key, x.props, x.type]); -} - -Head.peek().map(x => [x.key, x.props, x.type]); diff --git a/types/next/test/next-link-tests.tsx b/types/next/test/next-link-tests.tsx deleted file mode 100644 index 2a85fec1ad..0000000000 --- a/types/next/test/next-link-tests.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import Link from "next/link"; -import * as React from "react"; - -const links = ( -
    - { - console.log("Handled error!", e); - }} - prefetch - replace - scroll - shallow - > - Gotta link to somewhere! - - - All props are optional! - -
    -); diff --git a/types/next/test/next-router-tests.tsx b/types/next/test/next-router-tests.tsx deleted file mode 100644 index b06c1ad3a7..0000000000 --- a/types/next/test/next-router-tests.tsx +++ /dev/null @@ -1,110 +0,0 @@ -import Router, { withRouter, WithRouterProps } from "next/router"; -import * as React from "react"; -import * as qs from "querystring"; - -Router.readyCallbacks.push(() => { - console.log("I'll get called when the router initializes."); -}); -Router.ready(() => { - console.log( - "I'll get called immediately if the router initializes, or when it eventually does.", - ); -}); - -// Access readonly properties of the router. - -Object.keys(Router.components).forEach(key => { - const c = Router.components[key]; - c.err.isAnAny; - - return ; -}); - -function split(routeLike: string) { - routeLike.split("/").forEach(part => { - console.log("path part: ", part); - }); -} - -if (Router.asPath) { - split(Router.asPath); - split(Router.asPath); -} - -split(Router.pathname); - -const query = `?${qs.stringify(Router.query)}`; - -// Assign some callback methods. -Router.events.on('routeChangeStart', (url: string) => console.log("Route is starting to change.", url)); -Router.events.on('beforeHistoryChange', (as: string) => console.log("History hasn't changed yet.", as)); -Router.events.on('routeChangeComplete', (url: string) => console.log("Route change is complete.", url)); -Router.events.on('routeChangeError', (err: any, url: string) => console.log("Route change errored.", err, url)); - -// Call methods on the router itself. -Router.reload("/route").then(() => console.log("route was reloaded")); -Router.back(); -Router.beforePopState(({ url }) => !!url); - -Router.push("/route").then((success: boolean) => - console.log("route push success: ", success), -); -Router.push("/route", "/asRoute").then((success: boolean) => - console.log("route push success: ", success), -); -Router.push("/route", "/asRoute", { shallow: false }).then((success: boolean) => - console.log("route push success: ", success), -); - -Router.replace("/route").then((success: boolean) => - console.log("route replace success: ", success), -); -Router.replace("/route", "/asRoute").then((success: boolean) => - console.log("route replace success: ", success), -); -Router.replace("/route", "/asRoute", { - shallow: false, -}).then((success: boolean) => console.log("route replace success: ", success)); - -Router.prefetch("/route").then(Component => { - const element = ; -}); - -interface TestComponentProps { - testValue: string; -} - -class TestComponent extends React.Component { - state = { ready: false }; - - constructor(props: TestComponentProps & WithRouterProps) { - super(props); - if (props.router) { - props.router.ready(() => { - this.setState({ ready: true }); - }); - } - } - - render() { - return ( -
    -

    {this.state.ready ? 'Ready' : 'Not Ready'}

    -

    Route: {this.props.router ? this.props.router.route : ""}

    -

    Another prop: {this.props.testValue}

    -
    - ); - } -} - -withRouter(TestComponent); - -interface TestFCQuery { - test?: string; -} - -interface TestFCProps extends WithRouterProps { } - -const TestFC: React.FunctionComponent = ({ router }) => { - return
    {router && router.query && router.query.test}
    ; -}; diff --git a/types/next/tsconfig.json b/types/next/tsconfig.json index 9981affbd3..41f6efc969 100644 --- a/types/next/tsconfig.json +++ b/types/next/tsconfig.json @@ -30,14 +30,9 @@ "router.d.ts", "config.d.ts", "test/next-tests.ts", - "test/next-constants-tests.ts", "test/next-app-tests.tsx", "test/next-error-tests.tsx", - "test/next-head-tests.tsx", "test/next-document-tests.tsx", - "test/next-link-tests.tsx", - "test/next-dynamic-tests.tsx", - "test/next-router-tests.tsx", "test/next-component-tests.tsx" ] } diff --git a/types/node-cache/index.d.ts b/types/node-cache/index.d.ts index 6bac061ecb..61100a574d 100644 --- a/types/node-cache/index.d.ts +++ b/types/node-cache/index.d.ts @@ -283,3 +283,4 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac } export = NodeCache; +export as namespace NodeCache; diff --git a/types/node-gettext/index.d.ts b/types/node-gettext/index.d.ts index 3d17f9be16..f0ecee8b41 100644 --- a/types/node-gettext/index.d.ts +++ b/types/node-gettext/index.d.ts @@ -16,8 +16,8 @@ declare class GetText { gettext(msgid: string): string; ngettext(msgid: string, msgidPlural: string, count: number): string; npgettext(msgctxt: string, msgid: string, msgidPlural: string, count: number): string; - off(eventName: string, callback: (params: any) => void): string; - on(eventName: string, callback: (params: any) => void): void; + off(eventName: 'error', callback: (error: string) => void): void; + on(eventName: 'error', callback: (error: string) => void): void; pgettext(msgctxt: string, msgid: string): string; setLocale(locale: string): void; setTextDomain(domain: string): void; diff --git a/types/node-xlsx/index.d.ts b/types/node-xlsx/index.d.ts index bd500d8a4e..4b9432da76 100644 --- a/types/node-xlsx/index.d.ts +++ b/types/node-xlsx/index.d.ts @@ -10,7 +10,7 @@ * @param options options is for xlsx * @returns worksheets data, like: { name: 'worksheets', data: [[1,2,3],['1', '2','word']] } */ -export declare function parse( +export function parse( mixed: string | ArrayBuffer, options?: {} ): Array<{ @@ -24,7 +24,7 @@ export declare function parse( * @param options spannig multiple rows A1:A4 * @returns returns a buffer of worksheets */ -export declare function build( +export function build( worksheets: Array<{ name: string; data: any[][] }>, options?: {} ): ArrayBuffer; diff --git a/types/node/ts3.1/index.d.ts b/types/node/ts3.1/index.d.ts index be36602300..ee9f75cc5f 100644 --- a/types/node/ts3.1/index.d.ts +++ b/types/node/ts3.1/index.d.ts @@ -7,7 +7,7 @@ // Reference required types from the default lib: /// -/// +/// /// // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: diff --git a/types/node/v10/ts3.1/index.d.ts b/types/node/v10/ts3.1/index.d.ts index be36602300..ee9f75cc5f 100644 --- a/types/node/v10/ts3.1/index.d.ts +++ b/types/node/v10/ts3.1/index.d.ts @@ -7,7 +7,7 @@ // Reference required types from the default lib: /// -/// +/// /// // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: diff --git a/types/normalize-url/index.d.ts b/types/normalize-url/index.d.ts index fd76c4f72a..166477caee 100644 --- a/types/normalize-url/index.d.ts +++ b/types/normalize-url/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for normalize-url 3.3 +// Type definitions for normalize-url 4.1 // Project: https://github.com/sindresorhus/normalize-url // Definitions by: odin3 // BendingBender @@ -7,21 +7,154 @@ declare namespace normalizeUrl { interface Options { + /** + * @default 'http:' + */ defaultProtocol?: string; - forceHttp?: boolean; - forceHttps?: boolean; + /** + * Prepends `defaultProtocol` to the URL if it's protocol-relative. + * + * @default true + * @example + * normalizeUrl('//sindresorhus.com:80/'); + * //=> 'http://sindresorhus.com' + * + * normalizeUrl('//sindresorhus.com:80/', {normalizeProtocol: false}); + * //=> '//sindresorhus.com' + */ normalizeProtocol?: boolean; - normalizeHttps?: boolean; - sortQueryParameters?: boolean; - stripFragment?: boolean; + /** + * Normalizes `https:` URLs to `http:`. + * + * @default false + * @example + * normalizeUrl('https://sindresorhus.com:80/'); + * //=> 'https://sindresorhus.com' + * + * normalizeUrl('https://sindresorhus.com:80/', {forceHttp: true}); + * //=> 'http://sindresorhus.com' + */ + forceHttp?: boolean; + /** + * Normalizes `http:` URLs to `https:`. + * + * This option can't be used with the `forceHttp` option at the same time. + * + * @default false + * @example + * normalizeUrl('https://sindresorhus.com:80/'); + * //=> 'https://sindresorhus.com' + * + * normalizeUrl('http://sindresorhus.com:80/', {forceHttps: true}); + * //=> 'https://sindresorhus.com' + */ + forceHttps?: boolean; + /** + * Strip the [authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) part of a URL. + * + * @default true + * @example + * normalizeUrl('user:password@sindresorhus.com'); + * //=> 'https://sindresorhus.com' + * + * normalizeUrl('user:password@sindresorhus.com', {stripAuthentication: false}); + * //=> 'https://user:password@sindresorhus.com' + */ + stripAuthentication?: boolean; + /** + * Removes hash from the URL. + * + * @default false + * @example + * normalizeUrl('sindresorhus.com/about.html#contact'); + * //=> 'http://sindresorhus.com/about.html#contact' + * + * normalizeUrl('sindresorhus.com/about.html#contact', {stripHash: true}); + * //=> 'http://sindresorhus.com/about.html' + */ stripHash?: boolean; + /** + * Removes HTTP(S) protocol from an URL `http://sindresorhus.com` → `sindresorhus.com`. + * + * @default false + * @example + * normalizeUrl('https://sindresorhus.com'); + * //=> 'https://sindresorhus.com' + * + * normalizeUrl('sindresorhus.com', {stripProtocol: true}); + * //=> 'sindresorhus.com' + */ + stripProtocol?: boolean; + /** + * Removes `www.` from the URL. + * + * @default true + * @example + * normalizeUrl('http://www.sindresorhus.com'); + * //=> 'http://sindresorhus.com' + * + * normalizeUrl('http://www.sindresorhus.com', {stripWWW: false}); + * //=> 'http://www.sindresorhus.com' + */ stripWWW?: boolean; + /** + * Removes query parameters that matches any of the provided strings or regexes. + * + * @default [/^utm_\w+/i] + * @example + * normalizeUrl('www.sindresorhus.com?foo=bar&ref=test_ref', { + * removeQueryParameters: ['ref'] + * }); + * //=> 'http://sindresorhus.com/?foo=bar' + */ removeQueryParameters?: Array; + /** + * Removes trailing slash. + * + * **Note**: Trailing slash is always removed if the URL doesn't have a pathname. + * + * @default true + * @example + * normalizeUrl('http://sindresorhus.com/redirect/'); + * //=> 'http://sindresorhus.com/redirect' + * + * normalizeUrl('http://sindresorhus.com/redirect/', {removeTrailingSlash: false}); + * //=> 'http://sindresorhus.com/redirect/' + * + * normalizeUrl('http://sindresorhus.com/', {removeTrailingSlash: false}); + * //=> 'http://sindresorhus.com' + */ removeTrailingSlash?: boolean; + /** + * Removes the default directory index file from path that matches any of the provided strings or regexes. + * When `true`, the regex `/^index\.[a-z]+$/` is used. + * + * @default false + * @example + * normalizeUrl('www.sindresorhus.com/foo/default.php', { + * removeDirectoryIndex: [/^default\.[a-z]+$/] + * }); + * //=> 'http://sindresorhus.com/foo' + */ removeDirectoryIndex?: Array; + /** + * Sorts the query parameters alphabetically by key. + * + * @default true + * @example + * normalizeUrl('www.sindresorhus.com?b=two&a=one&c=three', { + * sortQueryParameters: false + * }); + * //=> 'http://sindresorhus.com/?b=two&a=one&c=three' + */ + sortQueryParameters?: boolean; } } +/** + * [Normalize](https://en.wikipedia.org/wiki/URL_normalization) a URL. + * @param url URL to normalize. + */ declare function normalizeUrl(url: string, options?: normalizeUrl.Options): string; export = normalizeUrl; diff --git a/types/normalize-url/normalize-url-tests.ts b/types/normalize-url/normalize-url-tests.ts index 961be30c0d..cdd87e42df 100644 --- a/types/normalize-url/normalize-url-tests.ts +++ b/types/normalize-url/normalize-url-tests.ts @@ -1,17 +1,23 @@ import normalizeUrl = require('normalize-url'); -let str: string; -str = normalizeUrl('sindresorhus.com'); -str = normalizeUrl('HTTP://xn--xample-hva.com:80/?b=bar&a=foo'); +normalizeUrl('sindresorhus.com'); // $ExpectType string +normalizeUrl('HTTP://xn--xample-hva.com:80/?b=bar&a=foo'); // $ExpectType string -normalizeUrl('//sindresorhus.com:80/', {normalizeProtocol: false}); -normalizeUrl('https://sindresorhus.com:80/', {normalizeHttps: true}); -normalizeUrl('sindresorhus.com/about.html#contact', {stripFragment: false}); -normalizeUrl('http://www.sindresorhus.com/about.html#contact', {stripWWW: false}); +normalizeUrl('//sindresorhus.com:80/', { defaultProtocol: 'https:' }); +normalizeUrl('//sindresorhus.com:80/', { normalizeProtocol: false }); +normalizeUrl('https://sindresorhus.com:80/', { forceHttp: true }); +normalizeUrl('http://sindresorhus.com:80/', { forceHttps: true }); +normalizeUrl('user:password@sindresorhus.com', { stripAuthentication: false }); +normalizeUrl('sindresorhus.com/about.html#contact', { stripHash: true }); +normalizeUrl('https://sindresorhus.com', { stripProtocol: true }); +normalizeUrl('http://www.sindresorhus.com', { stripWWW: false }); normalizeUrl('www.sindresorhus.com?foo=bar&ref=test_ref', { - removeQueryParameters: ['ref', /test/] + removeQueryParameters: ['ref', /test/], }); -normalizeUrl('http://sindresorhus.com/', {removeTrailingSlash: false}); +normalizeUrl('http://sindresorhus.com/', { removeTrailingSlash: false }); normalizeUrl('www.sindresorhus.com/foo/default.php', { - removeDirectoryIndex: [/^default\.[a-z]+$/, 'foo'] + removeDirectoryIndex: [/^default\.[a-z]+$/, 'foo'], +}); +normalizeUrl('www.sindresorhus.com?b=two&a=one&c=three', { + sortQueryParameters: false, }); diff --git a/types/normalize-url/tsconfig.json b/types/normalize-url/tsconfig.json index 1626fe81b7..0f18de6c48 100644 --- a/types/normalize-url/tsconfig.json +++ b/types/normalize-url/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "normalize-url-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/normalize-url/tslint.json b/types/normalize-url/tslint.json index 279473e356..f93cf8562a 100644 --- a/types/normalize-url/tslint.json +++ b/types/normalize-url/tslint.json @@ -1,7 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - // This package uses the Function type, and it will take effort to fix. - "ban-types": false - } + "extends": "dtslint/dt.json" } diff --git a/types/normalize-url/v3/index.d.ts b/types/normalize-url/v3/index.d.ts new file mode 100644 index 0000000000..fd76c4f72a --- /dev/null +++ b/types/normalize-url/v3/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for normalize-url 3.3 +// Project: https://github.com/sindresorhus/normalize-url +// Definitions by: odin3 +// BendingBender +// Mathieu M-Gosselin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace normalizeUrl { + interface Options { + defaultProtocol?: string; + forceHttp?: boolean; + forceHttps?: boolean; + normalizeProtocol?: boolean; + normalizeHttps?: boolean; + sortQueryParameters?: boolean; + stripFragment?: boolean; + stripHash?: boolean; + stripWWW?: boolean; + removeQueryParameters?: Array; + removeTrailingSlash?: boolean; + removeDirectoryIndex?: Array; + } +} + +declare function normalizeUrl(url: string, options?: normalizeUrl.Options): string; + +export = normalizeUrl; diff --git a/types/normalize-url/v3/normalize-url-tests.ts b/types/normalize-url/v3/normalize-url-tests.ts new file mode 100644 index 0000000000..961be30c0d --- /dev/null +++ b/types/normalize-url/v3/normalize-url-tests.ts @@ -0,0 +1,17 @@ +import normalizeUrl = require('normalize-url'); + +let str: string; +str = normalizeUrl('sindresorhus.com'); +str = normalizeUrl('HTTP://xn--xample-hva.com:80/?b=bar&a=foo'); + +normalizeUrl('//sindresorhus.com:80/', {normalizeProtocol: false}); +normalizeUrl('https://sindresorhus.com:80/', {normalizeHttps: true}); +normalizeUrl('sindresorhus.com/about.html#contact', {stripFragment: false}); +normalizeUrl('http://www.sindresorhus.com/about.html#contact', {stripWWW: false}); +normalizeUrl('www.sindresorhus.com?foo=bar&ref=test_ref', { + removeQueryParameters: ['ref', /test/] +}); +normalizeUrl('http://sindresorhus.com/', {removeTrailingSlash: false}); +normalizeUrl('www.sindresorhus.com/foo/default.php', { + removeDirectoryIndex: [/^default\.[a-z]+$/, 'foo'] +}); diff --git a/types/wait-for-localhost/tsconfig.json b/types/normalize-url/v3/tsconfig.json similarity index 62% rename from types/wait-for-localhost/tsconfig.json rename to types/normalize-url/v3/tsconfig.json index fb190a232f..dda934378d 100644 --- a/types/wait-for-localhost/tsconfig.json +++ b/types/normalize-url/v3/tsconfig.json @@ -6,18 +6,23 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": true, + "strictNullChecks": false, "strictFunctionTypes": true, - "baseUrl": "../", + "baseUrl": "../../", "typeRoots": [ - "../" + "../../" ], + "paths": { + "normalize-url": [ + "normalize-url/v3" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", - "wait-for-localhost-tests.ts" + "normalize-url-tests.ts" ] } diff --git a/types/normalize-url/v3/tslint.json b/types/normalize-url/v3/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/normalize-url/v3/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 42544390d9..80195cf516 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -2051,6 +2051,12 @@ declare namespace Office { * [Api set: Mailbox 1.5] */ ItemChanged, + /** + * Triggers when the appointment location is changed in Outlook. + * + * [Api set: Mailbox Preview] + */ + EnhancedLocationsChanged, /** * Triggers when a customXmlPart node is deleted. */ @@ -12092,7 +12098,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -12116,7 +12123,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -12440,7 +12448,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -12462,7 +12471,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -12566,7 +12576,7 @@ declare namespace Office { * * @param data - The data to be inserted. Data is not to exceed 1,000,000 characters. * If more than 1,000,000 characters are passed in, an ArgumentOutOfRange exception is thrown. - * @param options - An object literal that contains one or more of the following properties. + * @param options - Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. * coercionType: If text, the current style is applied in Outlook Web App and Outlook. * If the field is an HTML editor, only the text data is inserted, even if the data is HTML. @@ -12575,10 +12585,10 @@ declare namespace Office { * If the field is a text field, an InvalidDataFormat error is returned. * If coercionType is not set, the result depends on the field: if the field is HTML then HTML is used; * if the field is text, then plain text is used. - * @param callback - When the method completes, the function passed in the callback parameter is called with a single parameter of + * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - setSelectedDataAsync(data: string, options: Office.AsyncContextOptions & CoercionTypeOptions, callback: (asyncResult: Office.AsyncResult) => void): void; + setSelectedDataAsync(data: string, options?: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Asynchronously inserts data into the body or subject of a message. * @@ -12598,10 +12608,10 @@ declare namespace Office { * * @param data - The data to be inserted. Data is not to exceed 1,000,000 characters. * If more than 1,000,000 characters are passed in, an ArgumentOutOfRange exception is thrown. - * @param callback - When the method completes, the function passed in the callback parameter is called with a single parameter of + * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - setSelectedDataAsync(data: string, callback: (asyncResult: Office.AsyncResult) => void): void; + setSelectedDataAsync(data: string, callback?: (asyncResult: Office.AsyncResult) => void): void; } /** @@ -12953,7 +12963,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -12977,7 +12988,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -13341,7 +13353,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -13363,7 +13376,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -13466,7 +13480,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -13491,7 +13506,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -13692,7 +13708,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -13715,7 +13732,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -14251,7 +14269,7 @@ declare namespace Office { * * @param data - The data to be inserted. Data is not to exceed 1,000,000 characters. * If more than 1,000,000 characters are passed in, an ArgumentOutOfRange exception is thrown. - * @param options - An object literal that contains one or more of the following properties. + * @param options - Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. * coercionType: If text, the current style is applied in Outlook Web App and Outlook. * If the field is an HTML editor, only the text data is inserted, even if the data is HTML. @@ -14260,10 +14278,10 @@ declare namespace Office { * If the field is a text field, an InvalidDataFormat error is returned. * If coercionType is not set, the result depends on the field: if the field is HTML then HTML is used; * if the field is text, then plain text is used. - * @param callback - When the method completes, the function passed in the callback parameter is called with a single parameter of + * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - setSelectedDataAsync(data: string, options: Office.AsyncContextOptions & CoercionTypeOptions, callback: (asyncResult: Office.AsyncResult) => void): void; + setSelectedDataAsync(data: string, options?: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Asynchronously inserts data into the body or subject of a message. * @@ -14283,10 +14301,10 @@ declare namespace Office { * * @param data - The data to be inserted. Data is not to exceed 1,000,000 characters. * If more than 1,000,000 characters are passed in, an ArgumentOutOfRange exception is thrown. - * @param callback - When the method completes, the function passed in the callback parameter is called with a single parameter of + * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - setSelectedDataAsync(data: string, callback: (asyncResult: Office.AsyncResult) => void): void; + setSelectedDataAsync(data: string, callback?: (asyncResult: Office.AsyncResult) => void): void; } /** * The read mode of {@link Office.Item | Office.context.mailbox.item}. @@ -15062,7 +15080,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -15086,7 +15105,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -15419,7 +15439,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -15441,7 +15462,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -15548,7 +15570,7 @@ declare namespace Office { * * @param data - The data to be inserted. Data is not to exceed 1,000,000 characters. * If more than 1,000,000 characters are passed in, an ArgumentOutOfRange exception is thrown. - * @param options - An object literal that contains one or more of the following properties. + * @param options - Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. * coercionType: If text, the current style is applied in Outlook Web App and Outlook. * If the field is an HTML editor, only the text data is inserted, even if the data is HTML. @@ -15556,10 +15578,10 @@ declare namespace Office { * applied in Outlook. If the field is a text field, an InvalidDataFormat error is returned. * If coercionType is not set, the result depends on the field: if the field is HTML then HTML is used; * if the field is text, then plain text is used. - * @param callback - When the method completes, the function passed in the callback parameter is called with a single parameter of + * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - setSelectedDataAsync(data: string, options: Office.AsyncContextOptions & CoercionTypeOptions, callback: (asyncResult: Office.AsyncResult) => void): void; + setSelectedDataAsync(data: string, options?: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Asynchronously inserts data into the body or subject of a message. * @@ -15579,10 +15601,10 @@ declare namespace Office { * * @param data - The data to be inserted. Data is not to exceed 1,000,000 characters. * If more than 1,000,000 characters are passed in, an ArgumentOutOfRange exception is thrown. - * @param callback - When the method completes, the function passed in the callback parameter is called with a single parameter of + * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - setSelectedDataAsync(data: string, callback: (asyncResult: Office.AsyncResult) => void): void; + setSelectedDataAsync(data: string, callback?: (asyncResult: Office.AsyncResult) => void): void; } /** * The message read mode of {@link Office.Item | Office.context.mailbox.item}. @@ -15948,7 +15970,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -15972,7 +15995,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -16340,7 +16364,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -16362,7 +16387,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -16625,7 +16651,8 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently, the only supported event type is `Office.EventType.ItemChanged`. In Preview, `Office.EventType.OfficeThemeChanged` is also supported. + * Currently, the only supported event type is `Office.EventType.ItemChanged`. + * In Preview, `Office.EventType.OfficeThemeChanged` is also supported. * * [Api set: Mailbox 1.5] * @@ -16647,7 +16674,8 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently, the only supported event type is `Office.EventType.ItemChanged`. In Preview, `Office.EventType.OfficeThemeChanged` is also supported. + * Currently, the only supported event type is `Office.EventType.ItemChanged`. + * In Preview, `Office.EventType.OfficeThemeChanged` is also supported. * * [Api set: Mailbox 1.5] * @@ -17038,7 +17066,8 @@ declare namespace Office { /** * Removes the event handlers for a supported event type. * - * Currently, the only supported event type is `Office.EventType.ItemChanged`. In Preview, `Office.EventType.OfficeThemeChanged` is also supported. + * Currently, the only supported event type is `Office.EventType.ItemChanged`. + * In Preview, `Office.EventType.OfficeThemeChanged` is also supported. * * [Api set: Mailbox 1.5] * @@ -17058,7 +17087,8 @@ declare namespace Office { /** * Removes the event handlers for a supported event type. * - * Currently, the only supported event type is `Office.EventType.ItemChanged`. In Preview, `Office.EventType.OfficeThemeChanged` is also supported. + * Currently, the only supported event type is `Office.EventType.ItemChanged`. + * In Preview, `Office.EventType.OfficeThemeChanged` is also supported. * * [Api set: Mailbox 1.5] * @@ -19307,6 +19337,47 @@ declare namespace Excel { */ type: "WorkbookAutoSaveSettingChanged"; } + /** + * + * Provide information about the detail of WorksheetChangedEvent/TableChangedEvent + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + interface ChangedEventDetail { + /** + * + * Represents the value after changed. The data returned could be of type string, number, or a boolean. Cells that contain an error will return the error string. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + valueAfter: any; + /** + * + * Represents the value before changed. The data returned could be of type string, number, or a boolean. Cells that contain an error will return the error string. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + valueBefore: any; + /** + * + * Represents the type of value after changed + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + valueTypeAfter: Excel.RangeValueType | "Unknown" | "Empty" | "String" | "Integer" | "Double" | "Boolean" | "Error" | "RichValue"; + /** + * + * Represents the type of value before changed + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + valueTypeBefore: Excel.RangeValueType | "Unknown" | "Empty" | "String" | "Integer" | "Double" | "Boolean" | "Error" | "RichValue"; + } /** * * Provides information about the worksheet that raised the Changed event. @@ -19328,6 +19399,13 @@ declare namespace Excel { * [Api set: ExcelApi 1.7] */ changeType: Excel.DataChangeType | "Unknown" | "RangeEdited" | "RowInserted" | "RowDeleted" | "ColumnInserted" | "ColumnDeleted" | "CellInserted" | "CellDeleted"; + /** + * + * Represents the information about the change detail + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + */ + details: Excel.ChangedEventDetail; /** * * Gets the source of the event. See Excel.EventSource for details. @@ -19468,6 +19546,13 @@ declare namespace Excel { * [Api set: ExcelApi 1.7] */ worksheetId: string; + /** + * + * Represents the information about the change detail + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + */ + details: Excel.ChangedEventDetail; /** * * Gets the range that represents the changed area of a table on a specific worksheet. @@ -21878,7 +21963,28 @@ declare namespace Excel { set(properties: Interfaces.RangeUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Excel.Range): void; + /** + * + * Fills range from the current range to the destination range. + The destination range must extend the source either horizontally or vertically. Discontiguous ranges are not supported. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + * + * @param destinationRange The destination range to autofill. + * @param autoFillType The type of autofill. Specifies how the destination range is to be filled, based on the contents of the current range. Default is "FillDefault". + */ autoFill(destinationRange: Range | string, autoFillType?: Excel.AutoFillType): void; + /** + * + * Fills range from the current range to the destination range. + The destination range must extend the source either horizontally or vertically. Discontiguous ranges are not supported. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * + * @param destinationRange The destination range to autofill. + * @param autoFillType The type of autofill. Specifies how the destination range is to be filled, based on the contents of the current range. Default is "FillDefault". + */ autoFill(destinationRange: Range | string, autoFillType?: "FillDefault" | "FillCopy" | "FillSeries" | "FillFormats" | "FillValues" | "FillDays" | "FillWeekdays" | "FillMonths" | "FillYears" | "LinearTrend" | "GrowthTrend" | "FlashFill"): void; /** * @@ -21996,6 +22102,14 @@ declare namespace Excel { * @returns The Range which matched the search criteria. */ findOrNullObject(text: string, criteria: Excel.SearchCriteria): Excel.Range; + /** + * + * Does FlashFill to current range. Flash Fill will automatically fills data when it senses a pattern, so the range must be single column range and have data around in order to find pattern. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + flashFill(): void; /** * * Gets a Range object with the same top-left cell as the current Range object, but with the specified numbers of rows and columns. @@ -22205,7 +22319,7 @@ declare namespace Excel { * @param cellType The type of cells to include. * @param cellValueType If cellType is either Constants or Formulas, this argument is used to determine which types of cells to include in the result. These values can be combined together to return more than one type. The default is to select all constants or formulas, no matter what the type. */ - getSpecialCells(cellType: "ConditionalFormats" | "DataValidations" | "Blanks" | "Comments" | "Constants" | "Formulas" | "SameConditionalFormat" | "SameDataValidation" | "Visible", cellValueType?: "All" | "Errors" | "ErrorsLogical" | "ErrorsNumbers" | "ErrorsText" | "ErrorsLogicalNumber" | "ErrorsLogicalText" | "ErrorsNumberText" | "Logical" | "LogicalNumbers" | "LogicalText" | "LogicalNumbersText" | "Numbers" | "NumbersText" | "Text"): Excel.RangeAreas; + getSpecialCells(cellType: "ConditionalFormats" | "DataValidations" | "Blanks" | "Constants" | "Formulas" | "SameConditionalFormat" | "SameDataValidation" | "Visible", cellValueType?: "All" | "Errors" | "ErrorsLogical" | "ErrorsNumbers" | "ErrorsText" | "ErrorsLogicalNumber" | "ErrorsLogicalText" | "ErrorsNumberText" | "Logical" | "LogicalNumbers" | "LogicalText" | "LogicalNumbersText" | "Numbers" | "NumbersText" | "Text"): Excel.RangeAreas; /** * * Gets the RangeAreas object, comprising one or more ranges, that represents all the cells that match the specified type and value. @@ -22228,7 +22342,7 @@ declare namespace Excel { * @param cellType The type of cells to include. * @param cellValueType If cellType is either Constants or Formulas, this argument is used to determine which types of cells to include in the result. These values can be combined together to return more than one type. The default is to select all constants or formulas, no matter what the type. */ - getSpecialCellsOrNullObject(cellType: "ConditionalFormats" | "DataValidations" | "Blanks" | "Comments" | "Constants" | "Formulas" | "SameConditionalFormat" | "SameDataValidation" | "Visible", cellValueType?: "All" | "Errors" | "ErrorsLogical" | "ErrorsNumbers" | "ErrorsText" | "ErrorsLogicalNumber" | "ErrorsLogicalText" | "ErrorsNumberText" | "Logical" | "LogicalNumbers" | "LogicalText" | "LogicalNumbersText" | "Numbers" | "NumbersText" | "Text"): Excel.RangeAreas; + getSpecialCellsOrNullObject(cellType: "ConditionalFormats" | "DataValidations" | "Blanks" | "Constants" | "Formulas" | "SameConditionalFormat" | "SameDataValidation" | "Visible", cellValueType?: "All" | "Errors" | "ErrorsLogical" | "ErrorsNumbers" | "ErrorsText" | "ErrorsLogicalNumber" | "ErrorsLogicalText" | "ErrorsNumberText" | "Logical" | "LogicalNumbers" | "LogicalText" | "LogicalNumbersText" | "Numbers" | "NumbersText" | "Text"): Excel.RangeAreas; /** * * Gets the range object containing the anchor cell for a cell getting spilled into. Fails if applied to a range with more than one cell. Read only. @@ -22743,7 +22857,7 @@ declare namespace Excel { * @param cellType The type of cells to include. * @param cellValueType If cellType is either Constants or Formulas, this argument is used to determine which types of cells to include in the result. These values can be combined together to return more than one type. The default is to select all constants or formulas, no matter what the type. */ - getSpecialCells(cellType: "ConditionalFormats" | "DataValidations" | "Blanks" | "Comments" | "Constants" | "Formulas" | "SameConditionalFormat" | "SameDataValidation" | "Visible", cellValueType?: "All" | "Errors" | "ErrorsLogical" | "ErrorsNumbers" | "ErrorsText" | "ErrorsLogicalNumber" | "ErrorsLogicalText" | "ErrorsNumberText" | "Logical" | "LogicalNumbers" | "LogicalText" | "LogicalNumbersText" | "Numbers" | "NumbersText" | "Text"): Excel.RangeAreas; + getSpecialCells(cellType: "ConditionalFormats" | "DataValidations" | "Blanks" | "Constants" | "Formulas" | "SameConditionalFormat" | "SameDataValidation" | "Visible", cellValueType?: "All" | "Errors" | "ErrorsLogical" | "ErrorsNumbers" | "ErrorsText" | "ErrorsLogicalNumber" | "ErrorsLogicalText" | "ErrorsNumberText" | "Logical" | "LogicalNumbers" | "LogicalText" | "LogicalNumbersText" | "Numbers" | "NumbersText" | "Text"): Excel.RangeAreas; /** * * Returns a RangeAreas object that represents all the cells that match the specified type and value. Returns a null object if no special cells are found that match the criteria. @@ -22765,7 +22879,7 @@ declare namespace Excel { * @param cellType The type of cells to include. * @param cellValueType If cellType is either Constants or Formulas, this argument is used to determine which types of cells to include in the result. These values can be combined together to return more than one type. The default is to select all constants or formulas, no matter what the type. */ - getSpecialCellsOrNullObject(cellType: "ConditionalFormats" | "DataValidations" | "Blanks" | "Comments" | "Constants" | "Formulas" | "SameConditionalFormat" | "SameDataValidation" | "Visible", cellValueType?: "All" | "Errors" | "ErrorsLogical" | "ErrorsNumbers" | "ErrorsText" | "ErrorsLogicalNumber" | "ErrorsLogicalText" | "ErrorsNumberText" | "Logical" | "LogicalNumbers" | "LogicalText" | "LogicalNumbersText" | "Numbers" | "NumbersText" | "Text"): Excel.RangeAreas; + getSpecialCellsOrNullObject(cellType: "ConditionalFormats" | "DataValidations" | "Blanks" | "Constants" | "Formulas" | "SameConditionalFormat" | "SameDataValidation" | "Visible", cellValueType?: "All" | "Errors" | "ErrorsLogical" | "ErrorsNumbers" | "ErrorsText" | "ErrorsLogicalNumber" | "ErrorsLogicalText" | "ErrorsNumberText" | "Logical" | "LogicalNumbers" | "LogicalText" | "LogicalNumbersText" | "Numbers" | "NumbersText" | "Text"): Excel.RangeAreas; /** * * Returns a scoped collection of tables that overlap with any range in this RangeAreas object. @@ -35177,7 +35291,7 @@ declare namespace Excel { * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta * - * @param index Index value of the object to be retrieved. Zero-indexed. + * @param index Index value of the style object to be retrieved. Zero-indexed. */ getItemAt(index: number): Excel.Style; /** @@ -36414,12 +36528,8 @@ declare namespace Excel { * @beta * * @param geometricShapeType Represents the geometric type of the shape. See Excel.GeometricShapeType for details. - * @param left The distance, in points, from the left side of the shape to the left side of the worksheet. - * @param top The distance, in points, from the top edge of the shape to the top of the worksheet. - * @param width The width, in points, of the shape. - * @param height The height, in points, of the shape. */ - addGeometricShape(geometricShapeType: Excel.GeometricShapeType, left: number, top: number, width: number, height: number): Excel.Shape; + addGeometricShape(geometricShapeType: Excel.GeometricShapeType): Excel.Shape; /** * * Adds a geometric shape to worksheet. Returns a Shape object that represents the new shape. @@ -36428,12 +36538,8 @@ declare namespace Excel { * @beta * * @param geometricShapeType Represents the geometric type of the shape. See Excel.GeometricShapeType for details. - * @param left The distance, in points, from the left side of the shape to the left side of the worksheet. - * @param top The distance, in points, from the top edge of the shape to the top of the worksheet. - * @param width The width, in points, of the shape. - * @param height The height, in points, of the shape. */ - addGeometricShape(geometricShapeType: "LineInverse" | "Triangle" | "RightTriangle" | "Rectangle" | "Diamond" | "Parallelogram" | "Trapezoid" | "NonIsoscelesTrapezoid" | "Pentagon" | "Hexagon" | "Heptagon" | "Octagon" | "Decagon" | "Dodecagon" | "Star4" | "Star5" | "Star6" | "Star7" | "Star8" | "Star10" | "Star12" | "Star16" | "Star24" | "Star32" | "RoundRectangle" | "Round1Rectangle" | "Round2SameRectangle" | "Round2DiagonalRectangle" | "SnipRoundRectangle" | "Snip1Rectangle" | "Snip2SameRectangle" | "Snip2DiagonalRectangle" | "Plaque" | "Ellipse" | "Teardrop" | "HomePlate" | "Chevron" | "PieWedge" | "Pie" | "BlockArc" | "Donut" | "NoSmoking" | "RightArrow" | "LeftArrow" | "UpArrow" | "DownArrow" | "StripedRightArrow" | "NotchedRightArrow" | "BentUpArrow" | "LeftRightArrow" | "UpDownArrow" | "LeftUpArrow" | "LeftRightUpArrow" | "QuadArrow" | "LeftArrowCallout" | "RightArrowCallout" | "UpArrowCallout" | "DownArrowCallout" | "LeftRightArrowCallout" | "UpDownArrowCallout" | "QuadArrowCallout" | "BentArrow" | "UturnArrow" | "CircularArrow" | "LeftCircularArrow" | "LeftRightCircularArrow" | "CurvedRightArrow" | "CurvedLeftArrow" | "CurvedUpArrow" | "CurvedDownArrow" | "SwooshArrow" | "Cube" | "Can" | "LightningBolt" | "Heart" | "Sun" | "Moon" | "SmileyFace" | "IrregularSeal1" | "IrregularSeal2" | "FoldedCorner" | "Bevel" | "Frame" | "HalfFrame" | "Corner" | "DiagonalStripe" | "Chord" | "Arc" | "LeftBracket" | "RightBracket" | "LeftBrace" | "RightBrace" | "BracketPair" | "BracePair" | "Callout1" | "Callout2" | "Callout3" | "AccentCallout1" | "AccentCallout2" | "AccentCallout3" | "BorderCallout1" | "BorderCallout2" | "BorderCallout3" | "AccentBorderCallout1" | "AccentBorderCallout2" | "AccentBorderCallout3" | "WedgeRectCallout" | "WedgeRRectCallout" | "WedgeEllipseCallout" | "CloudCallout" | "Cloud" | "Ribbon" | "Ribbon2" | "EllipseRibbon" | "EllipseRibbon2" | "LeftRightRibbon" | "VerticalScroll" | "HorizontalScroll" | "Wave" | "DoubleWave" | "Plus" | "FlowChartProcess" | "FlowChartDecision" | "FlowChartInputOutput" | "FlowChartPredefinedProcess" | "FlowChartInternalStorage" | "FlowChartDocument" | "FlowChartMultidocument" | "FlowChartTerminator" | "FlowChartPreparation" | "FlowChartManualInput" | "FlowChartManualOperation" | "FlowChartConnector" | "FlowChartPunchedCard" | "FlowChartPunchedTape" | "FlowChartSummingJunction" | "FlowChartOr" | "FlowChartCollate" | "FlowChartSort" | "FlowChartExtract" | "FlowChartMerge" | "FlowChartOfflineStorage" | "FlowChartOnlineStorage" | "FlowChartMagneticTape" | "FlowChartMagneticDisk" | "FlowChartMagneticDrum" | "FlowChartDisplay" | "FlowChartDelay" | "FlowChartAlternateProcess" | "FlowChartOffpageConnector" | "ActionButtonBlank" | "ActionButtonHome" | "ActionButtonHelp" | "ActionButtonInformation" | "ActionButtonForwardNext" | "ActionButtonBackPrevious" | "ActionButtonEnd" | "ActionButtonBeginning" | "ActionButtonReturn" | "ActionButtonDocument" | "ActionButtonSound" | "ActionButtonMovie" | "Gear6" | "Gear9" | "Funnel" | "MathPlus" | "MathMinus" | "MathMultiply" | "MathDivide" | "MathEqual" | "MathNotEqual" | "CornerTabs" | "SquareTabs" | "PlaqueTabs" | "ChartX" | "ChartStar" | "ChartPlus", left: number, top: number, width: number, height: number): Excel.Shape; + addGeometricShape(geometricShapeType: "LineInverse" | "Triangle" | "RightTriangle" | "Rectangle" | "Diamond" | "Parallelogram" | "Trapezoid" | "NonIsoscelesTrapezoid" | "Pentagon" | "Hexagon" | "Heptagon" | "Octagon" | "Decagon" | "Dodecagon" | "Star4" | "Star5" | "Star6" | "Star7" | "Star8" | "Star10" | "Star12" | "Star16" | "Star24" | "Star32" | "RoundRectangle" | "Round1Rectangle" | "Round2SameRectangle" | "Round2DiagonalRectangle" | "SnipRoundRectangle" | "Snip1Rectangle" | "Snip2SameRectangle" | "Snip2DiagonalRectangle" | "Plaque" | "Ellipse" | "Teardrop" | "HomePlate" | "Chevron" | "PieWedge" | "Pie" | "BlockArc" | "Donut" | "NoSmoking" | "RightArrow" | "LeftArrow" | "UpArrow" | "DownArrow" | "StripedRightArrow" | "NotchedRightArrow" | "BentUpArrow" | "LeftRightArrow" | "UpDownArrow" | "LeftUpArrow" | "LeftRightUpArrow" | "QuadArrow" | "LeftArrowCallout" | "RightArrowCallout" | "UpArrowCallout" | "DownArrowCallout" | "LeftRightArrowCallout" | "UpDownArrowCallout" | "QuadArrowCallout" | "BentArrow" | "UturnArrow" | "CircularArrow" | "LeftCircularArrow" | "LeftRightCircularArrow" | "CurvedRightArrow" | "CurvedLeftArrow" | "CurvedUpArrow" | "CurvedDownArrow" | "SwooshArrow" | "Cube" | "Can" | "LightningBolt" | "Heart" | "Sun" | "Moon" | "SmileyFace" | "IrregularSeal1" | "IrregularSeal2" | "FoldedCorner" | "Bevel" | "Frame" | "HalfFrame" | "Corner" | "DiagonalStripe" | "Chord" | "Arc" | "LeftBracket" | "RightBracket" | "LeftBrace" | "RightBrace" | "BracketPair" | "BracePair" | "Callout1" | "Callout2" | "Callout3" | "AccentCallout1" | "AccentCallout2" | "AccentCallout3" | "BorderCallout1" | "BorderCallout2" | "BorderCallout3" | "AccentBorderCallout1" | "AccentBorderCallout2" | "AccentBorderCallout3" | "WedgeRectCallout" | "WedgeRRectCallout" | "WedgeEllipseCallout" | "CloudCallout" | "Cloud" | "Ribbon" | "Ribbon2" | "EllipseRibbon" | "EllipseRibbon2" | "LeftRightRibbon" | "VerticalScroll" | "HorizontalScroll" | "Wave" | "DoubleWave" | "Plus" | "FlowChartProcess" | "FlowChartDecision" | "FlowChartInputOutput" | "FlowChartPredefinedProcess" | "FlowChartInternalStorage" | "FlowChartDocument" | "FlowChartMultidocument" | "FlowChartTerminator" | "FlowChartPreparation" | "FlowChartManualInput" | "FlowChartManualOperation" | "FlowChartConnector" | "FlowChartPunchedCard" | "FlowChartPunchedTape" | "FlowChartSummingJunction" | "FlowChartOr" | "FlowChartCollate" | "FlowChartSort" | "FlowChartExtract" | "FlowChartMerge" | "FlowChartOfflineStorage" | "FlowChartOnlineStorage" | "FlowChartMagneticTape" | "FlowChartMagneticDisk" | "FlowChartMagneticDrum" | "FlowChartDisplay" | "FlowChartDelay" | "FlowChartAlternateProcess" | "FlowChartOffpageConnector" | "ActionButtonBlank" | "ActionButtonHome" | "ActionButtonHelp" | "ActionButtonInformation" | "ActionButtonForwardNext" | "ActionButtonBackPrevious" | "ActionButtonEnd" | "ActionButtonBeginning" | "ActionButtonReturn" | "ActionButtonDocument" | "ActionButtonSound" | "ActionButtonMovie" | "Gear6" | "Gear9" | "Funnel" | "MathPlus" | "MathMinus" | "MathMultiply" | "MathDivide" | "MathEqual" | "MathNotEqual" | "CornerTabs" | "SquareTabs" | "PlaqueTabs" | "ChartX" | "ChartStar" | "ChartPlus"): Excel.Shape; /** * * Group a subset of shapes in a worksheet. Returns a Shape object that represents the new group of shapes. @@ -36644,6 +36750,14 @@ declare namespace Excel { * @beta */ altTextTitle: string; + /** + * + * Returns the number of connection sites on the specified shape. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + readonly connectionSiteCount: number; /** * * Represents the geometric shape type of the specified shape. See Excel.GeometricShapeType for detail. Returns null if the shape is not geometric, for example, get GeometricShapeType of a line or a chart will return null. @@ -37201,6 +37315,22 @@ declare namespace Excel { class Line extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; + /** + * + * Represents the shape object that the beginning of the specified line is attached to. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + readonly beginConnectedShape: Excel.Shape; + /** + * + * Represents the shape object that the end of the specified line is attached to. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + readonly endConnectedShape: Excel.Shape; /** * * Returns the shape object for the line. Read-only. @@ -37209,6 +37339,70 @@ declare namespace Excel { * @beta */ readonly shape: Excel.Shape; + /** + * + * Represents the length of the arrowhead at the beginning of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginArrowHeadLength: Excel.ArrowHeadLength | "Short" | "Medium" | "Long"; + /** + * + * Represents the style of the arrowhead at the beginning of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginArrowHeadStyle: Excel.ArrowHeadStyle | "None" | "Triangle" | "Stealth" | "Diamond" | "Oval" | "Open"; + /** + * + * Represents the width of the arrowhead at the beginning of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginArrowHeadWidth: Excel.ArrowHeadWidth | "Narrow" | "Medium" | "Wide"; + /** + * + * Represents an integer that specifies the connection site that the beginning of a connector is connected to. Read-only. Returns null when the beginning of the line is not attached to any shape. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + readonly beginConnectedSite: number; + /** + * + * Represents the length of the arrowhead at the end of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endArrowHeadLength: Excel.ArrowHeadLength | "Short" | "Medium" | "Long"; + /** + * + * Represents the style of the arrowhead at the end of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endArrowHeadStyle: Excel.ArrowHeadStyle | "None" | "Triangle" | "Stealth" | "Diamond" | "Oval" | "Open"; + /** + * + * Represents the width of the arrowhead at the end of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endArrowHeadWidth: Excel.ArrowHeadWidth | "Narrow" | "Medium" | "Wide"; + /** + * + * Represents an integer that specifies the connection site that the end of a connector is connected to. Read-only. Returns null when the end of the line is not attached to any shape. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + readonly endConnectedSite: number; /** * * Represents the shape identifier. Read-only. @@ -37217,6 +37411,22 @@ declare namespace Excel { * @beta */ readonly id: string; + /** + * + * Represents whether the beginning of the specified line is connected to a shape. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + readonly isBeginConnected: boolean; + /** + * + * Represents whether the end of the specified line is connected to a shape. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + readonly isEndConnected: boolean; /** * * Represents the connector type for the line. @@ -37239,6 +37449,44 @@ declare namespace Excel { set(properties: Interfaces.LineUpdateData, options?: OfficeExtension.UpdateOptions): void; /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ set(properties: Excel.Line): void; + /** + * + * Attaches the beginning of the specified connector to a specified shape. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + * + * @param shape The shape to attach the beginning of the connector to. + * @param connectionSite The connection site on the shape which the beginning of the connector attach to. Must be an integer between 0 and the connection site count(not included) of the specified shape. + */ + beginConnect(shape: Excel.Shape, connectionSite: number): void; + /** + * + * Detaches the beginning of the specified connector from the shape it's attached to. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginDisconnect(): void; + /** + * + * Attaches the end of the specified connector to a specified shape. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + * + * @param shape The shape to attach the end of the connector to. + * @param connectionSite The connection site on the shape which the end of the connector attach to. Must be an integer between 0 and the connection site count(not included) of the specified shape. + */ + endConnect(shape: Excel.Shape, connectionSite: number): void; + /** + * + * Detaches the end of the specified connector from the shape it's attached to. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endDisconnect(): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * @@ -37468,6 +37716,13 @@ declare namespace Excel { class TextFrame extends OfficeExtension.ClientObject { /** The request context associated with the object. This connects the add-in's process to the Office host application's process. */ context: RequestContext; + /** + * + * Represents the text range in the text frame. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ readonly textRange: Excel.TextRange; /** * @@ -37874,7 +38129,7 @@ declare namespace Excel { nameInFormula: string; /** * - * Represents the sort order of the items in the slicer. + * Represents the sort order of the items in the slicer. Possible values are: DataSourceOrder, Ascending, Descending. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta @@ -37890,7 +38145,7 @@ declare namespace Excel { style: string; /** * - * Represents the distance, in points, from the top edge of the slicer to the right of the worksheet. + * Represents the distance, in points, from the top edge of the slicer to the top of the worksheet. Throws an invalid argument exception when set with negative value as input. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] @@ -37938,7 +38193,7 @@ declare namespace Excel { delete(): void; /** * - * Returns an array of selected items' names. Read-only. + * Returns an array of selected items' keys. Read-only. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta @@ -37946,8 +38201,8 @@ declare namespace Excel { getSelectedItems(): OfficeExtension.ClientResult; /** * - * Select slicer items based on their names. Previous selection will be cleared. - All items will be deselected if the array is empty. + * Select slicer items based on their keys. Previous selection will be cleared. + All items will be selected by default if the array is empty. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta @@ -38089,7 +38344,9 @@ declare namespace Excel { readonly hasData: boolean; /** * - * True if the slicer item is selected. Setting this value will not clear other SlicerItems' selected state. + * True if the slicer item is selected. + Setting this value will not clear other SlicerItems' selected state. + By default, if the slicer item is the only one selected, when it is deselected, all items will be selected. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta @@ -38934,6 +39191,36 @@ declare namespace Excel { systemDot = "SystemDot", systemDashDot = "SystemDashDot" } + /** + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + enum ArrowHeadLength { + short = "Short", + medium = "Medium", + long = "Long" + } + /** + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + enum ArrowHeadStyle { + none = "None", + triangle = "Triangle", + stealth = "Stealth", + diamond = "Diamond", + oval = "Oval", + open = "Open" + } + /** + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + enum ArrowHeadWidth { + narrow = "Narrow", + medium = "Medium", + wide = "Wide" + } /** * [Api set: ExcelApi 1.1] */ @@ -39846,7 +40133,13 @@ declare namespace Excel { * */ worksheetFormatChanged = "WorksheetFormatChanged", - wacoperationEvent = "WACOperationEvent" + wacoperationEvent = "WACOperationEvent", + /** + * + * RibbonCommandExecuted represents the type of event registered on ribbon, and occurs when user click on ribbon + * + */ + ribbonCommandExecuted = "RibbonCommandExecuted" } /** * [Api set: ExcelApi 1.7] @@ -40456,12 +40749,6 @@ declare namespace Excel { * */ blanks = "Blanks", - /** - * - * Cells containing comments. - * - */ - comments = "Comments", /** * * Cells containing constants. @@ -40755,6 +41042,24 @@ declare namespace Excel { ascending = "Ascending", descending = "Descending" } + /** + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + enum RibbonTab { + others = "Others", + home = "Home", + insert = "Insert", + draw = "Draw", + pageLayout = "PageLayout", + formulas = "Formulas", + data = "Data", + review = "Review", + view = "View", + developer = "Developer", + addIns = "AddIns", + help = "Help" + } /** * * An object containing the result of a function-evaluation operation @@ -48918,6 +49223,54 @@ declare namespace Excel { } /** An interface for updating data on the Line object, for use in "line.set({ ... })". */ interface LineUpdateData { + /** + * + * Represents the length of the arrowhead at the beginning of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginArrowHeadLength?: Excel.ArrowHeadLength | "Short" | "Medium" | "Long"; + /** + * + * Represents the style of the arrowhead at the beginning of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginArrowHeadStyle?: Excel.ArrowHeadStyle | "None" | "Triangle" | "Stealth" | "Diamond" | "Oval" | "Open"; + /** + * + * Represents the width of the arrowhead at the beginning of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginArrowHeadWidth?: Excel.ArrowHeadWidth | "Narrow" | "Medium" | "Wide"; + /** + * + * Represents the length of the arrowhead at the end of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endArrowHeadLength?: Excel.ArrowHeadLength | "Short" | "Medium" | "Long"; + /** + * + * Represents the style of the arrowhead at the end of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endArrowHeadStyle?: Excel.ArrowHeadStyle | "None" | "Triangle" | "Stealth" | "Diamond" | "Oval" | "Open"; + /** + * + * Represents the width of the arrowhead at the end of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endArrowHeadWidth?: Excel.ArrowHeadWidth | "Narrow" | "Medium" | "Wide"; /** * * Represents the connector type for the line. @@ -49212,7 +49565,7 @@ declare namespace Excel { nameInFormula?: string; /** * - * Represents the sort order of the items in the slicer. + * Represents the sort order of the items in the slicer. Possible values are: DataSourceOrder, Ascending, Descending. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta @@ -49228,7 +49581,7 @@ declare namespace Excel { style?: string; /** * - * Represents the distance, in points, from the top edge of the slicer to the right of the worksheet. + * Represents the distance, in points, from the top edge of the slicer to the top of the worksheet. Throws an invalid argument exception when set with negative value as input. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] @@ -49253,7 +49606,9 @@ declare namespace Excel { interface SlicerItemUpdateData { /** * - * True if the slicer item is selected. Setting this value will not clear other SlicerItems' selected state. + * True if the slicer item is selected. + Setting this value will not clear other SlicerItems' selected state. + By default, if the slicer item is the only one selected, when it is deselected, all items will be selected. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta @@ -54636,6 +54991,14 @@ declare namespace Excel { * @beta */ altTextTitle?: string; + /** + * + * Returns the number of connection sites on the specified shape. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + connectionSiteCount?: number; /** * * Represents the geometric shape type of the specified shape. See Excel.GeometricShapeType for detail. Returns null if the shape is not geometric, for example, get GeometricShapeType of a line or a chart will return null. @@ -54808,6 +55171,70 @@ declare namespace Excel { } /** An interface describing the data returned by calling "line.toJSON()". */ interface LineData { + /** + * + * Represents the length of the arrowhead at the beginning of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginArrowHeadLength?: Excel.ArrowHeadLength | "Short" | "Medium" | "Long"; + /** + * + * Represents the style of the arrowhead at the beginning of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginArrowHeadStyle?: Excel.ArrowHeadStyle | "None" | "Triangle" | "Stealth" | "Diamond" | "Oval" | "Open"; + /** + * + * Represents the width of the arrowhead at the beginning of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginArrowHeadWidth?: Excel.ArrowHeadWidth | "Narrow" | "Medium" | "Wide"; + /** + * + * Represents an integer that specifies the connection site that the beginning of a connector is connected to. Read-only. Returns null when the beginning of the line is not attached to any shape. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginConnectedSite?: number; + /** + * + * Represents the length of the arrowhead at the end of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endArrowHeadLength?: Excel.ArrowHeadLength | "Short" | "Medium" | "Long"; + /** + * + * Represents the style of the arrowhead at the end of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endArrowHeadStyle?: Excel.ArrowHeadStyle | "None" | "Triangle" | "Stealth" | "Diamond" | "Oval" | "Open"; + /** + * + * Represents the width of the arrowhead at the end of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endArrowHeadWidth?: Excel.ArrowHeadWidth | "Narrow" | "Medium" | "Wide"; + /** + * + * Represents an integer that specifies the connection site that the end of a connector is connected to. Read-only. Returns null when the end of the line is not attached to any shape. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endConnectedSite?: number; /** * * Represents the shape identifier. Read-only. @@ -54816,6 +55243,22 @@ declare namespace Excel { * @beta */ id?: string; + /** + * + * Represents whether the beginning of the specified line is connected to a shape. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + isBeginConnected?: boolean; + /** + * + * Represents whether the end of the specified line is connected to a shape. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + isEndConnected?: boolean; /** * * Represents the connector type for the line. @@ -55150,7 +55593,7 @@ declare namespace Excel { nameInFormula?: string; /** * - * Represents the sort order of the items in the slicer. + * Represents the sort order of the items in the slicer. Possible values are: DataSourceOrder, Ascending, Descending. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta @@ -55166,7 +55609,7 @@ declare namespace Excel { style?: string; /** * - * Represents the distance, in points, from the top edge of the slicer to the right of the worksheet. + * Represents the distance, in points, from the top edge of the slicer to the top of the worksheet. Throws an invalid argument exception when set with negative value as input. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] @@ -55199,7 +55642,9 @@ declare namespace Excel { hasData?: boolean; /** * - * True if the slicer item is selected. Setting this value will not clear other SlicerItems' selected state. + * True if the slicer item is selected. + Setting this value will not clear other SlicerItems' selected state. + By default, if the slicer item is the only one selected, when it is deselected, all items will be selected. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta @@ -63416,6 +63861,14 @@ declare namespace Excel { * @beta */ altTextTitle?: boolean; + /** + * + * For EACH ITEM in the collection: Returns the number of connection sites on the specified shape. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + connectionSiteCount?: boolean; /** * * For EACH ITEM in the collection: Represents the geometric shape type of the specified shape. See Excel.GeometricShapeType for detail. Returns null if the shape is not geometric, for example, get GeometricShapeType of a line or a chart will return null. @@ -63622,6 +64075,14 @@ declare namespace Excel { * @beta */ altTextTitle?: boolean; + /** + * + * Returns the number of connection sites on the specified shape. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + connectionSiteCount?: boolean; /** * * Represents the geometric shape type of the specified shape. See Excel.GeometricShapeType for detail. Returns null if the shape is not geometric, for example, get GeometricShapeType of a line or a chart will return null. @@ -63914,6 +64375,14 @@ declare namespace Excel { * @beta */ altTextTitle?: boolean; + /** + * + * For EACH ITEM in the collection: Returns the number of connection sites on the specified shape. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + connectionSiteCount?: boolean; /** * * For EACH ITEM in the collection: Represents the geometric shape type of the specified shape. See Excel.GeometricShapeType for detail. Returns null if the shape is not geometric, for example, get GeometricShapeType of a line or a chart will return null. @@ -64042,12 +64511,92 @@ declare namespace Excel { $all?: boolean; /** * + * Represents the shape object that the beginning of the specified line is attached to. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginConnectedShape?: Excel.Interfaces.ShapeLoadOptions; + /** + * + * Represents the shape object that the end of the specified line is attached to. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endConnectedShape?: Excel.Interfaces.ShapeLoadOptions; + /** + * * Returns the shape object for the line. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta */ shape?: Excel.Interfaces.ShapeLoadOptions; + /** + * + * Represents the length of the arrowhead at the beginning of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginArrowHeadLength?: boolean; + /** + * + * Represents the style of the arrowhead at the beginning of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginArrowHeadStyle?: boolean; + /** + * + * Represents the width of the arrowhead at the beginning of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginArrowHeadWidth?: boolean; + /** + * + * Represents an integer that specifies the connection site that the beginning of a connector is connected to. Read-only. Returns null when the beginning of the line is not attached to any shape. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + beginConnectedSite?: boolean; + /** + * + * Represents the length of the arrowhead at the end of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endArrowHeadLength?: boolean; + /** + * + * Represents the style of the arrowhead at the end of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endArrowHeadStyle?: boolean; + /** + * + * Represents the width of the arrowhead at the end of the specified line. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endArrowHeadWidth?: boolean; + /** + * + * Represents an integer that specifies the connection site that the end of a connector is connected to. Read-only. Returns null when the end of the line is not attached to any shape. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + endConnectedSite?: boolean; /** * * Represents the shape identifier. Read-only. @@ -64056,6 +64605,22 @@ declare namespace Excel { * @beta */ id?: boolean; + /** + * + * Represents whether the beginning of the specified line is connected to a shape. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + isBeginConnected?: boolean; + /** + * + * Represents whether the end of the specified line is connected to a shape. Read-only. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ + isEndConnected?: boolean; /** * * Represents the connector type for the line. @@ -64166,6 +64731,13 @@ declare namespace Excel { */ interface TextFrameLoadOptions { $all?: boolean; + /** + * + * Represents the text range in the text frame. + * + * [Api set: ExcelApi BETA (PREVIEW ONLY)] + * @beta + */ textRange?: Excel.Interfaces.TextRangeLoadOptions; /** * @@ -64422,7 +64994,7 @@ declare namespace Excel { nameInFormula?: boolean; /** * - * Represents the sort order of the items in the slicer. + * Represents the sort order of the items in the slicer. Possible values are: DataSourceOrder, Ascending, Descending. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta @@ -64438,7 +65010,7 @@ declare namespace Excel { style?: boolean; /** * - * Represents the distance, in points, from the top edge of the slicer to the right of the worksheet. + * Represents the distance, in points, from the top edge of the slicer to the top of the worksheet. Throws an invalid argument exception when set with negative value as input. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] @@ -64532,7 +65104,7 @@ declare namespace Excel { nameInFormula?: boolean; /** * - * For EACH ITEM in the collection: Represents the sort order of the items in the slicer. + * For EACH ITEM in the collection: Represents the sort order of the items in the slicer. Possible values are: DataSourceOrder, Ascending, Descending. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta @@ -64548,7 +65120,7 @@ declare namespace Excel { style?: boolean; /** * - * For EACH ITEM in the collection: Represents the distance, in points, from the top edge of the slicer to the right of the worksheet. + * For EACH ITEM in the collection: Represents the distance, in points, from the top edge of the slicer to the top of the worksheet. Throws an invalid argument exception when set with negative value as input. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] @@ -64584,7 +65156,9 @@ declare namespace Excel { hasData?: boolean; /** * - * True if the slicer item is selected. Setting this value will not clear other SlicerItems' selected state. + * True if the slicer item is selected. + Setting this value will not clear other SlicerItems' selected state. + By default, if the slicer item is the only one selected, when it is deselected, all items will be selected. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta @@ -64626,7 +65200,9 @@ declare namespace Excel { hasData?: boolean; /** * - * For EACH ITEM in the collection: True if the slicer item is selected. Setting this value will not clear other SlicerItems' selected state. + * For EACH ITEM in the collection: True if the slicer item is selected. + Setting this value will not clear other SlicerItems' selected state. + By default, if the slicer item is the only one selected, when it is deselected, all items will be selected. * * [Api set: ExcelApi BETA (PREVIEW ONLY)] * @beta @@ -64675,6 +65251,7 @@ declare namespace Excel { } } + //////////////////////////////////////////////////////////////// //////////////////////// End Excel APIs //////////////////////// //////////////////////////////////////////////////////////////// diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index c207b00668..ef05ead31d 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -2051,6 +2051,12 @@ declare namespace Office { * [Api set: Mailbox 1.5] */ ItemChanged, + /** + * Triggers when the appointment location is changed in Outlook. + * + * [Api set: Mailbox Preview] + */ + EnhancedLocationsChanged, /** * Triggers when a customXmlPart node is deleted. */ @@ -12091,8 +12097,9 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -12116,7 +12123,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -12440,7 +12448,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -12462,7 +12471,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -12566,7 +12576,7 @@ declare namespace Office { * * @param data - The data to be inserted. Data is not to exceed 1,000,000 characters. * If more than 1,000,000 characters are passed in, an ArgumentOutOfRange exception is thrown. - * @param options - An object literal that contains one or more of the following properties. + * @param options - Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. * coercionType: If text, the current style is applied in Outlook Web App and Outlook. * If the field is an HTML editor, only the text data is inserted, even if the data is HTML. @@ -12575,10 +12585,10 @@ declare namespace Office { * If the field is a text field, an InvalidDataFormat error is returned. * If coercionType is not set, the result depends on the field: if the field is HTML then HTML is used; * if the field is text, then plain text is used. - * @param callback - When the method completes, the function passed in the callback parameter is called with a single parameter of + * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - setSelectedDataAsync(data: string, options: Office.AsyncContextOptions & CoercionTypeOptions, callback: (asyncResult: Office.AsyncResult) => void): void; + setSelectedDataAsync(data: string, options?: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Asynchronously inserts data into the body or subject of a message. * @@ -12598,10 +12608,10 @@ declare namespace Office { * * @param data - The data to be inserted. Data is not to exceed 1,000,000 characters. * If more than 1,000,000 characters are passed in, an ArgumentOutOfRange exception is thrown. - * @param callback - When the method completes, the function passed in the callback parameter is called with a single parameter of + * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - setSelectedDataAsync(data: string, callback: (asyncResult: Office.AsyncResult) => void): void; + setSelectedDataAsync(data: string, callback?: (asyncResult: Office.AsyncResult) => void): void; } /** @@ -12953,7 +12963,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -12977,7 +12988,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -13341,7 +13353,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -13363,7 +13376,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -13466,7 +13480,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -13491,7 +13506,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -13692,7 +13708,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -13715,7 +13732,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -14251,7 +14269,7 @@ declare namespace Office { * * @param data - The data to be inserted. Data is not to exceed 1,000,000 characters. * If more than 1,000,000 characters are passed in, an ArgumentOutOfRange exception is thrown. - * @param options - An object literal that contains one or more of the following properties. + * @param options - Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. * coercionType: If text, the current style is applied in Outlook Web App and Outlook. * If the field is an HTML editor, only the text data is inserted, even if the data is HTML. @@ -14260,10 +14278,10 @@ declare namespace Office { * If the field is a text field, an InvalidDataFormat error is returned. * If coercionType is not set, the result depends on the field: if the field is HTML then HTML is used; * if the field is text, then plain text is used. - * @param callback - When the method completes, the function passed in the callback parameter is called with a single parameter of + * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - setSelectedDataAsync(data: string, options: Office.AsyncContextOptions & CoercionTypeOptions, callback: (asyncResult: Office.AsyncResult) => void): void; + setSelectedDataAsync(data: string, options?: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Asynchronously inserts data into the body or subject of a message. * @@ -14283,10 +14301,10 @@ declare namespace Office { * * @param data - The data to be inserted. Data is not to exceed 1,000,000 characters. * If more than 1,000,000 characters are passed in, an ArgumentOutOfRange exception is thrown. - * @param callback - When the method completes, the function passed in the callback parameter is called with a single parameter of + * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - setSelectedDataAsync(data: string, callback: (asyncResult: Office.AsyncResult) => void): void; + setSelectedDataAsync(data: string, callback?: (asyncResult: Office.AsyncResult) => void): void; } /** * The read mode of {@link Office.Item | Office.context.mailbox.item}. @@ -15062,7 +15080,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -15086,7 +15105,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -15419,7 +15439,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -15441,7 +15462,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -15548,7 +15570,7 @@ declare namespace Office { * * @param data - The data to be inserted. Data is not to exceed 1,000,000 characters. * If more than 1,000,000 characters are passed in, an ArgumentOutOfRange exception is thrown. - * @param options - An object literal that contains one or more of the following properties. + * @param options - Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. * coercionType: If text, the current style is applied in Outlook Web App and Outlook. * If the field is an HTML editor, only the text data is inserted, even if the data is HTML. @@ -15556,10 +15578,10 @@ declare namespace Office { * applied in Outlook. If the field is a text field, an InvalidDataFormat error is returned. * If coercionType is not set, the result depends on the field: if the field is HTML then HTML is used; * if the field is text, then plain text is used. - * @param callback - When the method completes, the function passed in the callback parameter is called with a single parameter of + * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - setSelectedDataAsync(data: string, options: Office.AsyncContextOptions & CoercionTypeOptions, callback: (asyncResult: Office.AsyncResult) => void): void; + setSelectedDataAsync(data: string, options?: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Asynchronously inserts data into the body or subject of a message. * @@ -15579,10 +15601,10 @@ declare namespace Office { * * @param data - The data to be inserted. Data is not to exceed 1,000,000 characters. * If more than 1,000,000 characters are passed in, an ArgumentOutOfRange exception is thrown. - * @param callback - When the method completes, the function passed in the callback parameter is called with a single parameter of + * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - setSelectedDataAsync(data: string, callback: (asyncResult: Office.AsyncResult) => void): void; + setSelectedDataAsync(data: string, callback?: (asyncResult: Office.AsyncResult) => void): void; } /** * The message read mode of {@link Office.Item | Office.context.mailbox.item}. @@ -15948,7 +15970,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -15972,7 +15995,8 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -16340,7 +16364,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -16362,7 +16387,8 @@ declare namespace Office { * Removes the event handlers for a supported event type. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. + * `Office.EventType.RecurrenceChanged`. + * In Preview, `Office.EventType.AttachmentsChanged` and `Office.EventType.EnhancedLocationsChanged` are also supported. * * [Api set: Mailbox 1.7] * @@ -16625,7 +16651,8 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently, the only supported event type is `Office.EventType.ItemChanged`. In Preview, `Office.EventType.OfficeThemeChanged` is also supported. + * Currently, the only supported event type is `Office.EventType.ItemChanged`. + * In Preview, `Office.EventType.OfficeThemeChanged` is also supported. * * [Api set: Mailbox 1.5] * @@ -16647,7 +16674,8 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently, the only supported event type is `Office.EventType.ItemChanged`. In Preview, `Office.EventType.OfficeThemeChanged` is also supported. + * Currently, the only supported event type is `Office.EventType.ItemChanged`. + * In Preview, `Office.EventType.OfficeThemeChanged` is also supported. * * [Api set: Mailbox 1.5] * @@ -17038,7 +17066,8 @@ declare namespace Office { /** * Removes the event handlers for a supported event type. * - * Currently, the only supported event type is `Office.EventType.ItemChanged`. In Preview, `Office.EventType.OfficeThemeChanged` is also supported. + * Currently, the only supported event type is `Office.EventType.ItemChanged`. + * In Preview, `Office.EventType.OfficeThemeChanged` is also supported. * * [Api set: Mailbox 1.5] * @@ -17058,7 +17087,8 @@ declare namespace Office { /** * Removes the event handlers for a supported event type. * - * Currently, the only supported event type is `Office.EventType.ItemChanged`. In Preview, `Office.EventType.OfficeThemeChanged` is also supported. + * Currently, the only supported event type is `Office.EventType.ItemChanged`. + * In Preview, `Office.EventType.OfficeThemeChanged` is also supported. * * [Api set: Mailbox 1.5] * diff --git a/types/ora/index.d.ts b/types/ora/index.d.ts index 08a1946c5d..13104b0b5c 100644 --- a/types/ora/index.d.ts +++ b/types/ora/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ora 3.0 +// Type definitions for ora 3.1 // Project: https://github.com/sindresorhus/ora // Definitions by: Basarat Ali Syed // Christian Rackerseder @@ -45,6 +45,16 @@ declare namespace ora { */ color: Color; + /** + * Change the spinner. + */ + spinner: SpinnerName | Spinner; + + /** + * Change the spinner indent. + */ + indent: number; + /** * Start the spinner. * @@ -149,6 +159,11 @@ declare namespace ora { * @default true */ hideCursor?: boolean; + /** + * Indent the spinner with the given number of spaces. + * @default 0 + */ + indent?: number; /** * Interval between each frame. * diff --git a/types/ora/ora-tests.ts b/types/ora/ora-tests.ts index 2c1b8ee82d..4e06c11248 100644 --- a/types/ora/ora-tests.ts +++ b/types/ora/ora-tests.ts @@ -9,6 +9,7 @@ ora({ spinner: { interval: 80, frames: ['-', '+', '-'] } }); ora({ color: 'cyan' }); ora({ color: 'foo' }); // $ExpectError ora({ hideCursor: true }); +ora({ indent: 1 }); ora({ interval: 80 }); ora({ stream: new PassThrough() }); ora({ isEnabled: true }); @@ -17,6 +18,8 @@ spinner.color = 'yellow'; spinner.text = 'Loading rainbows'; spinner.isSpinning; // $ExpectType boolean spinner.isSpinning = true; // $ExpectError +spinner.spinner = 'dots'; +spinner.indent = 5; spinner.start(); spinner.start('Test text'); diff --git a/types/p-event/index.d.ts b/types/p-event/index.d.ts index 0fde40d140..6f76b75748 100644 --- a/types/p-event/index.d.ts +++ b/types/p-event/index.d.ts @@ -1,17 +1,84 @@ -// Type definitions for p-event 1.3 +// Type definitions for p-event 2.3 // Project: https://github.com/sindresorhus/p-event#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 +import { PCancelable } from 'p-cancelable'; + export = pEvent; -declare function pEvent(emitter: pEvent.Emitter, event: string | symbol, options: MultiArgsOptions): Promise>; -declare function pEvent(emitter: pEvent.Emitter, event: string | symbol, filter: FilterFn): Promise; -declare function pEvent(emitter: pEvent.Emitter, event: string | symbol, options?: pEvent.Options): Promise; +/** + * Promisify an event by waiting for it to be emitted. + * + * Returns a `Promise` that is fulfilled when emitter emits an event matching `event`, or rejects if emitter emits + * any of the events defined in the `rejectionEvents` option. + * + * **Note**: `event` is a string for a single event type, for example, `'data'`. To listen on multiple + * events, pass an array of strings, such as `['started', 'stopped']`. + * + * The returned promise has a `.cancel()` method, which when called, removes the event listeners and causes the promise to never be settled. + * + * @param emitter Event emitter object. Should have either a `.on()`/`.addListener()`/`.addEventListener()` and + * `.off()`/`.removeListener()`/`.removeEventListener()` method, like the [Node.js `EventEmitter`](https://nodejs.org/api/events.html) and + * [DOM events](https://developer.mozilla.org/en-US/docs/Web/Events). + * @param event Name of the event or events to listen to. If the same event is defined both here and in + * `rejectionEvents`, this one takes priority. + */ +declare function pEvent( + emitter: pEvent.Emitter, + event: string | symbol | Array, + options: pEvent.MultiArgsOptions +): PCancelable>; +declare function pEvent( + emitter: pEvent.Emitter, + event: string | symbol | Array, + filter: pEvent.FilterFn +): PCancelable; +declare function pEvent( + emitter: pEvent.Emitter, + event: string | symbol | Array, + options?: pEvent.Options +): PCancelable; declare namespace pEvent { - interface Emitter { + /** + * Wait for multiple event emissions. Returns an array. + */ + function multiple( + emitter: Emitter, + event: string | symbol | Array, + options: MultipleMultiArgsOptions + ): PCancelable>>; + function multiple( + emitter: Emitter, + event: string | symbol | Array, + options: MultipleOptions + ): PCancelable; + + /** + * Returns an [async iterator](http://2ality.com/2016/10/asynchronous-iteration.html) that lets you asynchronously + * iterate over events of `event` emitted from `emitter`. The iterator ends when `emitter` emits an event matching + * any of the events defined in `resolutionEvents`, or rejects if `emitter` emits any of the events defined in + * the `rejectionEvents` option. + */ + function iterator( + emitter: Emitter, + event: string | symbol | Array, + options: IteratorMultiArgsOptions + ): AsyncIterableIterator>; + function iterator( + emitter: Emitter, + event: string | symbol | Array, + filter: FilterFn + ): AsyncIterableIterator; + function iterator( + emitter: Emitter, + event: string | symbol | Array, + options?: IteratorOptions + ): AsyncIterableIterator; + + interface Emitter { on?: AddRmListenerFn; addListener?: AddRmListenerFn; addEventListener?: AddRmListenerFn; @@ -20,17 +87,119 @@ declare namespace pEvent { removeEventListener?: AddRmListenerFn; } + type FilterFn = (el: T) => boolean; + interface Options { - rejectionEvents?: string[]; + /** + * Events that will reject the promise. + * @default ['error'] + */ + rejectionEvents?: Array; + /** + * By default, the promisified function will only return the first argument from the event callback, + * which works fine for most APIs. This option can be useful for APIs that return multiple arguments + * in the callback. Turning this on will make it return an array of all arguments from the callback, + * instead of just the first argument. This also applies to rejections. + * + * @example + * const pEvent = require('p-event'); + * const emitter = require('./some-event-emitter'); + * + * (async () => { + * const [foo, bar] = await pEvent(emitter, 'finish', {multiArgs: true}); + * })(); + * + * @default false + */ multiArgs?: boolean; + /** + * Time in milliseconds before timing out. + * @default Infinity + */ timeout?: number; + /** + * Filter function for accepting an event. + * + * @example + * const pEvent = require('p-event'); + * const emitter = require('./some-event-emitter'); + * + * (async () => { + * const result = await pEvent(emitter, '🦄', value => value > 3); + * // Do something with first 🦄 event with a value greater than 3 + * })(); + */ filter?: FilterFn; } + + interface MultiArgsOptions extends Options { + multiArgs: true; + } + + interface MultipleOptions extends Options { + /** + * The number of times the event needs to be emitted before the promise resolves. + */ + count: number; + /** + * Whether to resolve the promise immediately. Emitting one of the `rejectionEvents` won't throw an error. + * + * **Note**: The returned array will be mutated when an event is emitted. + * + * @example + * const emitter = new EventEmitter(); + * + * const promise = pEvent.multiple(emitter, 'hello', { + * resolveImmediately: true, + * count: Infinity + * }); + * + * const result = await promise; + * console.log(result); + * //=> [] + * + * emitter.emit('hello', 'Jack'); + * console.log(result); + * //=> ['Jack'] + * + * emitter.emit('hello', 'Mark'); + * console.log(result); + * //=> ['Jack', 'Mark'] + * + * // Stops listening + * emitter.emit('error', new Error('😿')); + * + * emitter.emit('hello', 'John'); + * console.log(result); + * //=> ['Jack', 'Mark'] + */ + resolveImmediately?: boolean; + } + + interface MultipleMultiArgsOptions extends MultipleOptions { + multiArgs: true; + } + + interface IteratorOptions extends Options { + /** + * Maximum number of events for the iterator before it ends. When the limit is reached, the iterator will be + * marked as `done`. This option is useful to paginate events, for example, fetching 10 events per page. + * @default Infinity + */ + limit?: number; + /** + * Events that will end the iterator. + * @default [] + */ + resolutionEvents?: Array; + } + + interface IteratorMultiArgsOptions extends IteratorOptions { + multiArgs: true; + } } -type AddRmListenerFn = (event: string | symbol, listener: (arg1: T, ...args: TRest[]) => void) => void; -type FilterFn = (el: T) => boolean; - -interface MultiArgsOptions extends pEvent.Options { - multiArgs: true; -} +type AddRmListenerFn = ( + event: string | symbol, + listener: (arg1: T, ...args: TRest[]) => void +) => void; diff --git a/types/p-event/p-event-tests.ts b/types/p-event/p-event-tests.ts index 0295cdb34b..dbbe50eee7 100644 --- a/types/p-event/p-event-tests.ts +++ b/types/p-event/p-event-tests.ts @@ -1,51 +1,85 @@ /// import pEvent = require('p-event'); -import * as events from 'events'; +import { EventEmitter } from 'events'; import * as fs from 'fs'; -class MyEmitter extends events.EventEmitter { +class NodeEmitter extends EventEmitter { + on(event: 'finish', listener: (num: number, str: string) => void) { + return this; + } + addListener(event: 'finish', listener: (num: number, str: string) => void) { + return this; + } + addEventListener(event: 'finish', listener: (num: number, str: string) => void) { + return this; + } + off(event: 'finish', listener: (num: number, str: string) => void) { + return this; + } + removeListener(event: 'finish', listener: (num: number, str: string) => void) { + return this; + } + removeEventListener(event: 'finish', listener: (num: number, str: string) => void) { + return this; + } } -class MyDomEmitter implements EventTarget { - addEventListener(type: 'foo', listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void { - } +class DomEmitter implements EventTarget { + addEventListener( + type: 'foo', + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void {} dispatchEvent(event: Event): boolean { return false; } - removeEventListener(type: 'foo', listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void { - } + removeEventListener( + type: 'foo', + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void {} } -pEvent(new MyEmitter(), 'finish') - .then(result => { - console.log(result); - }) - .catch(error => { - console.error(error); - }); +pEvent(new NodeEmitter(), 'finish'); // $ExpectType PCancelable +pEvent(new NodeEmitter(), '🦄', value => value > 3); // $ExpectType PCancelable +pEvent(new DomEmitter(), 'finish'); // $ExpectType PCancelable +pEvent(document, 'DOMContentLoaded'); // $ExpectType PCancelable -pEvent(new MyEmitter(), 'finish').then(result => { - const str: string = result; -}); +pEvent(new NodeEmitter(), 'finish', { rejectionEvents: ['error'] }); // $ExpectType PCancelable +pEvent(new NodeEmitter(), 'finish', { timeout: 1 }); // $ExpectType PCancelable +pEvent(new NodeEmitter(), 'finish', { filter: value => value > 3 }); // $ExpectType PCancelable +pEvent(new NodeEmitter(), 'finish', { multiArgs: true }); // $ExpectType PCancelable<(string | number)[]> -pEvent(new MyDomEmitter(), 'finish').then(result => { - const e: Event | undefined = result; -}); +pEvent(new NodeEmitter(), 'finish').cancel(); -pEvent(document, 'DOMContentLoaded').then(() => { - console.log('😎'); +// $ExpectType PCancelable +pEvent.multiple(new NodeEmitter(), 'hello', { + count: Infinity, }); +// $ExpectType PCancelable +pEvent.multiple(new NodeEmitter(), 'hello', { + resolveImmediately: true, + count: Infinity, +}); +// $ExpectType PCancelable<(string | number)[][]> +pEvent.multiple(new NodeEmitter(), 'hello', { + count: Infinity, + multiArgs: true, +}); +// $ExpectError +pEvent.multiple(new NodeEmitter(), 'hello', {}); +// $ExpectError +pEvent.multiple(new NodeEmitter(), 'hello'); -pEvent(new MyEmitter(), 'finish', {multiArgs: true}).then(result => { - const strArr: string[] = result; -}); +pEvent.iterator(new NodeEmitter(), 'finish'); // $ExpectType AsyncIterableIterator +pEvent.iterator(new NodeEmitter(), '🦄', value => value > 3); // $ExpectType AsyncIterableIterator -pEvent(new MyEmitter(), '🦄', value => value > 3).then(result => { - const num: number = result; -}); +pEvent.iterator(new NodeEmitter(), 'finish', { limit: 1 }); // $ExpectType AsyncIterableIterator +pEvent.iterator(new NodeEmitter(), 'finish', { resolutionEvents: ['finish'] }); // $ExpectType AsyncIterableIterator +pEvent.iterator(new NodeEmitter(), 'finish', { multiArgs: true }); // $ExpectType AsyncIterableIterator<(string | number)[]> async function getOpenReadStream(file: string) { const stream = fs.createReadStream(file); @@ -53,9 +87,24 @@ async function getOpenReadStream(file: string) { return stream; } -getOpenReadStream('unicorn.txt') - .then(stream => { - console.log('Is readable:', stream.readable); - stream.pipe(process.stdout); - }) - .catch(console.error); +(async () => { + const stream = await getOpenReadStream('unicorn.txt'); + stream.pipe(process.stdout); +})().catch(console.error); + +(async () => { + try { + const result = await pEvent(new NodeEmitter(), 'finish'); + + if (result === 1) { + throw new Error('Emitter finished with an error'); + } + + // `emitter` emitted a `finish` event with an acceptable value + console.log(result); + } catch (error) { + // `emitter` emitted an `error` event or + // emitted a `finish` with 'unwanted result' + console.error(error); + } +})(); diff --git a/types/p-event/tsconfig.json b/types/p-event/tsconfig.json index 0e047aa84b..dfde34c0e1 100644 --- a/types/p-event/tsconfig.json +++ b/types/p-event/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", + "es2016", "dom" ], "noImplicitAny": true, @@ -21,4 +21,4 @@ "index.d.ts", "p-event-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/p-event/v1/index.d.ts b/types/p-event/v1/index.d.ts new file mode 100644 index 0000000000..0fde40d140 --- /dev/null +++ b/types/p-event/v1/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for p-event 1.3 +// Project: https://github.com/sindresorhus/p-event#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export = pEvent; + +declare function pEvent(emitter: pEvent.Emitter, event: string | symbol, options: MultiArgsOptions): Promise>; +declare function pEvent(emitter: pEvent.Emitter, event: string | symbol, filter: FilterFn): Promise; +declare function pEvent(emitter: pEvent.Emitter, event: string | symbol, options?: pEvent.Options): Promise; + +declare namespace pEvent { + interface Emitter { + on?: AddRmListenerFn; + addListener?: AddRmListenerFn; + addEventListener?: AddRmListenerFn; + off?: AddRmListenerFn; + removeListener?: AddRmListenerFn; + removeEventListener?: AddRmListenerFn; + } + + interface Options { + rejectionEvents?: string[]; + multiArgs?: boolean; + timeout?: number; + filter?: FilterFn; + } +} + +type AddRmListenerFn = (event: string | symbol, listener: (arg1: T, ...args: TRest[]) => void) => void; +type FilterFn = (el: T) => boolean; + +interface MultiArgsOptions extends pEvent.Options { + multiArgs: true; +} diff --git a/types/p-event/v1/p-event-tests.ts b/types/p-event/v1/p-event-tests.ts new file mode 100644 index 0000000000..0295cdb34b --- /dev/null +++ b/types/p-event/v1/p-event-tests.ts @@ -0,0 +1,61 @@ +/// + +import pEvent = require('p-event'); +import * as events from 'events'; +import * as fs from 'fs'; + +class MyEmitter extends events.EventEmitter { +} + +class MyDomEmitter implements EventTarget { + addEventListener(type: 'foo', listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void { + } + + dispatchEvent(event: Event): boolean { + return false; + } + + removeEventListener(type: 'foo', listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void { + } +} + +pEvent(new MyEmitter(), 'finish') + .then(result => { + console.log(result); + }) + .catch(error => { + console.error(error); + }); + +pEvent(new MyEmitter(), 'finish').then(result => { + const str: string = result; +}); + +pEvent(new MyDomEmitter(), 'finish').then(result => { + const e: Event | undefined = result; +}); + +pEvent(document, 'DOMContentLoaded').then(() => { + console.log('😎'); +}); + +pEvent(new MyEmitter(), 'finish', {multiArgs: true}).then(result => { + const strArr: string[] = result; +}); + +pEvent(new MyEmitter(), '🦄', value => value > 3).then(result => { + const num: number = result; +}); + +async function getOpenReadStream(file: string) { + const stream = fs.createReadStream(file); + await pEvent(stream, 'open'); + return stream; +} + +getOpenReadStream('unicorn.txt') + .then(stream => { + console.log('Is readable:', stream.readable); + stream.pipe(process.stdout); + }) + .catch(console.error); diff --git a/types/p-event/v1/tsconfig.json b/types/p-event/v1/tsconfig.json new file mode 100644 index 0000000000..e8374c9b9e --- /dev/null +++ b/types/p-event/v1/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "p-event": [ + "p-event/v1" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "p-event-tests.ts" + ] +} diff --git a/types/p-pipe/tslint.json b/types/p-event/v1/tslint.json similarity index 100% rename from types/p-pipe/tslint.json rename to types/p-event/v1/tslint.json diff --git a/types/p-limit/index.d.ts b/types/p-limit/index.d.ts index af0306cdd9..de7b0a07d9 100644 --- a/types/p-limit/index.d.ts +++ b/types/p-limit/index.d.ts @@ -1,18 +1,43 @@ -// Type definitions for p-limit 2.0 +// Type definitions for p-limit 2.1 // Project: https://github.com/sindresorhus/p-limit#readme // Definitions by: BendingBender // Linus Unnebäck // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 export = pLimit; -declare function limit(cb: (a: A, b: B, c: C, d: D, e: E, f: F, ...args: any[]) => PromiseLike | T, a: A, b: B, c: C, d: D, e: E, f: F, ...args: any[]): Promise; -declare function limit(cb: (a: A, b: B, c: C, d: D, e: E, f: F) => PromiseLike | T, a: A, b: B, c: C, d: D, e: E, f: F): Promise; -declare function limit(cb: (a: A, b: B, c: C, d: D, e: E) => PromiseLike | T, a: A, b: B, c: C, d: D, e: E): Promise; -declare function limit(cb: (a: A, b: B, c: C, d: D) => PromiseLike | T, a: A, b: B, c: C, d: D): Promise; -declare function limit(cb: (a: A, b: B, c: C) => PromiseLike | T, a: A, b: B, c: C): Promise; -declare function limit(cb: (a: A, b: B) => PromiseLike | T, a: A, b: B): Promise; -declare function limit(cb: (a: A) => PromiseLike | T, a: A): Promise; -declare function limit(cb: () => PromiseLike | T): Promise; +/** + * Run multiple promise-returning & async functions with limited concurrency. + * @param concurrency Concurrency limit. Minimum: `1`. + * @returns A `limit` function. + */ +declare function pLimit(concurrency: number): pLimit.Limit; -declare function pLimit(concurrency: number): typeof limit; +declare namespace pLimit { + interface Limit { + /** + * Returns the promise returned by calling `fn(...args)`. + * + * @param fn Promise-returning/async function. + * @param args Any arguments to pass through to `fn`. + * Support for passing arguments on to the `fn` is provided in order to be able to avoid + * creating unnecessary closures. You probably don't need this optimization unless you're + * pushing a lot of functions. + */ + ( + fn: (...args: TArgs) => PromiseLike | R, + ...args: TArgs + ): Promise; + + /** + * The number of promises that are currently running. + */ + readonly activeCount: number; + + /** + * The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + */ + readonly pendingCount: number; + } +} diff --git a/types/p-limit/p-limit-tests.ts b/types/p-limit/p-limit-tests.ts index 51dcb394fe..3f9fb51083 100644 --- a/types/p-limit/p-limit-tests.ts +++ b/types/p-limit/p-limit-tests.ts @@ -8,28 +8,16 @@ const input = [ limit(() => Promise.resolve(undefined)), ]; -Promise.all(input).then(result => { - const str: string | undefined = result[0]; +Promise.all(input); // $ExpectType Promise<(string | undefined)[]> + +limit((a: string) => '', 'test').then(v => { + v; // $ExpectType string +}); +limit((a: string, b: number) => Promise.resolve(''), 'test', 1).then(v => { + v; // $ExpectType string }); -let str: string; - -declare function a(a: string): string; -declare function b(a: string, b: number): string; -declare function c(a: string, b: number, c: boolean): string; -declare function d(a: string, b: number, c: boolean, d: symbol): string; -declare function e(a: string, b: number, c: boolean, d: symbol, e: 'yes' | 'no'): string; -declare function f(a: string, b: number, c: boolean, d: symbol, e: 'yes' | 'no', f: 1 | 2): string; -declare function g(a: string, b: number, c: boolean, d: symbol, e: 'yes' | 'no', f: 1 | 2, g: true): string; - -limit(a, 'test').then(v => { str = v; }); -limit(b, 'test', 1).then(v => { str = v; }); -limit(c, 'test', 1, false).then(v => { str = v; }); -limit(d, 'test', 1, false, Symbol('test')).then(v => { str = v; }); -limit(e, 'test', 1, false, Symbol('test'), 'no').then(v => { str = v; }); -limit(f, 'test', 1, false, Symbol('test'), 'no', 2).then(v => { str = v; }); -limit(g, 'test', 1, false, Symbol('test'), 'no', 2, true).then(v => { str = v; }); - -declare function add(...args: number[]): number; - -limit(add, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13).then(v => (v === 91)); +limit.activeCount; // $ExpectType number +limit.activeCount = 1; // $ExpectError +limit.pendingCount; // $ExpectType number +limit.pendingCount = 1; // $ExpectError diff --git a/types/p-map/index.d.ts b/types/p-map/index.d.ts deleted file mode 100644 index ccaf32e711..0000000000 --- a/types/p-map/index.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Type definitions for p-map 1.1 -// Project: https://github.com/sindresorhus/p-map#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -export = pMap; - -declare function pMap(input: Iterable>, mapper: Mapper, options?: pMap.Options): Promise; - -type Input = Promise | PromiseLike | T; -type Mapper = (el: T, index: number) => Promise | R; - -declare namespace pMap { - interface Options { - concurrency?: number; - } -} diff --git a/types/p-map/p-map-tests.ts b/types/p-map/p-map-tests.ts deleted file mode 100644 index 48d4ed5e5a..0000000000 --- a/types/p-map/p-map-tests.ts +++ /dev/null @@ -1,18 +0,0 @@ -import pMap = require('p-map'); - -const sites = [ - Promise.resolve('sindresorhus'), - true, - 1 -]; - -const mapper = (el: number | string | boolean) => Promise.resolve(1); - -let num: number; -pMap(sites, mapper, {concurrency: 2}).then(result => { - num = result[3]; -}); - -pMap(sites, mapper).then(result => { - num = result[3]; -}); diff --git a/types/p-pipe/index.d.ts b/types/p-pipe/index.d.ts deleted file mode 100644 index 2c58bd8f01..0000000000 --- a/types/p-pipe/index.d.ts +++ /dev/null @@ -1,86 +0,0 @@ -// Type definitions for p-pipe 1.2 -// Project: https://github.com/sindresorhus/p-pipe#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 - -export = pPipe; - -// tslint:disable:no-unnecessary-generics -declare function pPipe(...args: Tasks1): PromiseTask; -declare function pPipe(...args: Tasks2): PromiseTask; -declare function pPipe(...args: Tasks3): PromiseTask; -declare function pPipe(...args: Tasks4): PromiseTask; -declare function pPipe( - ...args: Tasks5 -): PromiseTask; -declare function pPipe( - ...args: Tasks6 -): PromiseTask; -declare function pPipe( - ...args: Tasks7 -): PromiseTask; -declare function pPipe( - ...args: Tasks8 -): PromiseTask; -declare function pPipe(...args: Array>): PromiseTask; - -declare function pPipe(tasks: Tasks1): PromiseTask; -declare function pPipe(tasks: Tasks2): PromiseTask; -declare function pPipe(tasks: Tasks3): PromiseTask; -declare function pPipe(tasks: Tasks4): PromiseTask; -declare function pPipe( - tasks: Tasks5 -): PromiseTask; -declare function pPipe( - tasks: Tasks6 -): PromiseTask; -declare function pPipe( - tasks: Tasks7 -): PromiseTask; -declare function pPipe( - tasks: Tasks8 -): PromiseTask; -declare function pPipe(tasks: Array>): PromiseTask; - -type Tasks1 = [PromiseTask]; -type Tasks2 = [Task, Task]; -type Tasks3 = [Task, Task, Task]; -type Tasks4 = [Task, Task, Task, Task]; -type Tasks5 = [ - Task, - Task, - Task, - Task, - Task -]; -type Tasks6 = [ - Task, - Task, - Task, - Task, - Task, - Task -]; -type Tasks7 = [ - Task, - Task, - Task, - Task, - Task, - Task, - Task -]; -type Tasks8 = [ - Task, - Task, - Task, - Task, - Task, - Task, - Task, - Task -]; - -type Task = (input: T) => PromiseLike | R; -type PromiseTask = (input: T) => Promise; diff --git a/types/p-pipe/p-pipe-tests.ts b/types/p-pipe/p-pipe-tests.ts deleted file mode 100644 index 8901637430..0000000000 --- a/types/p-pipe/p-pipe-tests.ts +++ /dev/null @@ -1,57 +0,0 @@ -import pPipe = require('p-pipe'); - -const addUnicorn = (str: string) => Promise.resolve(`${str} Unicorn`); -const addRainbow = (str: string) => Promise.resolve(`${str} Rainbow`); - -const pipeline = pPipe(addUnicorn, addRainbow); - -pipeline('❤️'); // $ExpectType Promise - -const strToInt = (s: string) => Promise.resolve(1); -const intToBool = (i: number) => Promise.resolve(true); -const boolToObj = (b: boolean) => Promise.resolve({}); -const objToNull = (o: object) => Promise.resolve(null); -const nullToVoid = (n: null) => Promise.resolve(undefined); -const voidToStr = (u: undefined) => Promise.resolve(''); - -pPipe(strToInt); // $ExpectType PromiseTask -pPipe(strToInt, intToBool); // $ExpectType PromiseTask -pPipe(strToInt, intToBool, boolToObj); // $ExpectType PromiseTask -pPipe(strToInt, intToBool, boolToObj, objToNull); // $ExpectType PromiseTask -pPipe(strToInt, intToBool, boolToObj, objToNull, nullToVoid); // $ExpectType PromiseTask -pPipe(strToInt, intToBool, boolToObj, objToNull, nullToVoid, voidToStr); // $ExpectType PromiseTask -pPipe(strToInt, intToBool, boolToObj, objToNull, nullToVoid, voidToStr, strToInt); // $ExpectType PromiseTask -pPipe(strToInt, intToBool, boolToObj, objToNull, nullToVoid, voidToStr, strToInt, intToBool); // $ExpectType PromiseTask -// $ExpectType PromiseTask -pPipe( - strToInt, - intToBool, - boolToObj, - objToNull, - nullToVoid, - voidToStr, - strToInt, - intToBool, - boolToObj -); - -pPipe([strToInt]); // $ExpectType PromiseTask -pPipe([strToInt, intToBool]); // $ExpectType PromiseTask -pPipe([strToInt, intToBool, boolToObj]); // $ExpectType PromiseTask -pPipe([strToInt, intToBool, boolToObj, objToNull]); // $ExpectType PromiseTask -pPipe([strToInt, intToBool, boolToObj, objToNull, nullToVoid]); // $ExpectType PromiseTask -pPipe([strToInt, intToBool, boolToObj, objToNull, nullToVoid, voidToStr]); // $ExpectType PromiseTask -pPipe([strToInt, intToBool, boolToObj, objToNull, nullToVoid, voidToStr, strToInt]); // $ExpectType PromiseTask -pPipe([strToInt, intToBool, boolToObj, objToNull, nullToVoid, voidToStr, strToInt, intToBool]); // $ExpectType PromiseTask -// $ExpectType PromiseTask -pPipe([ - strToInt, - intToBool, - boolToObj, - objToNull, - nullToVoid, - voidToStr, - strToInt, - intToBool, - boolToObj, -]); diff --git a/types/papaparse/index.d.ts b/types/papaparse/index.d.ts index 300e33b4a5..372df6a737 100644 --- a/types/papaparse/index.d.ts +++ b/types/papaparse/index.d.ts @@ -11,7 +11,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -import "node"; +/// export as namespace Papa; diff --git a/types/parcel-bundler/index.d.ts b/types/parcel-bundler/index.d.ts index c661d105cd..230d928db1 100644 --- a/types/parcel-bundler/index.d.ts +++ b/types/parcel-bundler/index.d.ts @@ -2,7 +2,9 @@ // Project: https://github.com/parcel-bundler/parcel#readme // Definitions by: pinage404 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 + +import * as express from "express-serve-static-core"; declare namespace ParcelBundler { interface ParcelOptions { @@ -173,6 +175,8 @@ declare class ParcelBundler { addPackager(type: string, packager: string): void; bundle(): Promise; + + middleware(): (req: express.Request, res: express.Response, next: express.NextFunction) => any; } export = ParcelBundler; diff --git a/types/parcel-bundler/parcel-bundler-tests.ts b/types/parcel-bundler/parcel-bundler-tests.ts index 5833b8527b..0623056c89 100644 --- a/types/parcel-bundler/parcel-bundler-tests.ts +++ b/types/parcel-bundler/parcel-bundler-tests.ts @@ -10,4 +10,6 @@ bundler.addAssetType('md', 'markdown-asset'); bundler.addPackager('md', 'markdown-packager'); +bundler.middleware(); + bundler.bundle().then(bundle => bundle.name); diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index bf89204b04..b87a9f5f56 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -7,6 +7,7 @@ // Wes Grimes // Otherwise SAS // Andrew Goldis +// Alexandre Hétu Rivard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -490,7 +491,7 @@ declare namespace Parse { /** * Represents a LiveQuery Subscription. - * + * * @see https://docs.parseplatform.org/js/guide/#live-queries * @see NodeJS.EventEmitter * @@ -556,7 +557,7 @@ subscription.on('close', () => {}); class LiveQuerySubscription extends NodeJS.EventEmitter { /** * Creates an instance of LiveQuerySubscription. - * + * * @param {string} id * @param {string} query * @param {string} [sessionToken] @@ -692,12 +693,7 @@ subscription.on('close', () => {}); interface JobRequest { params: any; - } - - interface JobStatus { - error?: (response: any) => void; - message?: (response: any) => void; - success?: (response: any) => void; + message: (response: any) => void; } interface FunctionRequest { @@ -707,12 +703,6 @@ subscription.on('close', () => {}); user?: User; } - interface FunctionResponse { - success: (response: any) => void; - error (code: number, response: any): void; - error (response: any): void; - } - interface Cookie { name?: string; options?: CookieOptions; @@ -734,11 +724,7 @@ subscription.on('close', () => {}); interface AfterSaveRequest extends TriggerRequest { } interface AfterDeleteRequest extends TriggerRequest { } interface BeforeDeleteRequest extends TriggerRequest { } - interface BeforeDeleteResponse extends FunctionResponse { } interface BeforeSaveRequest extends TriggerRequest { } - interface BeforeSaveResponse extends FunctionResponse { - success: () => void; - } // Read preference describes how MongoDB driver route read operations to the members of a replica set. enum ReadPreferenceOption { @@ -760,19 +746,16 @@ subscription.on('close', () => {}); objects: Object[] } - interface AfterFindResponse extends FunctionResponse { - success: (objects: Object[]) => void; - } - - function afterDelete(arg1: any, func?: (request: AfterDeleteRequest) => void): void; - function afterSave(arg1: any, func?: (request: AfterSaveRequest) => void): void; - function beforeDelete(arg1: any, func?: (request: BeforeDeleteRequest, response: BeforeDeleteResponse) => void): void; - function beforeSave(arg1: any, func?: (request: BeforeSaveRequest, response: BeforeSaveResponse) => void): void; - function beforeFind(arg1: any, func?: (request: BeforeFindRequest) => void): void; - function afterFind(arg1: any, func?: (request: AfterFindRequest, response: AfterFindResponse) => void): void; - function define(name: string, func?: (request: FunctionRequest, response: FunctionResponse) => void): void; + function afterDelete(arg1: any, func?: (request: AfterDeleteRequest) => Promise | void): void; + function afterSave(arg1: any, func?: (request: AfterSaveRequest) => Promise | void): void; + function beforeDelete(arg1: any, func?: (request: BeforeDeleteRequest) => Promise | void): void; + function beforeSave(arg1: any, func?: (request: BeforeSaveRequest) => Promise | void): void; + function beforeFind(arg1: any, func?: (request: BeforeFindRequest) => Promise | void): void; + function beforeFind(arg1: any, func?: (request: BeforeFindRequest) => Promise | Query): void; + function afterFind(arg1: any, func?: (request: AfterFindRequest) => Promise | any): void; + function define(name: string, func?: (request: FunctionRequest) => Promise | any): void; function httpRequest(options: HTTPOptions): Promise; - function job(name: string, func?: (request: JobRequest, status: JobStatus) => void): HttpResponse; + function job(name: string, func?: (request: JobRequest) => Promise | void): HttpResponse; function run(name: string, data?: any, options?: RunOptions): Promise; function useMasterKey(): void; diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index 8a2064e968..cb80764cd4 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -126,7 +126,7 @@ function test_query() { // Find objects with distinct key query.distinct('name'); - const testQuery = Parse.Query.or(query, query); + const testQuery = Parse.Query.or(query, query); } async function test_query_promise() { @@ -348,30 +348,30 @@ function test_cloud_functions() { // result }); - Parse.Cloud.beforeDelete('MyCustomClass', (request: Parse.Cloud.BeforeDeleteRequest, - response: Parse.Cloud.BeforeDeleteResponse) => { + Parse.Cloud.beforeDelete('MyCustomClass', (request: Parse.Cloud.BeforeDeleteRequest) => { + // result + }); + + Parse.Cloud.beforeDelete('MyCustomClass', async (request: Parse.Cloud.BeforeDeleteRequest) => { // result }); const CUSTOM_ERROR_INVALID_CONDITION = 1001 const CUSTOM_ERROR_IMMUTABLE_FIELD = 1002 - Parse.Cloud.beforeSave('MyCustomClass', (request: Parse.Cloud.BeforeSaveRequest, - response: Parse.Cloud.BeforeSaveResponse) => { - + Parse.Cloud.beforeSave('MyCustomClass', async (request: Parse.Cloud.BeforeSaveRequest) => { if (request.object.isNew()) { - if (!request.object.has('immutable')) return response.error('Field immutable is required') + if (!request.object.has('immutable')) throw new Error('Field immutable is required') } else { const original = request.original; if (original == null) { // When the object is not new, request.original must be defined - return response.error(CUSTOM_ERROR_INVALID_CONDITION, 'Original must me defined for an existing object') + throw new Parse.Error(CUSTOM_ERROR_INVALID_CONDITION, 'Original must me defined for an existing object') } if (original.get('immutable') !== request.object.get('immutable')) { - return response.error(CUSTOM_ERROR_IMMUTABLE_FIELD, 'This field cannot be changed') + throw new Parse.Error(CUSTOM_ERROR_IMMUTABLE_FIELD, 'This field cannot be changed') } } - response.success() }); Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => { @@ -388,6 +388,30 @@ function test_cloud_functions() { request.readPreference = Parse.Cloud.ReadPreferenceOption.SecondaryPreferred request.readPreference = Parse.Cloud.ReadPreferenceOption.Nearest }); + + Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => { + let query = request.query; // the Parse.Query + + return new Parse.Query("QueryMe!"); + }); + + Parse.Cloud.beforeFind('MyCustomClass', async (request: Parse.Cloud.BeforeFindRequest) => { + let query = request.query; // the Parse.Query + + return new Parse.Query("QueryMe, IN THE FUTURE!"); + }); + + Parse.Cloud.afterFind('MyCustomClass', async (request: Parse.Cloud.AfterFindRequest) => { + return new Parse.Object('MyCustomClass'); + }); + + Parse.Cloud.define('AFunc', (request: Parse.Cloud.FunctionRequest) => { + return 'Some result'; + }); + + Parse.Cloud.job('AJob', (request: Parse.Cloud.JobRequest) => { + request.message('Message to associate with this job run'); + }); } class PlaceObject extends Parse.Object { } diff --git a/types/petit-dom/index.d.ts b/types/petit-dom/index.d.ts index 52e507f980..7f850bb1dd 100644 --- a/types/petit-dom/index.d.ts +++ b/types/petit-dom/index.d.ts @@ -98,6 +98,7 @@ export namespace PetitDom { }; interface IntrinsicProps { + content?: Content | ReadonlyArray; key?: Key; } diff --git a/types/pg-copy-streams/index.d.ts b/types/pg-copy-streams/index.d.ts new file mode 100644 index 0000000000..4f468d5639 --- /dev/null +++ b/types/pg-copy-streams/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for pg-copy-streams 1.2 +// Project: https://github.com/brianc/node-pg-copy-streams +// Definitions by: Brian Crowell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Submittable, Connection } from "pg"; +import { Transform, TransformOptions } from "stream"; + +export function from(txt: string, options?: TransformOptions): CopyStreamQuery; +export function to(txt: string, options?: TransformOptions): CopyToStreamQuery; + +export class CopyStreamQuery extends Transform implements Submittable { + submit(connection: Connection): void; +} + +export class CopyToStreamQuery extends Transform implements Submittable { + submit(connection: Connection): void; +} diff --git a/types/pg-copy-streams/pg-copy-streams-tests.ts b/types/pg-copy-streams/pg-copy-streams-tests.ts new file mode 100644 index 0000000000..41d960ab4e --- /dev/null +++ b/types/pg-copy-streams/pg-copy-streams-tests.ts @@ -0,0 +1,19 @@ +import { Client } from "pg"; +import { from, to } from "pg-copy-streams"; + +const client = new Client('fake-config-string'); + +const copyStream = client.query(from('copy data from stdin;')); + +copyStream.write('', err => { + if (err) { + console.error(err); + return; + } + + copyStream.end(); +}); + +const readStream = client.query(to('copy data to stdout;')); + +readStream.pipe(process.stdout); diff --git a/types/dd-trace/tsconfig.json b/types/pg-copy-streams/tsconfig.json similarity index 92% rename from types/dd-trace/tsconfig.json rename to types/pg-copy-streams/tsconfig.json index 6e65e3983c..6b8989eb58 100644 --- a/types/dd-trace/tsconfig.json +++ b/types/pg-copy-streams/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "dd-trace-tests.ts" + "pg-copy-streams-tests.ts" ] } \ No newline at end of file diff --git a/types/wait-for-localhost/tslint.json b/types/pg-copy-streams/tslint.json similarity index 100% rename from types/wait-for-localhost/tslint.json rename to types/pg-copy-streams/tslint.json diff --git a/types/pikaday/index.d.ts b/types/pikaday/index.d.ts index 2233fa9b4c..3061cd67e7 100644 --- a/types/pikaday/index.d.ts +++ b/types/pikaday/index.d.ts @@ -36,7 +36,7 @@ declare class Pikaday { * Returns a JavaScript Date object for the selected day, or null if * no date is selected. */ - getDate(): Date; + getDate(): Date | null; /** * Set the current selection. This will be restricted within the bounds @@ -50,7 +50,7 @@ declare class Pikaday { * Returns a Moment.js object for the selected date (Moment must be * loaded before Pikaday). */ - getMoment(): moment.Moment; + getMoment(): moment.Moment | null; /** * Set the current selection with a Moment.js object (see setDate). @@ -159,7 +159,7 @@ declare namespace Pikaday { /** * Bind the datepicker to a form field. */ - field?: HTMLElement; + field?: HTMLElement | null; /** * The default output format for toString() and field value. @@ -171,7 +171,7 @@ declare namespace Pikaday { * Use a different element to trigger opening the datepicker. * Default: field element. */ - trigger?: HTMLElement; + trigger?: HTMLElement | null; /** * Automatically show/hide the datepicker on field focus. @@ -201,7 +201,7 @@ declare namespace Pikaday { * DOM node to render calendar into, see container example. * Default: undefined. */ - container?: HTMLElement; + container?: HTMLElement | null; /** * The initial date to view when first opened. @@ -330,12 +330,12 @@ declare namespace Pikaday { * Function which will be used for parsing input string and getting a date object from it. * This function will take precedence over moment. */ - parse?(date: string, format: string): Date; + parse?(date: string, format: string): Date | null; /** * Callback function for when a date is selected. */ - onSelect?(date: Date): void; + onSelect?(this: Pikaday, date: Date): void; /** * Callback function for when the picker becomes visible. diff --git a/types/pikaday/pikaday-tests.ts b/types/pikaday/pikaday-tests.ts index 230104daf7..83790b70ec 100644 --- a/types/pikaday/pikaday-tests.ts +++ b/types/pikaday/pikaday-tests.ts @@ -14,15 +14,15 @@ new Pikaday({field: $('#datepicker')[0]}); console.log(date.toISOString()); } }); - field.parentNode.insertBefore(picker.el, field.nextSibling); + field.parentNode!.insertBefore(picker.el, field.nextSibling); })(); (() => { const picker = new Pikaday({ field: document.getElementById('datepicker'), format: 'D MMM YYYY', - onSelect: () => { - console.log(this.getMoment().format('Do MMMM YYYY')); + onSelect() { + console.log(this.getMoment()!.format('Do MMMM YYYY')); } }); @@ -116,3 +116,7 @@ new Pikaday({field: $('#datepicker')[0]}); toString: (date, format) => '2017-08-23' }); })(); + +new Pikaday({ + parse: (date) => null +}); diff --git a/types/pikaday/tsconfig.json b/types/pikaday/tsconfig.json index 3c936ab905..0c18391e53 100644 --- a/types/pikaday/tsconfig.json +++ b/types/pikaday/tsconfig.json @@ -6,8 +6,8 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "pikaday-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index af90a6f6a0..8e5622bdef 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for plotly.js 1.43 +// Type definitions for plotly.js 1.44 // Project: https://plot.ly/javascript/, https://github.com/plotly/plotly.js // Definitions by: Chris Gervang // Martin Duparc @@ -10,6 +10,7 @@ // Sooraj Pudiyadath // Jon Freedman // Megan Riel-Mehan +// Takafumi Yamaguchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -205,7 +206,17 @@ export function deleteFrames(root: Root, frames: number[]): Promise; + xref: 'container' | 'paper'; + yref: 'container' | 'paper'; + x: number; + y: number; + xanchor: 'auto' | 'left' | 'center' | 'right'; + yanchor: 'auto' | 'top' | 'middle' | 'bottom'; + pad: Partial + }>; titlefont: Partial; autosize: boolean; showlegend: boolean; diff --git a/types/plotly.js/test/index-tests.ts b/types/plotly.js/test/index-tests.ts index 79343f43f7..828f2870a3 100644 --- a/types/plotly.js/test/index-tests.ts +++ b/types/plotly.js/test/index-tests.ts @@ -251,6 +251,24 @@ const graphDiv = '#test'; }; Plotly.update(graphDiv, data_update, layout_update); })(); + +(() => { + const update = { + title: { + text: 'some new title', + font: { + size: 1.2, + }, + x: 0.9, + pad: { + t: 20 + }, + }, // updates the title + 'xaxis.range': [0, 5], // updates the xaxis range + 'yaxis.range[1]': 15 // updates the end of the yaxis range + } as Layout; + Plotly.relayout(graphDiv, update); +})(); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// diff --git a/types/pollyjs__core/index.d.ts b/types/pollyjs__core/index.d.ts index 8ffe642497..38cd511408 100644 --- a/types/pollyjs__core/index.d.ts +++ b/types/pollyjs__core/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/core 2.0 +// Type definitions for @pollyjs/core 2.2 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -55,8 +55,10 @@ export interface PollyConfig { } export interface Request { getHeader(name: string): string | null; - setHeader(name: string, value: string): Request; - setHeaders(headers: any): Request; + setHeader(name: string, value?: string | null): Request; + setHeaders(headers: Record): Request; + removeHeader(name: string): Request; + removeHeaders(headers: string[]): Request; hasHeader(name: string): boolean; type(contentType: string): Request; send(body: any): Request; @@ -83,8 +85,10 @@ export interface Response { body: any; status(status: number): Response; getHeader(name: string): string | null; - setHeader(name: string, value: string): Response; - setHeaders(headers: any): Response; + setHeader(name: string, value?: string | null): Response; + setHeaders(headers: Record): Response; + removeHeader(name: string): Request; + removeHeaders(headers: string[]): Request; hasHeader(name: string): boolean; type(contentType: string): Response; send(body: any): Response; @@ -100,8 +104,10 @@ export interface Intercept { export type RequestRouteEvent = 'request'; export type RecordingRouteEvent = 'beforeReplay' | 'beforePersist'; export type ResponseRouteEvent = 'beforeResponse' | 'response'; +export type ErrorRouteEvent = 'error'; export type EventListenerResponse = any; +export type ErrorEventListener = (req: Request, error: any) => EventListenerResponse; export type RequestEventListener = (req: Request) => EventListenerResponse; export type RecordingEventListener = (req: Request, recording: any) => EventListenerResponse; export type ResponseEventListener = (req: Request, res: Response) => EventListenerResponse; @@ -114,12 +120,15 @@ export class RouteHandler { on(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler; on(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler; on(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler; + on(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler; off(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler; off(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler; off(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler; + off(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler; once(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler; once(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler; once(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler; + once(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler; passthrough(value?: boolean): RouteHandler; intercept( diff --git a/types/pollyjs__core/pollyjs__core-tests.ts b/types/pollyjs__core/pollyjs__core-tests.ts index 0644eff7f4..bccd074bcf 100644 --- a/types/pollyjs__core/pollyjs__core-tests.ts +++ b/types/pollyjs__core/pollyjs__core-tests.ts @@ -127,5 +127,19 @@ async function test() { .configure({ expiresIn: '5d' }) .passthrough(); + server.any().on('error', (req, error) => { + req + .setHeader('Content-Length', '2344') + .setHeaders({ + 'Content-Type': 'application/json', + 'Content-Length': '42' + }) + .removeHeader('Content-Length') + .removeHeaders(['Content-Type', 'Content-Length']); + + req.removeHeaders(['Content-Type', 'Content-Length']); + log(req.pathname + JSON.stringify(error)); + }); + await polly.flush(); } diff --git a/types/postcss-nested/index.d.ts b/types/postcss-nested/index.d.ts new file mode 100644 index 0000000000..6bf8c45349 --- /dev/null +++ b/types/postcss-nested/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for postcss-nested 4.1 +// Project: https://github.com/postcss/postcss-nested#readme +// Definitions by: Maxim Vorontsov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { Plugin } from 'postcss'; + +declare namespace nested { + interface Options { + /** + * By default, plugin will bubble only @media and @supports at-rules. + * You can add your custom at-rules to this list by this option. + */ + bubble?: string[]; + + /** + * By default, plugin will unwrap only @font-face, @keyframes and @document at-rules. + * You can add your custom at-rules to this list by this option. + */ + unwrap?: string[]; + + /** + * By default, plugin will strip out any empty selector generated by intermediate nesting + * levels. You can set this option to true to preserve them. + */ + preserveEmpty?: boolean; + } + + type Nested = Plugin; +} + +declare const nested: nested.Nested; +export = nested; diff --git a/types/postcss-nested/package.json b/types/postcss-nested/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-nested/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-nested/postcss-nested-tests.ts b/types/postcss-nested/postcss-nested-tests.ts new file mode 100644 index 0000000000..86b0401559 --- /dev/null +++ b/types/postcss-nested/postcss-nested-tests.ts @@ -0,0 +1,12 @@ +import * as postcss from 'postcss'; +import nested = require('postcss-nested'); + +const withDefaultOptions: postcss.Transformer = nested(); +const withCustomOptions: postcss.Transformer = nested({ + bubble: ['phone'], + unwrap: ['phone'], + preserveEmpty: true +}); + +postcss().use(withDefaultOptions); +postcss().use(withCustomOptions); diff --git a/types/internal-ip/tsconfig.json b/types/postcss-nested/tsconfig.json similarity index 93% rename from types/internal-ip/tsconfig.json rename to types/postcss-nested/tsconfig.json index 99d54932e0..b6e9346303 100644 --- a/types/internal-ip/tsconfig.json +++ b/types/postcss-nested/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "internal-ip-tests.ts" + "postcss-nested-tests.ts" ] } diff --git a/types/postcss-nested/tslint.json b/types/postcss-nested/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-nested/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/postcss-url/index.d.ts b/types/postcss-url/index.d.ts index 361b69f1c7..472fccc21b 100644 --- a/types/postcss-url/index.d.ts +++ b/types/postcss-url/index.d.ts @@ -84,6 +84,13 @@ declare namespace url { */ ignoreFragmentWarning?: boolean; + /** + * Reduce size of inlined svg (IE9+, Android 3+) + * + * @default false + */ + optimizeSvgEncode?: boolean; + /** * Determine wether a file should be inlined. */ diff --git a/types/postcss-url/postcss-url-tests.ts b/types/postcss-url/postcss-url-tests.ts index a258b49be4..70086036ab 100644 --- a/types/postcss-url/postcss-url-tests.ts +++ b/types/postcss-url/postcss-url-tests.ts @@ -7,7 +7,7 @@ const single: postcss.Transformer = url({ url: 'copy', assetsPath: 'img', useHas const multiple: postcss.Transformer = url([ { filter: '**/assets/copy/*.png', url: 'copy', assetsPath: 'img', useHash: true }, - { filter: '**/assets/inline/*.svg', url: 'inline' }, + { filter: '**/assets/inline/*.svg', url: 'inline', optimizeSvgEncode: true }, { filter: '**/assets/**/*.gif', url: 'rebase' }, { filter: 'cdn/**/*', url: (asset) => `https://cdn.url/${asset.url}` }, ]); diff --git a/types/progress-stream/index.d.ts b/types/progress-stream/index.d.ts new file mode 100644 index 0000000000..17410ea177 --- /dev/null +++ b/types/progress-stream/index.d.ts @@ -0,0 +1,102 @@ +// Type definitions for progress-stream 2.0 +// Project: https://github.com/freeall/progress-stream +// Definitions by: Mick Dekkers +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import stream = require("stream"); +export = progress_stream; + +declare function progress_stream( + options: progress_stream.Options, + progressListener: progress_stream.ProgressListener, +): progress_stream.ProgressStream; + +declare function progress_stream( + optionsOrProgressListener?: + | progress_stream.Options + | progress_stream.ProgressListener, +): progress_stream.ProgressStream; + +declare namespace progress_stream { + interface Options { + time?: number; + speed?: number; + length?: number; + drain?: boolean; + transferred?: number; + } + + type ProgressListener = (progress: Progress) => void; + + interface ProgressStream extends stream.Transform { + on(event: "progress", listener: ProgressListener): this; + on(event: "length", listener: (length: number) => void): this; + once(event: "progress", listener: ProgressListener): this; + once(event: "length", listener: (length: number) => void): this; + setLength(length: number): void; + progress(): Progress; + + // We have to redeclare all on/once overloads from stream.Transform in + // order for this ProgressStream interface to extend stream.Transform + // correctly. Using an intersection type instead may be an option once + // https://github.com/Microsoft/TypeScript/issues/30031 is resolved. + + // stream.Readable events + + /* tslint:disable-next-line adjacent-overload-signatures */ + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + /* tslint:disable-next-line unified-signatures */ + on(event: "end", listener: () => void): this; + /* tslint:disable-next-line unified-signatures */ + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + /* tslint:disable-next-line adjacent-overload-signatures */ + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + /* tslint:disable-next-line unified-signatures */ + once(event: "end", listener: () => void): this; + /* tslint:disable-next-line unified-signatures */ + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + + // stream.Writable events + + /* tslint:disable-next-line adjacent-overload-signatures unified-signatures */ + on(event: "drain", listener: () => void): this; + /* tslint:disable-next-line unified-signatures */ + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + /* tslint:disable-next-line unified-signatures */ + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + /* tslint:disable-next-line adjacent-overload-signatures unified-signatures */ + once(event: "drain", listener: () => void): this; + /* tslint:disable-next-line unified-signatures */ + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + /* tslint:disable-next-line unified-signatures */ + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + + // events shared by stream.Readable and stream.Writable + + /* tslint:disable-next-line adjacent-overload-signatures */ + on(event: string | symbol, listener: (...args: any[]) => void): this; + /* tslint:disable-next-line adjacent-overload-signatures */ + once(event: string | symbol, listener: (...args: any[]) => void): this; + /* tslint:enable adjacent-overload-signatures unified-signatures */ + } + + interface Progress { + percentage: number; + transferred: number; + length: number; + remaining: number; + eta: number; + runtime: number; + delta: number; + speed: number; + } +} diff --git a/types/progress-stream/progress-stream-tests.ts b/types/progress-stream/progress-stream-tests.ts new file mode 100644 index 0000000000..e10ab0f925 --- /dev/null +++ b/types/progress-stream/progress-stream-tests.ts @@ -0,0 +1,71 @@ +import progress = require("progress-stream"); +import stream = require("stream"); + +const options: progress.Options = { + time: 100, + speed: 100, + length: 100, + drain: true, + transferred: 0, +}; + +const progressListener = (progress: progress.Progress) => { + // $ExpectType number + progress.percentage; + // $ExpectType number + progress.transferred; + // $ExpectType number + progress.length; + // $ExpectType number + progress.remaining; + // $ExpectType number + progress.eta; + // $ExpectType number + progress.runtime; + // $ExpectType number + progress.delta; + // $ExpectType number + progress.speed; +}; + +// $ExpectType ProgressStream +const p = progress(); + +// $ExpectType ProgressStream +progress(options); + +// $ExpectType ProgressStream +progress(options, progressListener); + +// $ExpectType ProgressStream +progress(progressListener); + +// $ExpectType ProgressStream +p.on("progress", progressListener); + +// $ExpectType ProgressStream +p.on("length", (length: number) => {}); + +p.setLength(200); // $ExpectType void + +p.progress(); // $ExpectType Progress + +// Check if ProgressStream extends stream.Transform correctly + +// $ExpectType ProgressStream +p.on("close", () => {}); +// $ExpectType ProgressStream +p.on("data", (chunk: any) => {}); +// $ExpectType ProgressStream +p.on("end", () => {}); +// $ExpectType ProgressStream +p.on("error", (err: Error) => {}); +// $ExpectType ProgressStream +p.on("readable", () => {}); +// $ExpectType ProgressStream +p.pause(); + +const writable = new stream.Writable(); + +// $ExpectType Writable +p.pipe(writable); diff --git a/types/progress-stream/tsconfig.json b/types/progress-stream/tsconfig.json new file mode 100644 index 0000000000..0dfc8b25fc --- /dev/null +++ b/types/progress-stream/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "progress-stream-tests.ts"] +} diff --git a/types/progress-stream/tslint.json b/types/progress-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/progress-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/prop-types/index.d.ts b/types/prop-types/index.d.ts index 75461dc372..ddb8c64947 100644 --- a/types/prop-types/index.d.ts +++ b/types/prop-types/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for prop-types 15.5 +// Type definitions for prop-types 15.7 // Project: https://github.com/reactjs/prop-types, https://facebook.github.io/react // Definitions by: DovydasNavickas // Ferdy Budhidharma +// Sebastian Silbermann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -62,6 +63,7 @@ export const string: Requireable; export const node: Requireable; export const element: Requireable; export const symbol: Requireable; +export const elementType: Requireable; export function instanceOf(expectedClass: new (...args: any[]) => T): Requireable; export function oneOf(types: T[]): Requireable; export function oneOfType>(types: T[]): Requireable>>; @@ -81,3 +83,8 @@ export function exact

    >(type: P): Requireable any): void; + +/** + * Only available if NODE_ENV=production + */ +export function resetWarningCache(): void; diff --git a/types/prop-types/prop-types-tests.ts b/types/prop-types/prop-types-tests.ts index 5973e6a7ca..e6067ee740 100644 --- a/types/prop-types/prop-types-tests.ts +++ b/types/prop-types/prop-types-tests.ts @@ -34,6 +34,7 @@ interface Props { }; optionalNumber?: number | null; customProp?: typeof uniqueType; + component: PropTypes.ReactComponentLike; } const innerProps = { @@ -74,7 +75,8 @@ const propTypes: PropTypesMap = { objectOf: PropTypes.objectOf(PropTypes.number.isRequired).isRequired, shape: PropTypes.shape(innerProps).isRequired, optionalNumber: PropTypes.number, - customProp: (() => null) as PropTypes.Validator + customProp: (() => null) as PropTypes.Validator, + component: PropTypes.elementType.isRequired }; // JS checking @@ -100,7 +102,8 @@ const propTypesWithoutAnnotation = { objectOf: PropTypes.objectOf(PropTypes.number.isRequired).isRequired, shape: PropTypes.shape(innerProps).isRequired, optionalNumber: PropTypes.number, - customProp: (() => null) as PropTypes.Validator + customProp: (() => null) as PropTypes.Validator, + component: PropTypes.elementType.isRequired }; const partialPropTypes = { @@ -150,6 +153,7 @@ type ExtractFromOuterPropsMatch4 = Props extends ExtractedPropsFromOuterPropsWit type ExtractPropsMismatch = ExtractedPartialProps extends Props ? true : false; PropTypes.checkPropTypes({ xs: PropTypes.array }, { xs: [] }, 'location', 'componentName'); +PropTypes.resetWarningCache(); // This would be the type that JSX sees type Defaultize = diff --git a/types/proper-lockfile/index.d.ts b/types/proper-lockfile/index.d.ts index 885e63808b..3e49e79fe3 100644 --- a/types/proper-lockfile/index.d.ts +++ b/types/proper-lockfile/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for proper-lockfile 3.0 // Project: https://github.com/moxystudio/node-proper-lockfile // Definitions by: Nikita Volodin +// Linus Unnebäck // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export interface LockOptions { @@ -10,17 +11,20 @@ export interface LockOptions { realpath?: boolean; // default: true fs?: any; // default: graceful-fs onCompromised?: (err: Error) => any; // default: (err) => throw err + lockfilePath?: string; // default: `${file}.lock` } export interface UnlockOptions { realpath?: boolean; // default: true fs?: any; // default: graceful-fs + lockfilePath?: string; // default: `${file}.lock` } export interface CheckOptions { stale?: number; // default: 10000 realpath?: boolean; // default: true fs?: any; // default: graceful-fs + lockfilePath?: string; // default: `${file}.lock` } export function lock(file: string, options?: LockOptions): Promise<() => Promise>; diff --git a/types/proper-lockfile/proper-lockfile-tests.ts b/types/proper-lockfile/proper-lockfile-tests.ts index 7555fd5116..344e7be3f8 100644 --- a/types/proper-lockfile/proper-lockfile-tests.ts +++ b/types/proper-lockfile/proper-lockfile-tests.ts @@ -39,7 +39,12 @@ check('some/file') // isLocked will be true if 'some/file' is locked, false otherwise }); +lock('', { lockfilePath: 'some/file-lock' }) + .then((release) => release()); + const release = lockSync('some/file'); // $ExpectType () => void release(); // $ExpectType void unlockSync('some/file'); // $ExpectType void +unlockSync('', { lockfilePath: 'some/file-lock' }); // $ExpectType void checkSync('some/file'); // $ExpectType boolean +checkSync('', { lockfilePath: 'some/file-lock' }); // $ExpectType boolean diff --git a/types/prosemirror-state/index.d.ts b/types/prosemirror-state/index.d.ts index a0c2b6ae69..0fc8950838 100644 --- a/types/prosemirror-state/index.d.ts +++ b/types/prosemirror-state/index.d.ts @@ -22,7 +22,7 @@ import { EditorProps, EditorView } from 'prosemirror-view'; * This is the type passed to the [`Plugin`](#state.Plugin) * constructor. It provides a definition for a plugin. */ -export interface PluginSpec { +export interface PluginSpec { /** * The [view props](#view.EditorProps) added by this plugin. Props * that are functions will be bound to have the plugin instance as @@ -33,14 +33,14 @@ export interface PluginSpec { * Allows a plugin to define a [state field](#state.StateField), an * extra slot in the state object in which it can keep its own data. */ - state?: StateField | null; + state?: StateField | null; /** * Can be used to make this a keyed plugin. You can have only one * plugin with a given key in a given state, but it is possible to * access the plugin's configuration and state through the key, * without having access to the plugin instance object. */ - key?: PluginKey | null; + key?: PluginKey | null; /** * When the plugin needs to interact with the editor view, or * set something up in the DOM, use this field. The function @@ -82,11 +82,11 @@ export interface PluginSpec { * They are part of the [editor state](#state.EditorState) and * may influence that state and the view that contains it. */ -export class Plugin { +export class Plugin { /** * Create a plugin. */ - constructor(spec: PluginSpec); + constructor(spec: PluginSpec); /** * The [props](#view.EditorProps) exported by this plugin. */ @@ -94,11 +94,11 @@ export class Plugin { /** * The plugin's [spec object](#state.PluginSpec). */ - spec: { [key: string]: any }; + spec: PluginSpec; /** * Extract the plugin's state field from an editor state. */ - getState(state: EditorState): any; + getState(state: EditorState): T; } /** * A plugin spec may provide a state field (under its @@ -106,7 +106,7 @@ export class Plugin { * describes the state it wants to keep. Functions provided here are * always called with the plugin instance as their `this` binding. */ -export interface StateField { +export interface StateField { /** * Initialize the value of the field. `config` will be the object * passed to [`EditorState.create`](#state.EditorState^create). Note @@ -138,7 +138,7 @@ export interface StateField { * editor state. Assigning a key does mean only one plugin of that * type can be active in a state. */ -export class PluginKey { +export class PluginKey { /** * Create a plugin key. */ @@ -147,7 +147,7 @@ export class PluginKey { * Get the active plugin with this key, if any, from an editor * state. */ - get(state: EditorState): Plugin | null | undefined; + get(state: EditorState): Plugin | null | undefined; /** * Get the plugin's state from an editor state. */ @@ -440,7 +440,7 @@ export class EditorState { /** * The plugins that are active in this state. */ - plugins: Array>; + plugins: Array>; /** * Apply the given transaction to produce a new state. */ @@ -465,13 +465,13 @@ export class EditorState { * [`init`](#state.StateField.init) method, passing in the new * configuration object.. */ - reconfigure(config: { schema?: S | null; plugins?: Array> | null }): EditorState; + reconfigure(config: { schema?: S | null; plugins?: Array> | null }): EditorState; /** * Serialize this state to JSON. If you want to serialize the state * of plugins, pass an object mapping property names to use in the * resulting JSON object to plugin objects. */ - toJSON(pluginFields?: { [name: string]: Plugin } | string | number): { [key: string]: any }; + toJSON(pluginFields?: { [name: string]: Plugin } | string | number): { [key: string]: any }; /** * Create a new state. */ @@ -480,7 +480,7 @@ export class EditorState { doc?: ProsemirrorNode | null; selection?: Selection | null; storedMarks?: Mark[] | null; - plugins?: Array> | null; + plugins?: Array> | null; }): EditorState; /** * Deserialize a JSON representation of a state. `config` should @@ -490,9 +490,9 @@ export class EditorState { * instances with the property names they use in the JSON object. */ static fromJSON( - config: { schema: S; plugins?: Array> | null }, + config: { schema: S; plugins?: Array> | null }, json: { [key: string]: any }, - pluginFields?: { [name: string]: Plugin } + pluginFields?: { [name: string]: Plugin } ): EditorState; } /** @@ -589,11 +589,11 @@ export class Transaction extends Transform { * Store a metadata property in this transaction, keyed either by * name or by plugin. */ - setMeta(key: string | Plugin | PluginKey, value: any): Transaction; + setMeta(key: string | Plugin | PluginKey, value: any): Transaction; /** * Retrieve a metadata property for a given name or plugin. */ - getMeta(key: string | Plugin | PluginKey): any; + getMeta(key: string | Plugin | PluginKey): any; /** * Returns true if this transaction doesn't contain any metadata, * and can thus safely be extended. diff --git a/types/prosemirror-view/index.d.ts b/types/prosemirror-view/index.d.ts index a539be4593..da83390c40 100644 --- a/types/prosemirror-view/index.d.ts +++ b/types/prosemirror-view/index.d.ts @@ -79,6 +79,7 @@ export class Decoration { pos: number, toDOM: ((view: EditorView, getPos: () => number) => Node) | Node, spec?: { + [key: string]: any; side?: number | null; marks?: Mark[] | null; stopEvent?: ((event: Event) => boolean) | null; diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 2c21363b1a..e1b1f21334 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -473,8 +473,8 @@ declare namespace R { * Applies a function to the value at the given index of an array, returning a new copy of the array with the * element at the given index replaced with the result of the function application. */ - adjust(fn: (a: T) => T, index: number, list: ReadonlyArray): T[]; - adjust(fn: (a: T) => T, index: number): (list: ReadonlyArray) => T[]; + adjust(index: number, fn: (a: T) => T, list: ReadonlyArray): T[]; + adjust(index: number, fn: (a: T) => T): (list: ReadonlyArray) => T[]; /** * Returns true if all elements of the list match the predicate, false if there are any that don't. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 6a03cbc3f0..9db133c971 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -299,7 +299,7 @@ class F2 { const capitalize = (str: string) => R.pipe( R.split(""), - R.adjust(R.toUpper, 0), + R.adjust(0, R.toUpper), R.join("") )(str); diff --git a/types/raygun/index.d.ts b/types/raygun/index.d.ts index 9315161a33..b2da46c446 100644 --- a/types/raygun/index.d.ts +++ b/types/raygun/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -declare namespace raygun { +export namespace raygun { interface KeyValueObject { [key: string]: string | number | boolean | KeyValueObject; } @@ -143,4 +143,4 @@ declare class Client { ): void; } -export = Client; +export { Client }; diff --git a/types/raygun/raygun-tests.ts b/types/raygun/raygun-tests.ts index 76328b01c5..abef1e9021 100644 --- a/types/raygun/raygun-tests.ts +++ b/types/raygun/raygun-tests.ts @@ -1,6 +1,6 @@ -import Client = require('raygun'); +import raygun = require('raygun'); -const client = new Client(); // $ExpectType Client +const client = new raygun.Client(); // $ExpectType Client client.init({apiKey: '1'}); // $ExpectType Client client.init(); // $ExpectError diff --git a/types/rc-time-picker/package.json b/types/rc-time-picker/package.json new file mode 100644 index 0000000000..f06689a6b9 --- /dev/null +++ b/types/rc-time-picker/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "moment": "^2.19.4" + } +} diff --git a/types/react-avatar-editor/index.d.ts b/types/react-avatar-editor/index.d.ts index 3d4135120c..00603c898e 100644 --- a/types/react-avatar-editor/index.d.ts +++ b/types/react-avatar-editor/index.d.ts @@ -3,26 +3,26 @@ // Definitions by: Diogo Corrêa // Gabriel Prates // Laurent Senta +// David Spiess // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from "react"; -export interface ImageState { - height: number; - width: number; +export interface Position { x: number; y: number; - resource: ImageData; } -export interface CroppedRect { - x: number; - y: number; +export interface CroppedRect extends Position { width: number; height: number; } +export interface ImageState extends CroppedRect { + resource: ImageData; +} + export interface AvatarEditorProps { className?: string; image: string | File; @@ -33,7 +33,7 @@ export interface AvatarEditorProps { color?: number[]; style?: object; scale?: number; - position?: object; + position?: Position; rotate?: number; crossOrigin?: string; disableDrop?: boolean; @@ -44,7 +44,7 @@ export interface AvatarEditorProps { onMouseUp?(): void; onMouseMove?(event: Event): void; onImageChange?(): void; - onPositionChange?(): void; + onPositionChange?(position: Position): void; } export default class AvatarEditor extends React.Component { diff --git a/types/react-avatar-editor/react-avatar-editor-tests.tsx b/types/react-avatar-editor/react-avatar-editor-tests.tsx index bee4ff6a56..5942f55a7e 100644 --- a/types/react-avatar-editor/react-avatar-editor-tests.tsx +++ b/types/react-avatar-editor/react-avatar-editor-tests.tsx @@ -1,8 +1,16 @@ import * as React from "react"; -import AvatarEditor, { ImageState, CroppedRect } from "react-avatar-editor"; +import AvatarEditor, { + ImageState, + CroppedRect, + Position +} from "react-avatar-editor"; const file: File = new File(["str"], "image.jpg"); const image: ImageData = new ImageData(1, 2); +const position: Position = { + x: 1, + y: 1 +}; const imageState: ImageState = { height: 1, width: 1, @@ -34,7 +42,7 @@ class AvatarEditorTest extends React.Component { - + @@ -45,7 +53,7 @@ class AvatarEditorTest extends React.Component { {}} /> {}} /> {}} /> - {}} /> + {}} /> { diff --git a/types/react-big-calendar/lib/addons/dragAndDrop.d.ts b/types/react-big-calendar/lib/addons/dragAndDrop.d.ts new file mode 100644 index 0000000000..a1b7d01dad --- /dev/null +++ b/types/react-big-calendar/lib/addons/dragAndDrop.d.ts @@ -0,0 +1,14 @@ +import BigCalendar, { BigCalendarProps, Event, stringOrDate } from '../../index'; +import * as React from 'react'; + +interface withDragAndDropProps { + onEventDrop?: (args: { event: TEvent, start: stringOrDate, end: stringOrDate, allDay: boolean }) => void; + onEventResize?: (args: { event: TEvent, start: stringOrDate, end: stringOrDate, allDay: boolean }) => void; + resizable?: boolean; +} + +declare class DragAndDropCalendar + extends React.Component & withDragAndDropProps> {} + +declare function withDragAndDrop(calendar: typeof BigCalendar): typeof DragAndDropCalendar; +export default withDragAndDrop; diff --git a/types/react-big-calendar/react-big-calendar-tests.tsx b/types/react-big-calendar/react-big-calendar-tests.tsx index 4bb6f23943..6b7c252f97 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -1,6 +1,7 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; import BigCalendar, { BigCalendarProps, Navigate, View, DateRange, DateLocalizer, ToolbarProps, EventWrapperProps } from "react-big-calendar"; +import withDragAndDrop from "react-big-calendar/lib/addons/dragAndDrop"; // Don't want to add this as a dependency, because it is only used for tests. declare const globalize: any; @@ -60,6 +61,30 @@ class CalendarResource { ReactDOM.render(, document.body); } +// Drag and Drop Example Test +{ + interface Props { + localizer: DateLocalizer; + } + const DragAndDropCalendar = withDragAndDrop(BigCalendar); + const DnD = ({ localizer }: Props) => ( + + ); + + const localizer = BigCalendar.momentLocalizer(moment); + + ReactDOM.render(, document.body); +} + { class MyCalendar extends BigCalendar {} @@ -203,7 +228,7 @@ function Event(event: any) { class EventWrapper extends React.Component { render() { - const { continuesEarlier, label, accessors = {}, style } = this.props; + const { continuesEarlier, event, label, accessors = {}, style } = this.props; return (

    {continuesEarlier}-{label}-{accessors.title && event && accessors.title(event)}}
    diff --git a/types/react-big-calendar/tsconfig.json b/types/react-big-calendar/tsconfig.json index eddf55cc13..8722501ef7 100644 --- a/types/react-big-calendar/tsconfig.json +++ b/types/react-big-calendar/tsconfig.json @@ -20,6 +20,7 @@ }, "files": [ "index.d.ts", - "react-big-calendar-tests.tsx" + "react-big-calendar-tests.tsx", + "lib/addons/dragAndDrop.d.ts" ] -} \ No newline at end of file +} diff --git a/types/react-click-outside/index.d.ts b/types/react-click-outside/index.d.ts index c09dccb155..3684c87484 100644 --- a/types/react-click-outside/index.d.ts +++ b/types/react-click-outside/index.d.ts @@ -1,11 +1,12 @@ // Type definitions for react-click-outside 3.0 // Project: https://github.com/kentor/react-click-outside // Definitions by: Christian Rackerseder +// Roman Nuritdinov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from "react"; -declare function enhanceWithClickOutside

    (wrappedComponent: React.ComponentClass

    ): React.ComponentClass

    ; +declare function enhanceWithClickOutside>(wrappedComponent: C): C; declare namespace enhanceWithClickOutside { } export = enhanceWithClickOutside; diff --git a/types/react-click-outside/react-click-outside-tests.tsx b/types/react-click-outside/react-click-outside-tests.tsx index d51516281e..fe8e7af110 100644 --- a/types/react-click-outside/react-click-outside-tests.tsx +++ b/types/react-click-outside/react-click-outside-tests.tsx @@ -22,6 +22,20 @@ class StatefulComponent extends React.Component { } } +@enhanceWithClickOutside +class ComponentWithDecorator extends React.Component { + state = { isOpened: true }; + + handleClickOutside() { + this.setState({ isOpened: false }); + } + + render() { + return

    {this.props.text}
    ; + } +} + const ClickOutsideStatefulComponent = enhanceWithClickOutside(StatefulComponent); render(, document.getElementById('test')); +render(, document.getElementById('test')); diff --git a/types/react-click-outside/tsconfig.json b/types/react-click-outside/tsconfig.json index caf91fdc1d..68d52cdab4 100644 --- a/types/react-click-outside/tsconfig.json +++ b/types/react-click-outside/tsconfig.json @@ -16,10 +16,11 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "experimentalDecorators": true }, "files": [ "index.d.ts", "react-click-outside-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/react-image-crop/index.d.ts b/types/react-image-crop/index.d.ts index 9cb750dbd2..877966b00e 100644 --- a/types/react-image-crop/index.d.ts +++ b/types/react-image-crop/index.d.ts @@ -51,7 +51,7 @@ declare namespace ReactCrop { function getPixelCrop(image: HTMLImageElement, percentCrop: Crop): Crop; function makeAspectCrop(crop: Crop, imageAspect: number): Crop; - function containCrop(crop: Crop, imageAspect: number): Crop; + function containCrop(previousCrop: Crop, crop: Crop, imageAspect: number): Crop; } declare class ReactCrop extends Component { diff --git a/types/react-instantsearch-core/index.d.ts b/types/react-instantsearch-core/index.d.ts index bceb91ca85..0092feb370 100644 --- a/types/react-instantsearch-core/index.d.ts +++ b/types/react-instantsearch-core/index.d.ts @@ -3,10 +3,13 @@ // Definitions by: Gordon Burgett // Justin Powell // David Furlong +// Haroen Viaene +// Samuel Vaillant // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 import * as React from 'react'; +import { SearchParameters } from 'algoliasearch-helper'; // Core /** @@ -29,7 +32,15 @@ export function createInstantSearch( */ export function createIndex(defaultRoot: object): React.ComponentClass; -export interface ConnectorDescription { +export interface ConnectorSearchResults { + results: AllSearchResults; + searching: boolean; + searchingForFacetValues: boolean; + isSearchStalled: boolean; + error: any; +} + +export interface ConnectorDescription { displayName: string; propTypes?: any; defaultProps?: any; @@ -43,14 +54,26 @@ export interface ConnectorDescription { * meta is the list of metadata from all widgets whose connector defines a getMetadata method. * searchForFacetValuesResults holds the search for facet values results. */ - getProvidedProps?(...args: any[]): any; + getProvidedProps( + this: React.Component, + props: TExposed, + searchState: SearchState, + searchResults: ConnectorSearchResults, + metadata: any, + resultsFacetValues: any, + ): TProvided; /** * This method defines exactly how the refine prop of widgets affects the search state. * It takes in the current props of the higher-order component, the search state of all widgets, as well as all arguments passed * to the refine and createURL props of stateful widgets, and returns a new state. */ - refine?(...args: any[]): any; + refine?( + this: React.Component, + props: TExposed, + searchState: SearchState, + ...args: any[], + ): SearchState; /** * This method applies the current props and state to the provided SearchParameters, and returns a new SearchParameters. The SearchParameters @@ -59,7 +82,12 @@ export interface ConnectorDescription { * to produce a new SearchParameters. Then, if the output SearchParameters differs from the previous one, a new search is triggered. * As such, the getSearchParameters method allows you to describe how the state and props of a widget should affect the search parameters. */ - getSearchParameters?(...args: any[]): any; + getSearchParameters?( + this: React.Component, + searchParameters: SearchParameters, + props: TExposed, + searchState: SearchState, + ): SearchParameters; /** * This method allows the widget to register a custom metadata object for any props and state combination. @@ -70,7 +98,11 @@ export interface ConnectorDescription { * The CurrentRefinements widget leverages this mechanism in order to allow any widget to declare the filters it has applied. If you want to add * your own filter, declare a filters property on your widget’s metadata */ - getMetadata?(...args: any[]): any; + getMetadata?( + this: React.Component, + props: TExposed, + searchState: SearchState, + ...args: any[]): any; /** * This method needs to be implemented if you want to have the ability to perform a search for facet values inside your widget. @@ -78,7 +110,11 @@ export interface ConnectorDescription { * props of stateful widgets, and returns an object of the shape: {facetName: string, query: string, maxFacetHits?: number}. The default value for the * maxFacetHits is the one set by the API which is 10. */ - searchForFacetValues?(...args: any[]): any; + searchForFacetValues?( + this: React.Component, + searchState: SearchState, + nextRefinement?: any, + ): any; /** * This method is called when a widget is about to unmount in order to clean the searchState. @@ -87,9 +123,13 @@ export interface ConnectorDescription { * searchState holds the searchState of all widgets, with the shape {[widgetId]: widgetState}. Stateful widgets describe the format of their searchState * in their respective documentation entry. */ - cleanUp?(...args: any[]): any; + cleanUp?(this: React.Component, props: TExposed, searchState: SearchState): SearchState; } +export type ConnectorProvided = TProvided & + { refine: (...args: any[]) => any, createURL: (...args: any[]) => string } & + { searchForItems: (...args: any[]) => any }; + /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. @@ -100,7 +140,14 @@ export interface ConnectorDescription { * @return a function that wraps a component into * an instantsearch connected one. */ -export function createConnector(connectorDesc: ConnectorDescription): (Composed: React.ComponentType) => React.ComponentClass; +export function createConnector( + connectorDesc: ConnectorDescription, +): ( + (stateless: React.StatelessComponent>) => React.ComponentClass + ) & ( + >>(Composed: React.ComponentType) => + ConnectedComponentClass, TExposed> + ); // Utils export const HIGHLIGHT_TAGS: { @@ -108,7 +155,17 @@ export const HIGHLIGHT_TAGS: { highlightPostTag: string, }; export const version: string; -export function translatable(defaultTranslations: any): (Composed: React.ComponentType) => React.ComponentClass; + +export interface TranslatableProvided { + translate(key: string, ...params: any[]): string; +} +export interface TranslatableExposed { + translations?: { [key: string]: string | ((...args: any[]) => string) }; +} + +export function translatable(defaultTranslations: { [key: string]: string | ((...args: any[]) => string) }): + (ctor: React.ComponentType) => + ConnectedComponentClass; // Widgets /** @@ -125,7 +182,21 @@ export function translatable(defaultTranslations: any): (Composed: React.Compone export class Configure extends React.Component {} // Connectors -export function connectAutoComplete(Composed: React.ComponentType): React.ComponentClass; +export interface AutocompleteProvided { + hits: Array>; + currentRefinement: string; + refine(value?: string): void; +} + +export interface AutocompleteExposed { + defaultRefinement?: string; +} + +// tslint:disable-next-line:no-unnecessary-generics +export function connectAutoComplete(stateless: React.StatelessComponent>): React.ComponentClass; +export function connectAutoComplete, TDoc = BasicDoc>(Composed: React.ComponentType): + ConnectedComponentClass, AutocompleteExposed>; + export function connectBreadcrumb(Composed: React.ComponentType): React.ComponentClass; export function connectConfigure(Composed: React.ComponentType): React.ComponentClass; @@ -208,7 +279,51 @@ export function connectGeoSearch(stateless: React.StatelessComponent>, THit>(ctor: React.ComponentType): ConnectedComponentClass, GeoSearchExposed>; export function connectHierarchicalMenu(Composed: React.ComponentType): React.ComponentClass; -export function connectHighlight(Composed: React.ComponentType): React.ComponentClass; + +export interface HighlightProvided { + /** + * function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attributes: + * * highlightProperty which is the property that contains the highlight structure from the records, + * * attribute which is the name of the attribute (it can be either a string or an array of strings) to look for, + * * hit which is the hit from Algolia. + * It returns an array of objects {value: string, isHighlighted: boolean}. + * If the element that corresponds to the attribute is an array of strings, it will return a nested array of objects. + * In this case you should cast the result: + * ```ts + * highlight({ + * attribute: 'my_string_array', + * hit, + * highlightProperty: '_highlightResult' + * }) as Array> + * ``` + */ + highlight(configuration: { + attribute: string; + hit: Hit; + highlightProperty: string; + preTag?: string; + postTag?: string; + }): Array<{value: string, isHighlighted: boolean}>; +} + +interface HighlightPassedThru { + hit: Hit; + attribute: string; + highlightProperty?: string; +} + +export type HighlightProps = HighlightProvided & HighlightPassedThru; + +/** + * connectHighlight connector provides the logic to create an highlighter component that will retrieve, parse and render an highlighted attribute from an Algolia hit. + */ +export function connectHighlight(stateless: React.StatelessComponent>): React.ComponentClass>; +export function connectHighlight>, TDoc>(ctor: React.ComponentType): ConnectedComponentClass>; + +interface HitsProvided { + /** the records that matched the search state */ + hits: Array>; +} /** * connectHits connector provides the logic to create connected components that will render the results retrieved from Algolia. @@ -217,7 +332,9 @@ export function connectHighlight(Composed: React.ComponentType): React.Comp * * https://community.algolia.com/react-instantsearch/connectors/connectHits.html */ -export function connectHits(ctor: React.ComponentType): ConnectedComponentClass; +// tslint:disable-next-line:no-unnecessary-generics +export function connectHits(stateless: React.StatelessComponent>): React.ComponentClass; +export function connectHits, THit>(ctor: React.ComponentType): ConnectedComponentClass>; export function connectHitsPerPage(Composed: React.ComponentType): React.ComponentClass; @@ -386,7 +503,7 @@ export interface StateResultsProvided { */ searchResults: SearchResults; /** In case of multiple indices you can retrieve all the results */ - allSearchResults: { [index: string]: SearchResults }; + allSearchResults: AllSearchResults; /** If there is a search in progress. */ searching: boolean; /** Flag that indicates if React InstantSearch has detected that searches are stalled. */ @@ -402,10 +519,20 @@ export interface StateResultsProvided { * * https://community.algolia.com/react-instantsearch/connectors/connectStateResults.html */ -export function connectStateResults(stateless: React.StatelessComponent): React.ComponentClass; -export function connectStateResults>, TDoc>(ctor: React.ComponentType): ConnectedComponentClass>; +export function connectStateResults( + stateless: React.StatelessComponent): React.ComponentClass; +export function connectStateResults>>( + ctor: React.ComponentType): ConnectedComponentClass; + +interface StatsProvided { + nbHits: number; + processingTimeMS: number; +} + +export function connectStats(stateless: React.StatelessComponent): React.ComponentClass; +export function connectStats>(ctor: React.ComponentType): + ConnectedComponentClass; -export function connectStats(Composed: React.ComponentType): React.ComponentClass; export function connectToggleRefinement(Composed: React.ComponentType): React.ComponentClass; export interface AlgoliaError { @@ -428,6 +555,8 @@ export type ConnectedComponentClass * https://community.algolia.com/react-instantsearch/guide/Search_state.html */ export interface SearchState { + [widgetId: string]: any; + range?: { [key: string]: { min: number; @@ -487,7 +616,7 @@ export interface SearchResults { nbPages: number; page: number; processingTimeMS: number; - exhaustiveNbHits: true; + exhaustiveNbHits: boolean; disjunctiveFacets: any[]; hierarchicalFacets: any[]; facets: any[]; @@ -495,6 +624,14 @@ export interface SearchResults { automaticRadius?: string; } +/** + * The shape of the searchResults object when used in a multi-index search + * https://community.algolia.com/react-instantsearch/connectors/connectStateResults.html#default-props-entry-connectStateResults-searchResults + */ +export type AllSearchResults = { + [index: string]: SearchResults; +} & SearchResults; + /** * All the records that match the search parameters. * Each record is augmented with a new attribute `_highlightResult` which is an diff --git a/types/react-instantsearch-core/react-instantsearch-core-tests.tsx b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx index e39a9f53e6..76cc26f2a4 100644 --- a/types/react-instantsearch-core/react-instantsearch-core-tests.tsx +++ b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx @@ -11,7 +11,21 @@ import { CurrentRefinementsProvided, connectCurrentRefinements, RefinementListProvided, - Refinement + Refinement, + connectHighlight, + connectHits, + HighlightProvided, + HighlightProps, + AutocompleteProvided, + connectAutoComplete, + Hit, + TranslatableProvided, + translatable, + ConnectorProvided, + StateResultsProvided, + ConnectorSearchResults, + BasicDoc, + AllSearchResults } from 'react-instantsearch-core'; () => { @@ -58,9 +72,12 @@ import { queryAndPage: [newQuery, newPage], }; }, - })(props => + })((props) =>
    The query is {props.query}, the page is {props.page}. + This is an error: { + props.somethingElse // $ExpectError + } {/* Clicking on this button will update the searchState to: { @@ -88,18 +105,143 @@ import { }; () => { + interface Provided { + query: string; + page: number; + } + + interface Exposed { + defaultRefinement: string; + startAtPage: number; + } + + const typedCoolConnector = createConnector({ + displayName: 'CoolWidget', + + getProvidedProps(props, searchState) { + // Since the `queryAndPage` searchState entry isn't necessarily defined, we need + // to default its value. + const [query, page] = searchState.queryAndPage || + [props.defaultRefinement, props.startAtPage]; + + // Connect the underlying component to the `queryAndPage` searchState entry. + return { + query, + page, + }; + }, + + refine(props, searchState, newQuery, newPage) { + // When the underlying component calls its `refine` prop, update the searchState + // with the new query and page. + return { + // `searchState` represents the search state of *all* widgets. We need to extend it + // instead of replacing it, otherwise other widgets will lose their + // respective state. + ...searchState, + queryAndPage: [newQuery, newPage], + }; + }, + }); + + const TypedCoolWidgetStateless = typedCoolConnector((props) => +
    + The query is {props.query}, the page is {props.page}. + This is an error: { + props.somethingElse // $ExpectError + } + {/* + Clicking on this button will update the searchState to: + { + ...otherSearchState, + query: 'algolia', + page: 20, + } + */} +
    + ); + + ; + + const TypedCoolWidget = typedCoolConnector( + class extends React.Component & { passThruName: string }> { + render() { + const props = this.props; + return
    + The query is {props.query}, the page is {props.page}. + The name is {props.passThruName} + {/* + Clicking on this button will update the searchState to: + { + ...otherSearchState, + query: 'algolia', + page: 20, + } + */} +
    ; + } + } + ); + + ; +}; + +() => { + interface MyDoc { + field1: string; + field2: number; + field3: { compound: string }; + } + interface StateResultsProps { - searchResults: SearchResults<{ - field1: string - field2: number - field3: { compound: string } - }>; + searchResults: SearchResults; // partial of StateResultsProvided additionalProp: string; } - const Stateless = ({ additionalProp, searchResults }: StateResultsProps) => + const Stateless = connectStateResults( + ({ + searchResults, + additionalProp, // $ExpectError + }) => (
    +

    {additionalProp}

    + {searchResults.hits.map((h) => { + return {h._highlightResult.field1!.value}; + })} +
    ) + ); + + ; + ; // $ExpectError + + const StatelessWithType = ({ additionalProp, searchResults }: StateResultsProps) =>

    {additionalProp}

    {searchResults.hits.map((h) => { @@ -108,11 +250,11 @@ import { return {compound}; })}
    ; - const ComposedStateless = connectStateResults(Stateless); + const ComposedStatelessWithType = connectStateResults(StatelessWithType); - ; // $ExpectError + ; // $ExpectError - ; + ; class MyComponent extends React.Component { render() { @@ -219,3 +361,348 @@ import { ; }; + +() => { + interface MyDoc { + a: 1; + b: { + c: '2' + }; + } + + const CustomHighlight = connectHighlight( + ({ highlight, attribute, hit }) => { + const highlights = highlight({ + highlightProperty: '_highlightResult', + attribute, + hit + }); + + return <> + {highlights.map(part => part.isHighlighted ? ( + {part.value} + ) : ( + {part.value} + )) + }; + } + ); + + class CustomHighlight2 extends React.Component { + render() { + const {highlight, attribute, hit, limit} = this.props; + const highlights = highlight({ + highlightProperty: '_highlightResult', + attribute, + hit + }); + + return <> + {highlights.slice(0, limit).map(part => part.isHighlighted ? ( + {part.value} + ) : ( + {part.value} + )) + }; + } + } + const ConnectedCustomHighlight2 = connectHighlight(CustomHighlight2); + + connectHits(({ hits }) => ( +

    + + +

    + )); +}; + +// https://github.com/algolia/react-instantsearch/blob/master/examples/autocomplete/src/App-Mentions.js +() => { + const Mention: any = null; // import Mention from 'antd/lib/mention'; + + const AsyncMention = ({ hits, refine }: AutocompleteProvided) => ( + hit.name)} + onSearchChange={refine} + /> + ); + + const ConnectedAsyncMention = connectAutoComplete(AsyncMention); + + ; +}; + +// https://github.com/algolia/react-instantsearch/blob/master/examples/autocomplete/src/App-Multi-Index.js +import * as Autosuggest from 'react-autosuggest'; +() => { + class Example extends React.Component { + state = { + value: this.props.currentRefinement, + }; + + onChange = (_event: any, { newValue }: { newValue: string }) => { + this.setState({ + value: newValue, + }); + } + + onSuggestionsFetchRequested = ({ value }: { value: string }) => { + this.props.refine(value); + } + + onSuggestionsClearRequested = () => { + this.props.refine(); + } + + getSuggestionValue(hit: Hit) { + return hit.name; + } + + renderSuggestion(hit: Hit) { + const Highlight: any = null; // import {Highlight} from 'react-instantsearch-dom' + return ; + } + + renderSectionTitle(section: any) { + return section.index; + } + + getSectionSuggestions(section: any) { + return section.hits; + } + + render() { + const { hits } = this.props; + const { value } = this.state; + + const inputProps = { + placeholder: 'Search for a product...', + onChange: this.onChange, + value, + }; + + return ( + + ); + } + } + + const AutoComplete = connectAutoComplete(Example); + + ; +}; + +() => { + type Props = SearchBoxProvided & TranslatableProvided & { + className?: string + showLoadingIndicator?: boolean + + submit?: JSX.Element; + reset?: JSX.Element; + loadingIndicator?: JSX.Element; + + onSubmit?: (event: React.SyntheticEvent) => any; + onReset?: (event: React.SyntheticEvent) => any; + onChange?: (event: React.SyntheticEvent) => any; + }; + interface State { + query: string | null; + } + + class SearchBox extends React.Component { + static defaultProps = { + currentRefinement: '', + className: 'ais-SearchBox', + focusShortcuts: ['s', '/'], + autoFocus: false, + searchAsYouType: true, + showLoadingIndicator: false, + isSearchStalled: false, + reset: clear, + submit: search, + }; + + constructor(props: SearchBox['props']) { + super(props); + + this.state = { + query: null, + }; + } + + getQuery = () => this.props.currentRefinement; + + onSubmit = (e: React.SyntheticEvent) => { + e.preventDefault(); + e.stopPropagation(); + + const { refine, onSubmit } = this.props; + + if (onSubmit) { + onSubmit(e); + } + return false; + } + + onChange = (event: React.ChangeEvent) => { + const { onChange } = this.props; + const value = event.target.value; + + this.setState({ query: value }); + + if (onChange) { + onChange(event); + } + } + + onReset = (event: React.FormEvent) => { + const { refine, onReset } = this.props; + + refine(''); + + this.setState({ query: '' }); + + if (onReset) { + onReset(event); + } + } + + render() { + const { + className, + translate, + loadingIndicator, + submit, + reset, + } = this.props; + const query = this.getQuery(); + + const isSearchStalled = + this.props.showLoadingIndicator && this.props.isSearchStalled; + + const isCurrentQuerySubmitted = + query && query === this.props.currentRefinement; + + const button = + isSearchStalled ? 'loading' : + isCurrentQuerySubmitted ? 'reset' : 'submit'; + + return ( +
    +
    + + + + +
    +
    + ); + } + } + + const TranslatableSearchBox = translatable({ + resetTitle: 'Clear the search query.', + submitTitle: 'Submit your search query.', + placeholder: 'Search here…', + })(SearchBox); + + const ConnectedSearchBox = connectSearchBox(TranslatableSearchBox); + + search} + onSubmit={(evt) => { console.log('submitted', evt); }} + />; +}; + +// can we recreate connectStateResults from source using the createConnector typedef? +() => { + function getIndexId(context: any): string { + return context && context.multiIndexContext + ? context.multiIndexContext.targetedIndex + : context.ais.mainTargetedIndex; + } + + function getResults(searchResults: { results: AllSearchResults }, context: any): SearchResults | null | undefined { + const {results} = searchResults; + if (results && !results.hits) { + return results[getIndexId(context)] + ? results[getIndexId(context)] + : null; + } else { + return results ? results : null; + } + } + + const csr = createConnector({ + displayName: 'AlgoliaStateResults', + + getProvidedProps(props, searchState, searchResults) { + const results = getResults(searchResults, this.context); + + return { + searchState, + searchResults: results, + allSearchResults: searchResults.results, + searching: searchResults.searching, + isSearchStalled: searchResults.isSearchStalled, + error: searchResults.error, + searchingForFacetValues: searchResults.searchingForFacetValues, + props, + }; + }, + }); + + const asConnectStateResults: typeof connectStateResults = csr; +}; diff --git a/types/react-instantsearch-dom/index.d.ts b/types/react-instantsearch-dom/index.d.ts index 6ecb03c981..6f270485b3 100644 --- a/types/react-instantsearch-dom/index.d.ts +++ b/types/react-instantsearch-dom/index.d.ts @@ -2,6 +2,8 @@ // Project: https://community.algolia.com/react-instantsearch/ // Definitions by: Gordon Burgett // Justin Powell +// Haroen Viaene +// Samuel Vaillant // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 diff --git a/types/react-instantsearch-native/index.d.ts b/types/react-instantsearch-native/index.d.ts index 6b328de132..74933ebabf 100644 --- a/types/react-instantsearch-native/index.d.ts +++ b/types/react-instantsearch-native/index.d.ts @@ -2,6 +2,8 @@ // Project: https://community.algolia.com/react-instantsearch // Definitions by: Gordon Burgett // Justin Powell +// Haroen Viaene +// Samuel Vaillant // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 diff --git a/types/react-instantsearch/index.d.ts b/types/react-instantsearch/index.d.ts index 3f80cf4aa3..64a415e6ba 100644 --- a/types/react-instantsearch/index.d.ts +++ b/types/react-instantsearch/index.d.ts @@ -2,6 +2,8 @@ // Project: https://community.algolia.com/react-instantsearch/ // Definitions by: Gordon Burgett // Justin Powell +// Haroen Viaene +// Samuel Vaillant // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 diff --git a/types/react-jss/index.d.ts b/types/react-jss/index.d.ts index c2ee0a008a..b7dafa5982 100644 --- a/types/react-jss/index.d.ts +++ b/types/react-jss/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Sebastian Silbermann // James Lawrence // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 2.9 import { createGenerateClassName, JSS, SheetsRegistry } from "jss"; import * as React from "react"; import { createTheming, ThemeProvider, withTheme } from "theming"; diff --git a/types/react-jss/lib/injectSheet.d.ts b/types/react-jss/lib/injectSheet.d.ts index d165ee7e6d..eb35117017 100644 --- a/types/react-jss/lib/injectSheet.d.ts +++ b/types/react-jss/lib/injectSheet.d.ts @@ -73,11 +73,11 @@ export interface CSSProperties { | DynamicCSSRule | CSSProperties; } -export type Styles = Record< +export type Styles = Record< ClassKey, CSSProperties >; -export type StyleCreator = ( +export type StyleCreator = ( theme: T ) => Styles; @@ -93,20 +93,20 @@ export interface InjectOptions extends CreateStyleSheetOptions { theming?: Theming; } -export type ClassNameMap = Record; +export type ClassNameMap = Record; export type WithSheet< - S extends string | Styles | StyleCreator, + S extends string | Styles | StyleCreator, GivenTheme = undefined, - Props = {} +Props = {}, > = { classes: ClassNameMap< - S extends string + S extends string | number | symbol ? S : S extends StyleCreator ? C : S extends Styles ? C : never >; -} & WithTheme ? T : GivenTheme>; +} & WithTheme ? T : GivenTheme>; export interface WithTheme { theme: T; diff --git a/types/react-measure/index.d.ts b/types/react-measure/index.d.ts index 9cd5853948..3236dc2a4c 100644 --- a/types/react-measure/index.d.ts +++ b/types/react-measure/index.d.ts @@ -57,7 +57,7 @@ export interface MeasureProps { children?: React.SFC; } -export declare function withContentRect(types: ReadonlyArray | MeasurementType): +export function withContentRect(types: ReadonlyArray | MeasurementType): (fn: MeasuredComponent) => React.ComponentType; declare class Measure extends React.Component {} diff --git a/types/react-native-fetch-blob/index.d.ts b/types/react-native-fetch-blob/index.d.ts index 910fa4dba9..38b59bee28 100644 --- a/types/react-native-fetch-blob/index.d.ts +++ b/types/react-native-fetch-blob/index.d.ts @@ -33,11 +33,11 @@ export interface Polyfill { Fetch: PolyfillFetch; } -export declare class PolyfillFetch extends RNFetchBlobFetchPolyfill { +export class PolyfillFetch extends RNFetchBlobFetchPolyfill { constructor(config: RNFetchBlobConfig); } -export declare class RNFetchBlobFetchPolyfill { +export class RNFetchBlobFetchPolyfill { constructor(config: RNFetchBlobConfig); build(): (url: string, options: RNFetchBlobConfig) => StatefulPromise; @@ -129,13 +129,13 @@ export interface PolyfillFileReader extends EventTarget { result: number; } -export declare namespace PolyfillFileReader { +export namespace PolyfillFileReader { const EMPTY: number; const LOADING: number; const DONE: number; } -export declare class PolyfillEvent { +export class PolyfillEvent { } export interface PolyfillProgressEvent extends EventTarget { @@ -144,7 +144,7 @@ export interface PolyfillProgressEvent extends EventTarget { total: number; } -export declare class PolyfillBlob extends EventTarget { +export class PolyfillBlob extends EventTarget { /** * RNFetchBlob Blob polyfill, create a Blob directly from file path, BASE64 * encoded data, and string. The conversion is done implicitly according to @@ -194,7 +194,7 @@ export declare class PolyfillBlob extends EventTarget { close(): Promise; } -export declare namespace PolyfillBlob { +export namespace PolyfillBlob { function clearCache(): void; function build(data: any, cType: any): Promise; @@ -202,7 +202,7 @@ export declare namespace PolyfillBlob { function setLog(level: number): void; } -export declare class PolyfillFile extends PolyfillBlob { +export class PolyfillFile extends PolyfillBlob { } export interface PolyfillXMLHttpRequest extends PolyfillXMLHttpRequestEventTarget { @@ -252,7 +252,7 @@ export interface PolyfillXMLHttpRequest extends PolyfillXMLHttpRequestEventTarge responseType: string; } -export declare namespace PolyfillXMLHttpRequest { +export namespace PolyfillXMLHttpRequest { const binaryContentTypes: string[]; const UNSENT: number; const OPENED: number; @@ -490,7 +490,7 @@ export interface StatefulPromise extends Promise { expire(callback: () => void): StatefulPromise; } -export declare class RNFetchBlobSession { +export class RNFetchBlobSession { constructor(name: string, list: string[]); add(path: string): RNFetchBlobSession; @@ -609,10 +609,10 @@ export interface RNFetchBlobStream { onEnd(): void; } -export declare class RNFetchBlobFile { +export class RNFetchBlobFile { } -export declare class RNFetchBlobStat { +export class RNFetchBlobStat { lastModified: string; size: string; type: "directory" | "file"; diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 0cee14dfd2..a96ffd41eb 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -9297,7 +9297,9 @@ export const PointPropType: React.Validator; export const ViewPropTypes: React.ValidationMap; declare global { - function require(name: string): any; + type ReactNativeRequireFunction = (name: string) => any; + + var require: ReactNativeRequireFunction; /** * Console polyfill @@ -9315,7 +9317,7 @@ declare global { ignoredYellowBox: string[]; } - const console: Console; + var console: Console; /** * Navigator object for accessing location API diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 860d54523e..f2b0b968fb 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -32,6 +32,7 @@ // Deniss Borisovs // Kenneth Skovhus // Aaron Rosen +// Haseeb Majid // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -922,6 +923,7 @@ export interface DrawerItemsProps { inactiveLabelStyle?: StyleProp; iconContainerStyle?: StyleProp; drawerPosition: 'left' | 'right'; + screenProps?: any; } export interface DrawerScene { route: NavigationRoute; diff --git a/types/react-resizable/index.d.ts b/types/react-resizable/index.d.ts new file mode 100644 index 0000000000..5684c1f55d --- /dev/null +++ b/types/react-resizable/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for react-resizable 1.7 +// Project: https://github.com/STRML/react-resizable +// Definitions by: Harry Brrundage +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +export type Axis = "both" | "x" | "y" | "none"; + +export interface ResizableState { + resizing: boolean; + width: number; + height: number; + slackW: number; + slackH: number; +} + +export interface DragCallbackData { + node: HTMLElement; + x: number; + y: number; + deltaX: number; + deltaY: number; + lastX: number; + lastY: number; +} + +export interface ResizeCallbackData { + node: HTMLElement; + size: { width: number; height: number }; +} + +export interface ResizableProps { + className?: string; + width: number; + height: number; + handleSize?: [number, number]; + lockAspectRatio?: boolean; + axis?: Axis; + minConstraints?: [number, number]; + maxConstraints?: [number, number]; + onResizeStop?: (e: React.SyntheticEvent, data: ResizeCallbackData) => any; + onResizeStart?: (e: React.SyntheticEvent, data: ResizeCallbackData) => any; + onResize?: (e: React.SyntheticEvent, data: ResizeCallbackData) => any; + draggableOpts?: any; +} + +export class Resizable extends React.Component< + ResizableProps, + ResizableState +> {} + +export interface ResizableBoxState { + height: number; + width: number; +} + +export type ResizableBoxProps = ResizableProps; + +export class ResizableBox extends React.Component< + ResizableBoxProps, + ResizableBoxState +> {} diff --git a/types/react-resizable/react-resizable-tests.tsx b/types/react-resizable/react-resizable-tests.tsx new file mode 100644 index 0000000000..1ecbd7574d --- /dev/null +++ b/types/react-resizable/react-resizable-tests.tsx @@ -0,0 +1,49 @@ +import * as React from "react"; +import { Resizable, ResizableBox, ResizeCallbackData } from "react-resizable"; + +const resizeCallback = ( + event: React.SyntheticEvent, + data: ResizeCallbackData +) => { + console.log(data.size.height); + console.log(data.node); +}; + +class TestResizableComponent extends React.Component { + render() { + return ( + +
    {this.props.children}
    +
    + ); + } +} + +class TestResizableBoxComponent extends React.Component { + render() { + return ( + +
    {this.props.children}
    +
    + ); + } +} diff --git a/types/react-resizable/tsconfig.json b/types/react-resizable/tsconfig.json new file mode 100644 index 0000000000..d1125b7758 --- /dev/null +++ b/types/react-resizable/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "jsx": "react", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "react-resizable-tests.tsx"] +} diff --git a/types/react-resizable/tslint.json b/types/react-resizable/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-resizable/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-resize-detector/index.d.ts b/types/react-resize-detector/index.d.ts index 68f0382dba..25e06d7bb8 100755 --- a/types/react-resize-detector/index.d.ts +++ b/types/react-resize-detector/index.d.ts @@ -29,7 +29,7 @@ interface ReactResizeDetectorProps extends React.Props { declare class ReactResizeDetector extends React.PureComponent { } -export declare function withResizeDetector( +export function withResizeDetector( WrappedComponent: React.ReactNode, props?: ReactResizeDetectorProps ): React.Component; diff --git a/types/react-widgets/index.d.ts b/types/react-widgets/index.d.ts index 61eaa78829..ac6b47b90c 100644 --- a/types/react-widgets/index.d.ts +++ b/types/react-widgets/index.d.ts @@ -7,6 +7,7 @@ // Maxime Billemaz // Georg Steinmetz // Troy Zarger +// Siya Mzam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/react-widgets/lib/DropdownList.d.ts b/types/react-widgets/lib/DropdownList.d.ts index f5aa5846e6..04683b6b62 100644 --- a/types/react-widgets/lib/DropdownList.d.ts +++ b/types/react-widgets/lib/DropdownList.d.ts @@ -166,6 +166,11 @@ interface DropdownListProps extends ReactWidgetsCommonDropdownProps> { name="list" multiple={false} /> + & Readonly

    ; + readonly props: Readonly>; state: Readonly; /** * @deprecated @@ -468,7 +468,7 @@ declare namespace React { type FC

    = FunctionComponent

    ; interface FunctionComponent

    { - (props: P & { children?: ReactNode }, context?: any): ReactElement | null; + (props: PropsWithChildren

    , context?: any): ReactElement | null; propTypes?: WeakValidationMap

    ; contextTypes?: ValidationMap; defaultProps?: Partial

    ; @@ -476,7 +476,7 @@ declare namespace React { } interface RefForwardingComponent { - (props: P & { children?: ReactNode }, ref: Ref): ReactElement | null; + (props: PropsWithChildren

    , ref: Ref): ReactElement | null; propTypes?: WeakValidationMap

    ; contextTypes?: ValidationMap; defaultProps?: Partial

    ; @@ -722,6 +722,8 @@ declare namespace React { : P : P; + type PropsWithChildren

    = P & { children?: ReactNode }; + /** * NOTE: prefer ComponentPropsWithRef, if the ref is forwarded, * or ComponentPropsWithoutRef when refs are not supported. @@ -747,7 +749,7 @@ declare namespace React { function memo

    ( Component: SFC

    , - propsAreEqual?: (prevProps: Readonly

    , nextProps: Readonly

    ) => boolean + propsAreEqual?: (prevProps: Readonly>, nextProps: Readonly>) => boolean ): NamedExoticComponent

    ; function memo>( Component: T, diff --git a/types/react/test/index.ts b/types/react/test/index.ts index d4fee49d30..7f8b13a437 100644 --- a/types/react/test/index.ts +++ b/types/react/test/index.ts @@ -803,3 +803,9 @@ const sfc: React.SFC = Memoized2; // this $ExpectError is failing on TypeScript@next // // $ExpectError Property '$$typeof' is missing in type // const specialSfc2: React.SpecialSFC = props => null; + +const propsWithChildren: React.PropsWithChildren = { + hello: "world", + foo: 42, + children: functionComponent, +}; diff --git a/types/readable-stream/package.json b/types/readable-stream/package.json new file mode 100644 index 0000000000..6eaa7476e4 --- /dev/null +++ b/types/readable-stream/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "safe-buffer": "*" + } +} diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index 963f68600c..44f97c933b 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -30,7 +30,7 @@ export type TooltipFormatter = (value: string | number | Array, entry: TooltipPayload, index: number) => React.ReactNode; export type ItemSorter = (a: T, b: T) => number; export type ContentRenderer

    = (props: P) => React.ReactNode; -export type DataKey = string | number | ((dataObject: any) => number | [number, number] | null); +export type DataKey = string | number | ((dataObject: any) => string | number | [number, number] | null); export type IconType = 'plainline' | 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'plainline'; export type LegendType = IconType | 'none'; @@ -201,6 +201,7 @@ export interface BarProps extends EventAttributes, Partial { } + label={(props: {name: string}) => } dataKey="value" activeIndex={this.state.activeIndex} activeShape={renderActiveShape} @@ -204,7 +204,7 @@ class Component extends React.Component<{}, ComponentState> { - + diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index 540e1128dd..c2a0b22d73 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -46,7 +46,7 @@ declare module 'recompose' { export interface InferableComponentEnhancerWithProps {

    ( component: Component

    - ): React.ComponentType & TNeedsProps> + ): React.ComponentClass & TNeedsProps> } // Injects props and removes them from the prop requirements. @@ -283,7 +283,7 @@ declare module 'recompose' { // setStatic: https://github.com/acdlite/recompose/blob/master/docs/API.md#setStatic export function setStatic( key: string, value: any - ): (component: T) => T; + ): >(component: T) => T; // setPropTypes: https://github.com/acdlite/recompose/blob/master/docs/API.md#setPropTypes export function setPropTypes

    ( @@ -293,7 +293,7 @@ declare module 'recompose' { // setDisplayName: https://github.com/acdlite/recompose/blob/master/docs/API.md#setDisplayName export function setDisplayName( displayName: string - ): (component: T) => T; + ): >(component: T) => T; // Utilities: https://github.com/acdlite/recompose/blob/master/docs/API.md#utilities diff --git a/types/reduce-reducers/index.d.ts b/types/reduce-reducers/index.d.ts index 9f787df032..89f98aa2b3 100644 --- a/types/reduce-reducers/index.d.ts +++ b/types/reduce-reducers/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for reduce-reducers 0.2 +// Type definitions for reduce-reducers 0.3 // Project: https://github.com/redux-utilities/reduce-reducers // Definitions by: Huy Nguyen // Dalius Dobravolskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { Reducer } from 'redux'; export default function reduceReducer(r0: Reducer, s: S | null): Reducer; diff --git a/types/reduce-reducers/package.json b/types/reduce-reducers/package.json index 6d68bf2f9b..7f5b19d45b 100644 --- a/types/reduce-reducers/package.json +++ b/types/reduce-reducers/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "redux": "^3.6.0" + "redux": "^4.0.0" } } diff --git a/types/reduce-reducers/reduce-reducers-tests.ts b/types/reduce-reducers/reduce-reducers-tests.ts index f4fdd8fff3..6d14449814 100644 --- a/types/reduce-reducers/reduce-reducers-tests.ts +++ b/types/reduce-reducers/reduce-reducers-tests.ts @@ -8,8 +8,8 @@ interface TestStore { a: number; b: string; } -const firstReducer: (state: TestStore, action: Action) => TestStore = (a, b) => a; -const secondReducer: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const firstReducer: Reducer = (store, action) => ({a: 0, b: ''}); +const secondReducer: Reducer = (store, action) => ({a: 0, b: ''}); const finalReducer: (state: TestStore, action: Action) => TestStore = reduceReducers(firstReducer, secondReducer); const finalReducerWithState: (state: TestStore, action: Action) => TestStore = reduceReducers(firstReducer, secondReducer, null); @@ -23,14 +23,14 @@ const finalReducerWithInitialState: (state: TestStore, action: Action) => TestSt secondReducer, initialState); -const reducer02: (state: TestStore, action: Action) => TestStore = (a, b) => a; -const reducer03: (state: TestStore, action: Action) => TestStore = (a, b) => a; -const reducer04: (state: TestStore, action: Action) => TestStore = (a, b) => a; -const reducer05: (state: TestStore, action: Action) => TestStore = (a, b) => a; -const reducer06: (state: TestStore, action: Action) => TestStore = (a, b) => a; -const reducer07: (state: TestStore, action: Action) => TestStore = (a, b) => a; -const reducer08: (state: TestStore, action: Action) => TestStore = (a, b) => a; -const reducer09: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer02: Reducer = (store, action) => ({a: 0, b: ''}); +const reducer03: Reducer = (store, action) => ({a: 0, b: ''}); +const reducer04: Reducer = (store, action) => ({a: 0, b: ''}); +const reducer05: Reducer = (store, action) => ({a: 0, b: ''}); +const reducer06: Reducer = (store, action) => ({a: 0, b: ''}); +const reducer07: Reducer = (store, action) => ({a: 0, b: ''}); +const reducer08: Reducer = (store, action) => ({a: 0, b: ''}); +const reducer09: Reducer = (store, action) => ({a: 0, b: ''}); const finalReducerWithInitialState02: (state: TestStore, action: Action) => TestStore = reduceReducers( firstReducer, diff --git a/types/reflux/index.d.ts b/types/reflux/index.d.ts index dcfa795e73..a00dffb7db 100644 --- a/types/reflux/index.d.ts +++ b/types/reflux/index.d.ts @@ -51,8 +51,6 @@ export class Component any): void; } diff --git a/types/rmc-drawer/package.json b/types/rmc-drawer/package.json new file mode 100644 index 0000000000..f06689a6b9 --- /dev/null +++ b/types/rmc-drawer/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "moment": "^2.19.4" + } +} diff --git a/types/rn-fetch-blob/index.d.ts b/types/rn-fetch-blob/index.d.ts index 79758b4511..2ff48bc108 100644 --- a/types/rn-fetch-blob/index.d.ts +++ b/types/rn-fetch-blob/index.d.ts @@ -33,11 +33,11 @@ export interface Polyfill { Fetch: PolyfillFetch; } -export declare class PolyfillFetch extends RNFetchBlobFetchPolyfill { +export class PolyfillFetch extends RNFetchBlobFetchPolyfill { constructor(config: RNFetchBlobConfig); } -export declare class RNFetchBlobFetchPolyfill { +export class RNFetchBlobFetchPolyfill { constructor(config: RNFetchBlobConfig); build(): (url: string, options: RNFetchBlobConfig) => StatefulPromise; @@ -129,13 +129,13 @@ export interface PolyfillFileReader extends EventTarget { result: number; } -export declare namespace PolyfillFileReader { +export namespace PolyfillFileReader { const EMPTY: number; const LOADING: number; const DONE: number; } -export declare class PolyfillEvent { +export class PolyfillEvent { } export interface PolyfillProgressEvent extends EventTarget { @@ -144,7 +144,7 @@ export interface PolyfillProgressEvent extends EventTarget { total: number; } -export declare class PolyfillBlob extends EventTarget { +export class PolyfillBlob extends EventTarget { /** * RNFetchBlob Blob polyfill, create a Blob directly from file path, BASE64 * encoded data, and string. The conversion is done implicitly according to @@ -194,7 +194,7 @@ export declare class PolyfillBlob extends EventTarget { close(): Promise; } -export declare namespace PolyfillBlob { +export namespace PolyfillBlob { function clearCache(): void; function build(data: any, cType: any): Promise; @@ -202,7 +202,7 @@ export declare namespace PolyfillBlob { function setLog(level: number): void; } -export declare class PolyfillFile extends PolyfillBlob { +export class PolyfillFile extends PolyfillBlob { } export interface PolyfillXMLHttpRequest extends PolyfillXMLHttpRequestEventTarget { @@ -252,7 +252,7 @@ export interface PolyfillXMLHttpRequest extends PolyfillXMLHttpRequestEventTarge responseType: string; } -export declare namespace PolyfillXMLHttpRequest { +export namespace PolyfillXMLHttpRequest { const binaryContentTypes: string[]; const UNSENT: number; const OPENED: number; @@ -490,7 +490,7 @@ export interface StatefulPromise extends Promise { expire(callback: () => void): StatefulPromise; } -export declare class RNFetchBlobSession { +export class RNFetchBlobSession { constructor(name: string, list: string[]); add(path: string): RNFetchBlobSession; @@ -609,10 +609,10 @@ export interface RNFetchBlobStream { onEnd(): void; } -export declare class RNFetchBlobFile { +export class RNFetchBlobFile { } -export declare class RNFetchBlobStat { +export class RNFetchBlobStat { lastModified: string; size: string; type: "directory" | "file"; diff --git a/types/sarif/index.d.ts b/types/sarif/index.d.ts index cc5a9899b5..56bcf3e8da 100644 --- a/types/sarif/index.d.ts +++ b/types/sarif/index.d.ts @@ -5,7 +5,7 @@ // TypeScript Version: 2.4 /** - * Static Analysis Results Format (SARIF) Version 2.0.0-csd.2.beta-2019-01-09 JSON Schema: a standard format for the + * Static Analysis Results Format (SARIF) Version 2.0.0-csd.2.beta-2019-01-24 JSON Schema: a standard format for the * output of static analysis tools. */ export interface Log { @@ -32,23 +32,174 @@ export interface Log { export namespace Log { type version = - "2.0.0-csd.2.beta.2019-01-09"; + "2.0.0-csd.2.beta.2019-01-24"; } /** - * A file relevant to a tool invocation or to a result. + * A single artifact. In some cases, this artifact might be nested within another artifact. + */ +export interface Artifact { + /** + * The contents of the artifact. + */ + contents?: ArtifactContent; + + /** + * Specifies the encoding for an artifact object that refers to a text file. + */ + encoding?: string; + + /** + * A dictionary, each of whose keys is the name of a hash function and each of whose values is the hashed value of + * the artifact produced by the specified hash function. + */ + hashes?: { [key: string]: string }; + + /** + * The Coordinated Universal Time (UTC) date and time at which the artifact was most recently modified. See + * "Date/time properties" in the SARIF spec for the required format. + */ + lastModifiedTimeUtc?: string; + + /** + * The length of the artifact in bytes. + */ + length?: number; + + /** + * The location of the artifact. + */ + location?: ArtifactLocation; + + /** + * The MIME type (RFC 2045) of the artifact. + */ + mimeType?: string; + + /** + * The offset in bytes of the artifact within its containing artifact. + */ + offset?: number; + + /** + * Identifies the index of the immediate parent of the artifact, if this artifact is nested. + */ + parentIndex?: number; + + /** + * The role or roles played by the artifact in the analysis. + */ + roles?: Artifact.roles[]; + + /** + * Specifies the source language for any artifact object that refers to a text file that contains source code. + */ + sourceLanguage?: string; + + /** + * Key/value pairs that provide additional information about the artifact. + */ + properties?: PropertyBag; +} + +export namespace Artifact { + type roles = + "analysisTarget" | + "toolComponent" | + "attachment" | + "responseFile" | + "resultFile" | + "standardStream" | + "traceFile" | + "unmodifiedFile" | + "modifiedFile" | + "addedFile" | + "deletedFile" | + "renamedFile" | + "uncontrolledFile"; +} + +/** + * A change to a single artifact. + */ +export interface ArtifactChange { + /** + * The location of the artifact to change. + */ + artifactLocation: ArtifactLocation; + + /** + * An array of replacement objects, each of which represents the replacement of a single region in a single + * artifact specified by 'artifactLocation'. + */ + replacements: Replacement[]; + + /** + * Key/value pairs that provide additional information about the change. + */ + properties?: PropertyBag; +} + +/** + * Represents the contents of an artifact. + */ +export interface ArtifactContent { + /** + * MIME Base64-encoded content from a binary artifact, or from a text artifact in its original encoding. + */ + binary?: string; + + /** + * UTF-8-encoded content from a text artifact. + */ + text?: string; + + /** + * Key/value pairs that provide additional information about the artifact content. + */ + properties?: PropertyBag; +} + +/** + * Specifies the location of an artifact. + */ +export interface ArtifactLocation { + /** + * The index within the run artifacts array of the artifact object associated with the artifact location. + */ + index?: number; + + /** + * A string containing a valid relative or absolute URI. + */ + uri: string; + + /** + * A string which indirectly specifies the absolute URI with respect to which a relative URI in the "uri" property + * is interpreted. + */ + uriBaseId?: string; + + /** + * Key/value pairs that provide additional information about the artifact location. + */ + properties?: PropertyBag; +} + +/** + * An artifact relevant to a tool invocation or to a result. */ export interface Attachment { + /** + * The location of the attachment. + */ + artifactLocation: ArtifactLocation; + /** * A message describing the role played by the attachment. */ description?: Message; - /** - * The location of the attachment. - */ - fileLocation: FileLocation; - /** * An array of rectangles specifying areas of interest within the image. */ @@ -75,8 +226,8 @@ export interface CodeFlow { message?: Message; /** - * An array of one or more unique threadFlow objects, each of which describes the progress of a program through - * a thread of execution. + * An array of one or more unique threadFlow objects, each of which describes the progress of a program through a + * thread of execution. */ threadFlows: ThreadFlow[]; @@ -94,7 +245,7 @@ export interface Conversion { /** * The locations of the analysis tool's per-run log files. */ - analysisToolLogFiles?: FileLocation[]; + analysisToolLogFiles?: ArtifactLocation[]; /** * An invocation object that describes the invocation of the converter. @@ -182,8 +333,8 @@ export interface Exception { innerExceptions?: Exception[]; /** - * A string that identifies the kind of exception, for example, the fully qualified type name of an object that - * was thrown, or the symbolic name of a signal. + * A string that identifies the kind of exception, for example, the fully qualified type name of an object that was + * thrown, or the symbolic name of a signal. */ kind?: string; @@ -210,7 +361,7 @@ export interface ExternalPropertyFile { /** * The location of the external property file. */ - fileLocation?: FileLocation; + artifactLocation?: ArtifactLocation; /** * A stable, unique identifer for the external property file in the form of a GUID. @@ -232,15 +383,20 @@ export interface ExternalPropertyFile { * References to external property files that should be inlined with the content of a root log file. */ export interface ExternalPropertyFiles { + /** + * An array of external property files containing run.artifacts arrays to be merged with the root log file. + */ + artifacts?: ExternalPropertyFile[]; + /** * An external property file containing a run.conversion object to be merged with the root log file. */ conversion?: ExternalPropertyFile; /** - * An array of external property files containing run.files arrays to be merged with the root log file. + * An external property file containing a run.properties object to be merged with the root log file. */ - files?: ExternalPropertyFile[]; + externalizedProperties?: ExternalPropertyFile; /** * An external property file containing a run.graphs object to be merged with the root log file. @@ -257,187 +413,32 @@ export interface ExternalPropertyFiles { */ logicalLocations?: ExternalPropertyFile[]; - /** - * An external property file containing a run.resources object to be merged with the root log file. - */ - resources?: ExternalPropertyFile; - /** * An array of external property files containing run.results arrays to be merged with the root log file. */ results?: ExternalPropertyFile[]; /** - * An external property file containing a run.properties object to be merged with the root log file. + * An external property file containing a run.tool object to be merged with the root log file. */ - properties?: ExternalPropertyFile; + tool?: ExternalPropertyFile; } /** - * A single file. In some cases, this file might be nested within another file. - */ -export interface File { - /** - * The contents of the file. - */ - contents?: FileContent; - - /** - * Specifies the encoding for a file object that refers to a text file. - */ - encoding?: string; - - /** - * The location of the file. - */ - fileLocation?: FileLocation; - - /** - * A dictionary, each of whose keys is the name of a hash function and each of whose values is the hashed value - * of the file produced by the specified hash function. - */ - hashes?: { [key: string]: string }; - - /** - * The Coordinated Universal Time (UTC) date and time at which the file was most recently modified. See - * "Date/time properties" in the SARIF spec for the required format. - */ - lastModifiedTimeUtc?: string; - - /** - * The length of the file in bytes. - */ - length?: number; - - /** - * The MIME type (RFC 2045) of the file. - */ - mimeType?: string; - - /** - * The offset in bytes of the file within its containing file. - */ - offset?: number; - - /** - * Identifies the index of the immediate parent of the file, if this file is nested. - */ - parentIndex?: number; - - /** - * The role or roles played by the file in the analysis. - */ - roles?: File.roles[]; - - /** - * Specifies the source language for any file object that refers to a text file that contains source code. - */ - sourceLanguage?: string; - - /** - * Key/value pairs that provide additional information about the file. - */ - properties?: PropertyBag; -} - -export namespace File { - type roles = - "analysisTarget" | - "attachment" | - "responseFile" | - "resultFile" | - "standardStream" | - "traceFile" | - "unmodifiedFile" | - "modifiedFile" | - "addedFile" | - "deletedFile" | - "renamedFile" | - "uncontrolledFile"; -} - -/** - * A change to a single file. - */ -export interface FileChange { - /** - * The location of the file to change. - */ - fileLocation: FileLocation; - - /** - * An array of replacement objects, each of which represents the replacement of a single region in a single file - * specified by 'fileLocation'. - */ - replacements: Replacement[]; - - /** - * Key/value pairs that provide additional information about the file change. - */ - properties?: PropertyBag; -} - -/** - * Represents content from an external file. - */ -export interface FileContent { - /** - * MIME Base64-encoded content from a binary file, or from a text file in its original encoding. - */ - binary?: string; - - /** - * UTF-8-encoded content from a text file. - */ - text?: string; - - /** - * Key/value pairs that provide additional information about the external file. - */ - properties?: PropertyBag; -} - -/** - * Specifies the location of a file. - */ -export interface FileLocation { - /** - * The index within the run files array of the file object associated with the file location. - */ - fileIndex?: number; - - /** - * A string containing a valid relative or absolute URI. - */ - uri: string; - - /** - * A string which indirectly specifies the absolute URI with respect to which a relative URI in the "uri" - * property is interpreted. - */ - uriBaseId?: string; - - /** - * Key/value pairs that provide additional information about the file location. - */ - properties?: PropertyBag; -} - -/** - * A proposed fix for the problem represented by a result object. A fix specifies a set of file to modify. For each - * file, it specifies a set of bytes to remove, and provides a set of new bytes to replace them. + * A proposed fix for the problem represented by a result object. A fix specifies a set of artifacts to modify. For + * each artifact, it specifies a set of bytes to remove, and provides a set of new bytes to replace them. */ export interface Fix { + /** + * One or more artifact changes that comprise a fix for a result. + */ + changes: ArtifactChange[]; + /** * A message that describes the proposed fix, enabling viewers to present the proposed change to an end user. */ description?: Message; - /** - * One or more file changes that comprise a fix for a result. - */ - fileChanges: FileChange[]; - /** * Key/value pairs that provide additional information about the fix. */ @@ -445,8 +446,8 @@ export interface Fix { } /** - * A network of nodes and directed edges that describes some aspect of the structure of the code (for example, a - * call graph). + * A network of nodes and directed edges that describes some aspect of the structure of the code (for example, a call + * graph). */ export interface Graph { /** @@ -521,7 +522,7 @@ export interface Invocation { arguments?: string[]; /** - * A set of files relevant to the invocation of the tool. + * A set of artifacts relevant to the invocation of the tool. */ attachments?: Attachment[]; @@ -549,7 +550,7 @@ export interface Invocation { /** * An absolute URI specifying the location of the analysis tool's executable. */ - executableLocation?: FileLocation; + executableLocation?: ArtifactLocation; /** * The process exit code. @@ -587,36 +588,40 @@ export interface Invocation { processStartFailureMessage?: string; /** - * The locations of any response files specified on the tool's command line. + * An array of reportingConfigurationOverride objects that describe runtime reporting behavior. */ - responseFiles?: FileLocation[]; + reportingConfigurationOverrides?: ReportingConfigurationOverride[]; /** - * The Coordinated Universal Time (UTC) date and time at which the run started. See "Date/time properties" in - * the SARIF spec for the required format. + * The locations of any response files specified on the tool's command line. + */ + responseFiles?: ArtifactLocation[]; + + /** + * The Coordinated Universal Time (UTC) date and time at which the run started. See "Date/time properties" in the + * SARIF spec for the required format. */ startTimeUtc?: string; /** * A file containing the standard error stream from the process that was invoked. */ - stderr?: FileLocation; + stderr?: ArtifactLocation; /** * A file containing the standard input stream to the process that was invoked. */ - stdin?: FileLocation; + stdin?: ArtifactLocation; /** * A file containing the standard output stream from the process that was invoked. */ - stdout?: FileLocation; + stdout?: ArtifactLocation; /** - * A file containing the interleaved standard output and standard error stream from the process that was - * invoked. + * A file containing the interleaved standard output and standard error stream from the process that was invoked. */ - stdoutStderr?: FileLocation; + stdoutStderr?: ArtifactLocation; /** * A value indicating whether the tool's execution completed successfully. @@ -631,7 +636,7 @@ export interface Invocation { /** * The working directory for the analysis tool run. */ - workingDirectory?: FileLocation; + workingDirectory?: ArtifactLocation; /** * Key/value pairs that provide additional information about the invocation. @@ -649,9 +654,9 @@ export interface Location { annotations?: Region[]; /** - * The human-readable fully qualified name of the logical location. If run.logicalLocations is present, this - * value matches a property name within that object, from which further information about the logical location - * can be obtained. + * The human-readable fully qualified name of the logical location. If run.logicalLocations is present, this value + * matches a property name within that object, from which further information about the logical location can be + * obtained. */ fullyQualifiedLogicalName?: string; @@ -666,7 +671,7 @@ export interface Location { message?: Message; /** - * Identifies the file and region. + * Identifies the artifact and region. */ physicalLocation?: PhysicalLocation; @@ -681,8 +686,8 @@ export interface Location { */ export interface LogicalLocation { /** - * The machine-readable name for the logical location, such as a mangled function name provided by a C++ - * compiler that encodes calling convention, return type and other details along with the function name. + * The machine-readable name for the logical location, such as a mangled function name provided by a C++ compiler + * that encodes calling convention, return type and other details along with the function name. */ decoratedName?: string; @@ -693,8 +698,8 @@ export interface LogicalLocation { /** * The type of construct this logical location component refers to. Should be one of 'function', 'member', - * 'module', 'namespace', 'parameter', 'resource', 'returnType', 'type', or 'variable', if any of those - * accurately describe the construct. + * 'module', 'namespace', 'parameter', 'resource', 'returnType', 'type', or 'variable', if any of those accurately + * describe the construct. */ kind?: string; @@ -726,20 +731,15 @@ export interface Message { arguments?: string[]; /** - * The resource id for a plain text message string. + * A Markdown message string. + */ + markdown?: string; + + /** + * The resource id for a plain text or Markdown message string. */ messageId?: string; - /** - * The resource id for a rich text message string. - */ - richMessageId?: string; - - /** - * A rich text message string. - */ - richText?: string; - /** * A plain text message string. */ @@ -751,6 +751,26 @@ export interface Message { properties?: PropertyBag; } +/** + * A message string or message format string rendered in multiple formats. + */ +export interface MultiformatMessageString { + /** + * A Markdown message string or format string. + */ + markdown?: string; + + /** + * A plain text message string or format string. + */ + text?: string; + + /** + * Key/value pairs that provide additional information about the message. + */ + properties?: PropertyBag; +} + /** * Represents a node in a graph. */ @@ -807,7 +827,7 @@ export interface Notification { message: Message; /** - * The file and region relevant to this notification. + * The artifact and region relevant to this notification. */ physicalLocation?: PhysicalLocation; @@ -839,34 +859,35 @@ export interface Notification { export namespace Notification { type level = + "none" | "note" | "warning" | "error"; } /** - * A physical location relevant to a result. Specifies a reference to a programming artifact together with a range - * of bytes or characters within that artifact. + * A physical location relevant to a result. Specifies a reference to a programming artifact together with a range of + * bytes or characters within that artifact. */ export interface PhysicalLocation { /** - * Specifies a portion of the file that encloses the region. Allows a viewer to display additional context + * The location of the artifact. + */ + artifactLocation: ArtifactLocation; + + /** + * Specifies a portion of the artifact that encloses the region. Allows a viewer to display additional context * around the region. */ contextRegion?: Region; - /** - * The location of the file. - */ - fileLocation: FileLocation; - /** * Value that distinguishes this physical location from all other physical locations in this run object. */ id?: number; /** - * Specifies a portion of the file. + * Specifies a portion of the artifact. */ region?: Region; @@ -927,7 +948,7 @@ export interface Rectangle { } /** - * A region within a file where a result was detected. + * A region within an artifact where a result was detected. */ export interface Region { /** @@ -936,7 +957,7 @@ export interface Region { byteLength?: number; /** - * The zero-based offset from the beginning of the file of the first byte in the region. + * The zero-based offset from the beginning of the artifact of the first byte in the region. */ byteOffset?: number; @@ -946,7 +967,7 @@ export interface Region { charLength?: number; /** - * The zero-based offset from the beginning of the file of the first character in the region. + * The zero-based offset from the beginning of the artifact of the first character in the region. */ charOffset?: number; @@ -966,12 +987,12 @@ export interface Region { message?: Message; /** - * The portion of the file contents within the specified region. + * The portion of the artifact contents within the specified region. */ - snippet?: FileContent; + snippet?: ArtifactContent; /** - * Specifies the source language, if any, of the portion of the file specified by the region object. + * Specifies the source language, if any, of the portion of the artifact specified by the region object. */ sourceLanguage?: string; @@ -992,18 +1013,18 @@ export interface Region { } /** - * The replacement of a single region of a file. + * The replacement of a single region of an artifact. */ export interface Replacement { /** - * The region of the file to delete. + * The region of the artifact to delete. */ deletedRegion: Region; /** * The content to insert at the location specified by the 'deletedRegion' property. */ - insertedContent?: FileContent; + insertedContent?: ArtifactContent; /** * Key/value pairs that provide additional information about the replacement. @@ -1012,21 +1033,133 @@ export interface Replacement { } /** - * Container for items that require localization. + * Information about a tool report that can be configured at runtime. */ -export interface Resources { +export interface ReportingConfiguration { /** - * A dictionary, each of whose keys is a resource identifier and each of whose values is a localized string. + * Specifies whether the report may be produced during the scan. */ - messageStrings?: { [key: string]: string }; + enabled?: boolean; /** - * An array of rule objects relevant to the run. + * Specifies the failure level for the report. */ - rules?: Rule[]; + level?: ReportingConfiguration.level; /** - * Key/value pairs that provide additional information about the resources. + * Contains configuration information specific to a report. + */ + parameters?: PropertyBag; + + /** + * Specifies the relative priority of the report. Used for analysis output only. + */ + rank?: number; + + /** + * Key/value pairs that provide additional information about the reporting configuration. + */ + properties?: PropertyBag; +} + +export namespace ReportingConfiguration { + type level = + "none" | + "note" | + "warning" | + "error"; +} + +/** + * Information about how a specific tool report was reconfigured at runtime. + */ +export interface ReportingConfigurationOverride { + /** + * Specifies how the report was configured during the scan. + */ + configuration?: ReportingConfiguration; + + /** + * The index within the run.tool.extensions array of the toolComponent object which describes the plug-in or tool + * extension that produced the report. + */ + extensionIndex?: number; + + /** + * The index within the toolComponent.notificationDescriptors array of the reportingDescriptor associated with this + * override. + */ + notificationIndex?: number; + + /** + * The index within the toolComponent.ruleDescriptors array of the reportingDescriptor associated with this + * override. + */ + ruleIndex?: number; + + /** + * Key/value pairs that provide additional information about the reporting configuration. + */ + properties?: PropertyBag; +} + +/** + * Metadata that describes a specific report produced by the tool, as part of the analysis it provides or its runtime + * reporting. + */ +export interface ReportingDescriptor { + /** + * Default reporting configuration information. + */ + defaultConfiguration?: ReportingConfiguration; + + /** + * An array of stable, opaque identifiers by which this report was known in some previous version of the analysis + * tool. + */ + deprecatedIds?: string[]; + + /** + * A description of the report. Should, as far as possible, provide details sufficient to enable resolution of any + * problem indicated by the result. + */ + fullDescription?: Message; + + /** + * Provides the primary documentation for the report, useful when there is no online documentation. + */ + help?: Message; + + /** + * A URI where the primary documentation for the report can be found. + */ + helpUri?: string; + + /** + * A stable, opaque identifier for the report. + */ + id?: string; + + /** + * A set of name/value pairs with arbitrary names. Each value is a multiformatMessageString object, which holds + * message strings in plain text and (optionally) Markdown format. The strings can include placeholders, which can + * be used to construct a message in combination with an arbitrary number of additional string arguments. + */ + messageStrings?: { [key: string]: MultiformatMessageString }; + + /** + * A report identifier that is understandable to an end user. + */ + name?: Message; + + /** + * A concise description of the report. Should be a single sentence that is understandable when visible space is + * limited to a single line of text. + */ + shortDescription?: Message; + + /** + * Key/value pairs that provide additional information about the report. */ properties?: PropertyBag; } @@ -1036,13 +1169,13 @@ export interface Resources { */ export interface Result { /** - * Identifies the file that the analysis tool was instructed to scan. This need not be the same as the file + * Identifies the artifact that the analysis tool was instructed to scan. This need not be the same as the artifact * where the result actually occurred. */ - analysisTarget?: FileLocation; + analysisTarget?: ArtifactLocation; /** - * A set of files relevant to the result. + * A set of artifacts relevant to the result. */ attachments?: Attachment[]; @@ -1073,8 +1206,7 @@ export interface Result { fixes?: Fix[]; /** - * A dictionary, each of whose keys is the id of a graph and each of whose values is a 'graph' object with that - * id. + * A dictionary, each of whose keys is the id of a graph and each of whose values is a 'graph' object with that id. */ graphs?: { [key: string]: Graph }; @@ -1093,6 +1225,11 @@ export interface Result { */ instanceGuid?: string; + /** + * A value that categorizes results by evaluation state. + */ + kind?: Result.kind; + /** * A value specifying the severity level of the result. */ @@ -1105,8 +1242,8 @@ export interface Result { locations?: Location[]; /** - * A message that describes the result. The first sentence of the message only will be displayed when visible - * space is limited. + * A message that describes the result. The first sentence of the message only will be displayed when visible space + * is limited. */ message: Message; @@ -1135,6 +1272,12 @@ export interface Result { */ relatedLocations?: Location[]; + /** + * The index within the run.tool.extensions array of the tool component object which describes the plug-in or tool + * extension that produced the result. + */ + ruleExtensionIndex?: number; + /** * The stable, unique identifier of the rule, if any, to which this notification is relevant. This member can be * used to retrieve rule metadata from the rules dictionary, if it exists. @@ -1168,13 +1311,19 @@ export interface Result { } export namespace Result { - type level = + type kind = + "none" | "notApplicable" | "pass" | + "fail" | + "review" | + "open"; + + type level = + "none" | "note" | "warning" | - "error" | - "open"; + "error"; type suppressionStates = "suppressedInSource" | @@ -1182,7 +1331,8 @@ export namespace Result { type baselineState = "new" | - "existing" | + "unchanged" | + "updated" | "absent"; } @@ -1191,14 +1341,13 @@ export namespace Result { */ export interface ResultProvenance { /** - * An array of physicalLocation objects which specify the portions of an analysis tool's output that a - * converter transformed into the result. + * An array of physicalLocation objects which specify the portions of an analysis tool's output that a converter + * transformed into the result. */ conversionSources?: PhysicalLocation[]; /** - * A GUID-valued string equal to the id.instanceGuid property of the run in which the result was first - * detected. + * A GUID-valued string equal to the id.instanceGuid property of the run in which the result was first detected. */ firstDetectionRunInstanceGuid?: string; @@ -1233,111 +1382,7 @@ export interface ResultProvenance { } /** - * Describes an analysis rule. - */ -export interface Rule { - /** - * Information about the rule that can be configured at runtime. - */ - configuration?: RuleConfiguration; - - /** - * An array of stable, opaque identifiers by which this rule was known in some previous version of the analysis - * tool. - */ - deprecatedIds?: string[]; - - /** - * A description of the rule. Should, as far as possible, provide details sufficient to enable resolution of any - * problem indicated by the result. - */ - fullDescription?: Message; - - /** - * Provides the primary documentation for the rule, useful when there is no online documentation. - */ - help?: Message; - - /** - * A URI where the primary documentation for the rule can be found. - */ - helpUri?: string; - - /** - * A stable, opaque identifier for the rule. - */ - id?: string; - - /** - * A set of name/value pairs with arbitrary names. The value within each name/value pair consists of plain text - * interspersed with placeholders, which can be used to construct a message in combination with an arbitrary - * number of additional string arguments. - */ - messageStrings?: { [key: string]: string }; - - /** - * A rule identifier that is understandable to an end user. - */ - name?: Message; - - /** - * A set of name/value pairs with arbitrary names. The value within each name/value pair consists of rich text - * interspersed with placeholders, which can be used to construct a message in combination with an arbitrary - * number of additional string arguments. - */ - richMessageStrings?: { [key: string]: string }; - - /** - * A concise description of the rule. Should be a single sentence that is understandable when visible space is - * limited to a single line of text. - */ - shortDescription?: Message; - - /** - * Key/value pairs that provide additional information about the rule. - */ - properties?: PropertyBag; -} - -/** - * Information about a rule that can be configured at runtime. - */ -export interface RuleConfiguration { - /** - * Specifies the default severity level for results generated by this rule. - */ - defaultLevel?: RuleConfiguration.defaultLevel; - - /** - * Specifies the default priority or importance for results generated by this rule. - */ - defaultRank?: number; - - /** - * Specifies whether the rule will be evaluated during the scan. - */ - enabled?: boolean; - - /** - * Contains configuration information specific to this rule. - */ - parameters?: PropertyBag; - - /** - * Key/value pairs that provide additional information about the rule configuration. - */ - properties?: PropertyBag; -} - -export namespace RuleConfiguration { - type defaultLevel = - "note" | - "warning" | - "error"; -} - -/** - * Describes a single run of an analysis tool, and contains the output of that run. + * Describes a single run of an analysis tool, and contains the reported output of that run. */ export interface Run { /** @@ -1345,6 +1390,11 @@ export interface Run { */ aggregateIds?: RunAutomationDetails[]; + /** + * An array of artifact objects relevant to the run. + */ + artifacts?: Artifact[]; + /** * The 'instanceGuid' property of a previous SARIF 'run' that comprises the baseline that was used to compute * result 'baselineState' properties for the run. @@ -1357,18 +1407,18 @@ export interface Run { columnKind?: Run.columnKind; /** - * A conversion object that describes how a converter transformed an analysis tool's native output format into + * A conversion object that describes how a converter transformed an analysis tool's native reporting format into * the SARIF format. */ conversion?: Conversion; /** - * Specifies the default encoding for any file object that refers to a text file. + * Specifies the default encoding for any artifact object that refers to a text file. */ defaultFileEncoding?: string; /** - * Specifies the default source language for any file object that refers to a text file that contains source + * Specifies the default source language for any artifact object that refers to a text file that contains source * code. */ defaultSourceLanguage?: string; @@ -1379,13 +1429,7 @@ export interface Run { externalPropertyFiles?: ExternalPropertyFiles; /** - * An array of file objects relevant to the run. - */ - files?: File[]; - - /** - * A dictionary, each of whose keys is the id of a graph and each of whose values is a 'graph' object with that - * id. + * A dictionary, each of whose keys is the id of a graph and each of whose values is a 'graph' object with that id. */ graphs?: { [key: string]: Graph }; @@ -1405,47 +1449,41 @@ export interface Run { logicalLocations?: LogicalLocation[]; /** - * An ordered list of character sequences that were treated as line breaks when computing region information - * for the run. + * The MIME type of all Markdown text message properties in the run. Default: "text/markdown;variant=GFM" + */ + markdownMessageMimeType?: string; + + /** + * An ordered list of character sequences that were treated as line breaks when computing region information for + * the run. */ newlineSequences?: string[]; /** - * The file location specified by each uriBaseId symbol on the machine where the tool originally ran. + * The artifact location specified by each uriBaseId symbol on the machine where the tool originally ran. */ - originalUriBaseIds?: { [key: string]: FileLocation }; + originalUriBaseIds?: { [key: string]: ArtifactLocation }; /** * The string used to replace sensitive information in a redaction-aware property. */ redactionToken?: string; - /** - * Items that can be localized, such as message strings and rule metadata. - */ - resources?: Resources; - /** * The set of results contained in an SARIF log. The results array can be omitted when a run is solely exporting * rules metadata. It must be present (but may be empty) if a log file represents an actual scan. */ results?: Result[]; - /** - * The MIME type of all rich text message properties in the run. Default: "text/markdown;variant=GFM" - */ - richMessageMimeType?: string; - /** * Information about the tool or tool pipeline that generated the results in this run. A run can only contain - * results produced by a single tool or tool pipeline. A run can aggregate results from multiple log files, as - * long as context around the tool run (tool command-line arguments and the like) is identical for all - * aggregated files. + * results produced by a single tool or tool pipeline. A run can aggregate results from multiple log files, as long + * as context around the tool run (tool command-line arguments and the like) is identical for all aggregated files. */ tool: Tool; /** - * Specifies the revision in version control of the files that were scanned. + * Specifies the revision in version control of the artifacts that were scanned. */ versionControlProvenance?: VersionControlDetails[]; @@ -1595,15 +1633,17 @@ export interface ThreadFlowLocation { executionTimeUtc?: string; /** - * Specifies the importance of this location in understanding the code flow in which it occurs. The order from - * most to least important is "essential", "important", "unimportant". Default: "important". + * Specifies the importance of this location in understanding the code flow in which it occurs. The order from most + * to least important is "essential", "important", "unimportant". Default: "important". */ importance?: ThreadFlowLocation.importance; /** - * A string describing the type of this location. + * A set of distinct strings that categorize the thread flow location. Well-known kinds include acquire, release, + * enter, exit, call, return, branch, implicit, false, true, caution, danger, unknown, unreachable, taint, + * function, handler, lock, memory, resource, and scope. */ - kind?: string; + kinds?: string[]; /** * The code location. @@ -1627,8 +1667,8 @@ export interface ThreadFlowLocation { /** * A dictionary, each of whose keys specifies a variable or expression, the associated value of which represents - * the variable or expression value. For an annotation of kind 'continuation', for example, this dictionary - * might hold the current assumed values of a set of global variables. + * the variable or expression value. For an annotation of kind 'continuation', for example, this dictionary might + * hold the current assumed values of a set of global variables. */ state?: { [key: string]: string }; @@ -1650,20 +1690,14 @@ export namespace ThreadFlowLocation { */ export interface Tool { /** - * The binary version of the tool's primary executable file expressed as four non-negative integers separated - * by a period (for operating systems that express file versions in this way). + * The analysis tool that was run. */ - dottedQuadFileVersion?: string; + driver: ToolComponent; /** - * The absolute URI from which the tool can be downloaded. + * Tool extensions that contributed to or reconfigured the analysis tool that was run. */ - downloadUri?: string; - - /** - * The name of the tool along with its version and any other useful identifying information, such as its locale. - */ - fullName?: string; + extensions?: ToolComponent[]; /** * The tool language (expressed as an ISO 649 two-letter lowercase culture code) and region (expressed as an ISO @@ -1672,28 +1706,73 @@ export interface Tool { language?: string; /** - * The name of the tool. + * Key/value pairs that provide additional information about the tool. + */ + properties?: PropertyBag; +} + +/** + * A component, such as a plug-in or the default driver, of the analysis tool that was run. + */ +export interface ToolComponent { + /** + * The index within the run artifacts array of the artifact object associated with the component. + */ + artifactIndex?: number; + + /** + * The binary version of the component's primary executable file expressed as four non-negative integers separated + * by a period (for operating systems that express file versions in this way). + */ + dottedQuadFileVersion?: string; + + /** + * The absolute URI from which the component can be downloaded. + */ + downloadUri?: string; + + /** + * The name of the component along with its version and any other useful identifying information, such as its + * locale. + */ + fullName?: string; + + /** + * A dictionary, each of whose keys is a resource identifier and each of whose values is a multiformatMessageString + * object, which holds message strings in plain text and (optionally) Markdown format. The strings can include + * placeholders, which can be used to construct a message in combination with an arbitrary number of additional + * string arguments. + */ + globalMessageStrings?: { [key: string]: MultiformatMessageString }; + + /** + * The name of the component. */ name: string; /** - * A version that uniquely identifies the SARIF logging component that generated this file, if it is versioned - * separately from the tool. + * An array of reportDescriptor objects relevant to the notifications related to the configuration and runtime + * execution of the component. */ - sarifLoggerVersion?: string; + notificationDescriptors?: ReportingDescriptor[]; /** - * The tool version in the format specified by Semantic Versioning 2.0. + * An array of reportDescriptor objects relevant to the analysis performed by the component. + */ + ruleDescriptors?: ReportingDescriptor[]; + + /** + * The component version in the format specified by Semantic Versioning 2.0. */ semanticVersion?: string; /** - * The tool version, in whatever format the tool natively provides. + * The component version, in whatever format the component natively provides. */ version?: string; /** - * Key/value pairs that provide additional information about the tool. + * Key/value pairs that provide additional information about the component. */ properties?: PropertyBag; } @@ -1703,8 +1782,8 @@ export interface Tool { */ export interface VersionControlDetails { /** - * A Coordinated Universal Time (UTC) date and time that can be used to synchronize an enlistment to the state - * of the repository at that time. + * A Coordinated Universal Time (UTC) date and time that can be used to synchronize an enlistment to the state of + * the repository at that time. */ asOfTimeUtc?: string; @@ -1717,7 +1796,7 @@ export interface VersionControlDetails { * The location in the local file system to which the root of the repository was mapped at the time of the * analysis. */ - mappedTo?: FileLocation; + mappedTo?: ArtifactLocation; /** * The absolute URI of the repository. diff --git a/types/sarif/sarif-tests.ts b/types/sarif/sarif-tests.ts index 45b5bf922d..35d522b86b 100644 --- a/types/sarif/sarif-tests.ts +++ b/types/sarif/sarif-tests.ts @@ -4,8 +4,10 @@ const input = `{ "runs": [ { "tool": { - "name": "CodeScanner", - "semanticVersion": "2.1.0" + "driver": { + "name": "CodeScanner", + "semanticVersion": "2.1.0" + }, }, "results": [ ] @@ -13,6 +15,6 @@ const input = `{ ] }`; const log = JSON.parse("") as sarif.Log; -if (log.runs[0].tool.name !== "CodeScanner") { +if (log.runs[0].tool.driver.name !== "CodeScanner") { throw new Error("error: Tool name does not match"); } diff --git a/types/seamless-immutable/index.d.ts b/types/seamless-immutable/index.d.ts index 1990dff0ab..1206034846 100644 --- a/types/seamless-immutable/index.d.ts +++ b/types/seamless-immutable/index.d.ts @@ -80,7 +80,7 @@ declare namespace SeamlessImmutable { propertyPath: [ K, L, M, N ], updaterFunction: (value: T[K][L][M][N], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): Immutable; updateIn( propertyPath: [ K, L, M, N, O ], updaterFunction: (value: T[K][L][M][N][O], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): Immutable; - updateIn(propertyPath: string[], updaterFunction: (value: TValue, ...additionalParameters: any[]) => any, ...additionalArguments: any[]): Immutable; + updateIn(propertyPath: string[], updaterFunction: (value: TValue, ...additionalParameters: any[]) => any, ...additionalArguments: any[]): Immutable; without(property: K): Immutable; without(...properties: K[]): Immutable; diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index d89dac0d4a..107e01495a 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -1379,7 +1379,11 @@ declare namespace sequelize { * Should the join model have timestamps */ timestamps?: boolean; - + + /** + * Belongs-To-Many creates a unique key when primary key is not present on through model. This unique key name can be overridden using uniqueKey option. + */ + uniqueKey?: string; } /** diff --git a/types/sha/index.d.ts b/types/sha/index.d.ts index 954036341b..5bde64b12b 100644 --- a/types/sha/index.d.ts +++ b/types/sha/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for sha 2.0 +// Type definitions for sha 3.0 // Project: https://github.com/ForbesLindesay/sha // Definitions by: Oscar Busk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/shipit-utils/index.d.ts b/types/shipit-utils/index.d.ts index 64a62f2d61..6a8582bfad 100644 --- a/types/shipit-utils/index.d.ts +++ b/types/shipit-utils/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import shipit = require("shipit"); +import shipit = require("shipit-cli"); export type GruntOrShipit = typeof shipit | {}; export type EmptyCallback = () => void; diff --git a/types/shipit-utils/shipit-utils-tests.ts b/types/shipit-utils/shipit-utils-tests.ts index 36da5f0073..96bbe2bbdb 100644 --- a/types/shipit-utils/shipit-utils-tests.ts +++ b/types/shipit-utils/shipit-utils-tests.ts @@ -1,4 +1,4 @@ -import shipit = require("shipit"); +import shipit = require("shipit-cli"); import utils = require("shipit-utils"); const originalShipit = utils.getShipit(shipit); diff --git a/types/signale/index.d.ts b/types/signale/index.d.ts index 83a8cbaafb..fd1467adb0 100644 --- a/types/signale/index.d.ts +++ b/types/signale/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for signale 1.2 -// Project: https://github.com/klauscfhq/signale +// Project: https://github.com/klaussinani/signale // Definitions by: Resi Respati // Kingdaro // Joydip Roy diff --git a/types/sinon/index.d.ts b/types/sinon/index.d.ts index 7295119c66..d05495078c 100644 --- a/types/sinon/index.d.ts +++ b/types/sinon/index.d.ts @@ -1618,10 +1618,14 @@ declare namespace Sinon { * * @template TType Type being stubbed. * @param constructor Object or class to stub. + * @param overrides An optional map overriding created stubs * @returns A stubbed version of the constructor. * @remarks The given constructor function is not invoked. See also the stub API. */ - createStubInstance(constructor: StubbableType): SinonStubbedInstance; + createStubInstance( + constructor: StubbableType, + overrides?: { [K in keyof TType]?: any } + ): SinonStubbedInstance; } interface SinonApi { diff --git a/types/sinon/sinon-tests.ts b/types/sinon/sinon-tests.ts index aebe96ae25..9e76b20bbe 100644 --- a/types/sinon/sinon-tests.ts +++ b/types/sinon/sinon-tests.ts @@ -87,6 +87,9 @@ function testSandbox() { const privateFooFoo: sinon.SinonStub = privateFooStubbedInstance.foo; const clsBar: number = stubInstance.bar; const privateFooBar: number = privateFooStubbedInstance.bar; + sb.createStubInstance(cls, { + bar: 1 + }); } function testFakeServer() { diff --git a/types/sinon/ts3.1/index.d.ts b/types/sinon/ts3.1/index.d.ts index 7123e75d49..2157678aaa 100644 --- a/types/sinon/ts3.1/index.d.ts +++ b/types/sinon/ts3.1/index.d.ts @@ -399,7 +399,7 @@ declare namespace Sinon { * The Promise library can be overwritten using the usingPromise method. * Since sinon@2.0.0 */ - resolves(value?: TReturnValue extends Promise ? TResolveValue : never): SinonStub; + resolves(value?: TReturnValue extends PromiseLike ? TResolveValue : never): SinonStub; /** * Causes the stub to return a Promise which resolves to the argument at the provided index. * stub.resolvesArg(0); causes the stub to return a Promise which resolves to the first argument. @@ -1707,11 +1707,14 @@ declare namespace Sinon { * * @template TType Type being stubbed. * @param constructor Object or class to stub. + * @param overrides An optional map overriding created stubs * @returns A stubbed version of the constructor. * @remarks The given constructor function is not invoked. See also the stub API. */ createStubInstance( - constructor: StubbableType + constructor: StubbableType, + overrides?: { [K in keyof TType]?: + SinonStubbedMember | TType[K] extends (...args: any[]) => infer R ? R : TType[K] } ): SinonStubbedInstance; } diff --git a/types/sinon/ts3.1/sinon-tests.ts b/types/sinon/ts3.1/sinon-tests.ts index 2db25348ae..0f07193704 100644 --- a/types/sinon/ts3.1/sinon-tests.ts +++ b/types/sinon/ts3.1/sinon-tests.ts @@ -1,4 +1,5 @@ import sinon = require("sinon"); +import Bluebird = require("bluebird"); function testSandbox() { const obj = {}; @@ -67,7 +68,7 @@ function testSandbox() { sb.replaceSetter(replaceMe, 'setter', (v) => { }); const cls = class { - foo(arg1: string, arg2: number) { return 1; } + foo(arg1: string, arg2: number): number { return 1; } bar: number; }; const PrivateFoo = class { @@ -87,6 +88,10 @@ function testSandbox() { const privateFooFoo: sinon.SinonStub = privateFooStubbedInstance.foo; const clsBar: number = stubInstance.bar; const privateFooBar: number = privateFooStubbedInstance.bar; + sb.createStubInstance(cls, { + foo: (arg1: string, arg2: number) => 2, + bar: 1 + }); } function testFakeServer() { @@ -422,6 +427,7 @@ function testStub() { const obj = class { foo() { } promiseFunc() { return Promise.resolve('foo'); } + promiseLikeFunc() { return {} as any as Bluebird; } }; const instance = new obj(); @@ -430,10 +436,12 @@ function testStub() { const spy: sinon.SinonSpy = stub; - function promiseFunc(n: number) { return Promise.resolve('foo'); } const promiseStub = sinon.stub(instance, 'promiseFunc'); promiseStub.resolves('test'); + const promiseLikeStub = sinon.stub(instance, 'promiseLikeFunc'); + promiseLikeStub.resolves('test'); + sinon.stub(instance); stub.reset(); diff --git a/types/slate-react/index.d.ts b/types/slate-react/index.d.ts index 30e54f2a02..4f7192c4fc 100644 --- a/types/slate-react/index.d.ts +++ b/types/slate-react/index.d.ts @@ -289,7 +289,7 @@ export class Editor extends React.Component implements moveToStartOfPreviousText: CoreEditor['moveToStartOfPreviousText']; moveToStartOfText: CoreEditor['moveToStartOfText']; moveToRangeOfDocument: CoreEditor['moveToRangeOfDocument']; - moveToRangeOf: CoreEditor['moveToRangeOf']; + moveToRangeOfNode: CoreEditor['moveToRangeOfNode']; select: CoreEditor['select']; addMarkAtRange: CoreEditor['addMarkAtRange']; deleteAtRange: CoreEditor['deleteAtRange']; diff --git a/types/slate-react/slate-react-tests.tsx b/types/slate-react/slate-react-tests.tsx index 4f8f55b47b..f4c2ce9df0 100644 --- a/types/slate-react/slate-react-tests.tsx +++ b/types/slate-react/slate-react-tests.tsx @@ -220,7 +220,7 @@ editor .moveToEndOfPreviousText() .moveToEndOfText() .moveToFocus() -.moveToRangeOf(inline) +.moveToRangeOfNode(inline) .moveToRangeOfDocument() .moveToStart() .moveToStartOfBlock() diff --git a/types/slate/index.d.ts b/types/slate/index.d.ts index 567b7ee52e..9b7717e6b8 100644 --- a/types/slate/index.d.ts +++ b/types/slate/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for slate 0.43 +// Type definitions for slate 0.44 // Project: https://github.com/ianstormtaylor/slate // Definitions by: Andy Kent // Jamie Talbot @@ -8,6 +8,7 @@ // Francesco Agnoletto // Irwan Fario Subastian // Hanna Greaves +// Jack Allen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as Immutable from "immutable"; @@ -401,8 +402,6 @@ declare class BaseNode< findDescendants(iterator: (node: Node) => boolean): Node | null; getActiveMarksAtRange(range: Range): Immutable.Set; getAncestors(path: Path): Immutable.List | null; - getBlocksAtRange(range: Range): Immutable.List; - getBlocksAtRangeAsArray(range: Range): Block[]; getBlocks(): Immutable.List; getBlocksAsArray(): Block[]; getBlocksByType(type: string): Immutable.List; @@ -432,6 +431,8 @@ declare class BaseNode< getInsertMarksAtRange(range: Range): Immutable.Set; getKeysToPathsTable(): object; getLastText(): Text | null; + getLeafBlocksAtRange(range: Range): Immutable.List; + getLeafBlocksAtRangeAsArray(range: Range): Block[]; getMarks(): Immutable.Set; getMarksAsArray(): Mark[]; getMarksAtPosition(key: string, offset: number): Immutable.Set; @@ -460,6 +461,8 @@ declare class BaseNode< getPreviousNode(path: Path): Node | null; getPreviousSibling(path: Path): Node | null; getPreviousText(path: Path): Text | null; + getRootBlocksAtRange(range: Range): Immutable.List; + getRootInlinesAtRange(range: Range): Immutable.List; getSelectionIndexes( range: Range, isSelected?: boolean @@ -883,6 +886,8 @@ export type ErrorCode = | "child_required" | "child_type_invalid" | "child_unknown" + | "child_min_invalid" + | "child_max_invalid" | "first_child_object_invalid" | "first_child_type_invalid" | "last_child_object_invalid" @@ -1144,7 +1149,7 @@ export class Editor implements Controller { moveToStartOfPreviousText(): Editor; moveToStartOfText(): Editor; moveToRangeOfDocument(): Editor; - moveToRangeOf(node: Node): Editor; + moveToRangeOfNode(node: Node): Editor; select(properties: Range | RangeProperties): Editor; addMarkAtRange(range: Range, mark: Mark | MarkProperties | string): Editor; deleteAtRange(range: Range): Editor; @@ -1933,7 +1938,7 @@ export interface Controller { /** * Move the current selection's anchor to the start of the provided node and its focus to the end of it. */ - moveToRangeOf(node: Node): Controller; + moveToRangeOfNode(node: Node): Controller; /** * Merge the current selection with the provided properties */ diff --git a/types/slate/slate-tests.ts b/types/slate/slate-tests.ts index 07f15dcaac..0bb2595165 100644 --- a/types/slate/slate-tests.ts +++ b/types/slate/slate-tests.ts @@ -210,7 +210,7 @@ editor .moveToEndOfPreviousText() .moveToEndOfText() .moveToFocus() -.moveToRangeOf(inline) +.moveToRangeOfNode(inline) .moveToRangeOfDocument() .moveToStart() .moveToStartOfBlock() diff --git a/types/solidity-parser-antlr/index.d.ts b/types/solidity-parser-antlr/index.d.ts index 7b92aefb22..7547fd282e 100644 --- a/types/solidity-parser-antlr/index.d.ts +++ b/types/solidity-parser-antlr/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/federicobond/solidity-parser-antlr // Definitions by: Leonid Logvinov // Alex Browne +// Xiao Liang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -13,114 +14,208 @@ export interface Location { start: LineColumn; end: LineColumn; } + +// Note: This should be consistent with the definition of type ASTNode +export type ASTNodeTypeString = 'SourceUnit' +| 'PragmaDirective' +| 'PragmaName' +| 'PragmaValue' +| 'Version' +| 'VersionOperator' +| 'VersionConstraint' +| 'ImportDeclaration' +| 'ImportDirective' +| 'ContractDefinition' +| 'InheritanceSpecifier' +| 'ContractPart' +| 'StateVariableDeclaration' +| 'UsingForDeclaration' +| 'StructDefinition' +| 'ModifierDefinition' +| 'ModifierInvocation' +| 'FunctionDefinition' +| 'ReturnParameters' +| 'ModifierList' +| 'EventDefinition' +| 'EnumValue' +| 'EnumDefinition' +| 'ParameterList' +| 'Parameter' +| 'EventParameterList' +| 'EventParameter' +| 'FunctionTypeParameterList' +| 'FunctionTypeParameter' +| 'VariableDeclaration' +| 'TypeName' +| 'UserDefinedTypeName' +| 'Mapping' +| 'FunctionTypeName' +| 'StorageLocation' +| 'StateMutability' +| 'Block' +| 'Statement' +| 'ExpressionStatement' +| 'IfStatement' +| 'WhileStatement' +| 'SimpleStatement' +| 'ForStatement' +| 'InlineAssemblyStatement' +| 'DoWhileStatement' +| 'ContinueStatement' +| 'BreakStatement' +| 'ReturnStatement' +| 'ThrowStatement' +| 'VariableDeclarationStatement' +| 'IdentifierList' +| 'ElementaryTypeName' +| 'Expression' +| 'PrimaryExpression' +| 'ExpressionList' +| 'NameValueList' +| 'NameValue' +| 'FunctionCallArguments' +| 'AssemblyBlock' +| 'AssemblyItem' +| 'AssemblyExpression' +| 'AssemblyCall' +| 'AssemblyLocalDefinition' +| 'AssemblyAssignment' +| 'AssemblyIdentifierOrList' +| 'AssemblyIdentifierList' +| 'AssemblyStackAssignment' +| 'LabelDefinition' +| 'AssemblySwitch' +| 'AssemblyCase' +| 'AssemblyFunctionDefinition' +| 'AssemblyFunctionReturns' +| 'AssemblyFor' +| 'AssemblyIf' +| 'AssemblyLiteral' +| 'SubAssembly' +| 'TupleExpression' +| 'ElementaryTypeNameExpression' +| 'NumberLiteral' +| 'Identifier' +| 'BinaryOperation' +| 'Conditional'; + export interface BaseASTNode { - type: string; + type: ASTNodeTypeString; range?: [number, number]; loc?: Location; } export interface SourceUnit extends BaseASTNode { + type: 'SourceUnit'; children: ASTNode[]; // TODO: Can be more precise } // tslint:disable-line:no-empty-interface -export interface PragmaDirective extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface PragmaName extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface PragmaValue extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface Version extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface VersionOperator extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface VersionConstraint extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface ImportDeclaration extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface ImportDirective extends BaseASTNode {} // tslint:disable-line:no-empty-interface +export interface PragmaDirective extends BaseASTNode { type: 'PragmaDirective'; } +export interface PragmaName extends BaseASTNode { type: 'PragmaName'; } +export interface PragmaValue extends BaseASTNode { type: 'PragmaValue'; } +export interface Version extends BaseASTNode { type: 'Version'; } +export interface VersionOperator extends BaseASTNode { type: 'VersionOperator'; } +export interface VersionConstraint extends BaseASTNode { type: 'VersionConstraint'; } +export interface ImportDeclaration extends BaseASTNode { type: 'ImportDeclaration'; } +export interface ImportDirective extends BaseASTNode { type: 'ImportDirective'; } export interface ContractDefinition extends BaseASTNode { + type: 'ContractDefinition'; name: string; subNodes: ASTNode[]; // TODO: Can be more precise } -export interface InheritanceSpecifier extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface ContractPart extends BaseASTNode {} // tslint:disable-line:no-empty-interface +export interface InheritanceSpecifier extends BaseASTNode { type: 'InheritanceSpecifier'; } +export interface ContractPart extends BaseASTNode { type: 'ContractPart'; } export interface StateVariableDeclaration extends BaseASTNode { + type: 'StateVariableDeclaration'; variables: VariableDeclaration[]; } -export interface UsingForDeclaration extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface StructDefinition extends BaseASTNode {} // tslint:disable-line:no-empty-interface +export interface UsingForDeclaration extends BaseASTNode { type: 'UsingForDeclaration'; } +export interface StructDefinition extends BaseASTNode { type: 'StructDefinition'; } export interface ModifierDefinition extends BaseASTNode { + type: 'ModifierDefinition'; name: string; } export interface ModifierInvocation extends BaseASTNode { + type: 'ModifierInvocation'; name: string; } export interface FunctionDefinition extends BaseASTNode { + type: 'FunctionDefinition'; name: string; parameters: ParameterList; body: Block | null; } -export interface ReturnParameters extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface ModifierList extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface EventDefinition extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface EnumValue extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface EnumDefinition extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface ParameterList extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface Parameter extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface EventParameterList extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface EventParameter extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface FunctionTypeParameterList extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface FunctionTypeParameter extends BaseASTNode {} // tslint:disable-line:no-empty-interface +export interface ReturnParameters extends BaseASTNode { type: 'ReturnParameters'; } +export interface ModifierList extends BaseASTNode { type: 'ModifierList'; } +export interface EventDefinition extends BaseASTNode { type: 'EventDefinition'; } +export interface EnumValue extends BaseASTNode { type: 'EnumValue'; } +export interface EnumDefinition extends BaseASTNode { type: 'EnumDefinition'; } +export interface ParameterList extends BaseASTNode { type: 'ParameterList'; } +export interface Parameter extends BaseASTNode { type: 'Parameter'; } +export interface EventParameterList extends BaseASTNode { type: 'EventParameterList'; } +export interface EventParameter extends BaseASTNode { type: 'EventParameter'; } +export interface FunctionTypeParameterList extends BaseASTNode { type: 'FunctionTypeParameterList'; } +export interface FunctionTypeParameter extends BaseASTNode { type: 'FunctionTypeParameter'; } export interface VariableDeclaration extends BaseASTNode { + type: 'VariableDeclaration'; visibility: "public" | "private"; isStateVar: boolean; } -export interface TypeName extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface UserDefinedTypeName extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface Mapping extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface FunctionTypeName extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface StorageLocation extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface StateMutability extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface Block extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface Statement extends BaseASTNode {} // tslint:disable-line:no-empty-interface +export interface TypeName extends BaseASTNode { type: 'TypeName'; } +export interface UserDefinedTypeName extends BaseASTNode { type: 'UserDefinedTypeName'; } +export interface Mapping extends BaseASTNode { type: 'Mapping'; } +export interface FunctionTypeName extends BaseASTNode { type: 'FunctionTypeName'; } +export interface StorageLocation extends BaseASTNode { type: 'StorageLocation'; } +export interface StateMutability extends BaseASTNode { type: 'StateMutability'; } +export interface Block extends BaseASTNode { type: 'Block'; } +export interface Statement extends BaseASTNode { type: 'Statement'; } export interface ExpressionStatement extends BaseASTNode { + type: 'ExpressionStatement'; expression: ASTNode; } export interface IfStatement extends BaseASTNode { + type: 'IfStatement'; trueBody: ASTNode; falseBody: ASTNode; } -export interface WhileStatement extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface SimpleStatement extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface ForStatement extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface InlineAssemblyStatement extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface DoWhileStatement extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface ContinueStatement extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface BreakStatement extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface ReturnStatement extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface ThrowStatement extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface VariableDeclarationStatement extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface IdentifierList extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface ElementaryTypeName extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface Expression extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface PrimaryExpression extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface ExpressionList extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface NameValueList extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface NameValue extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface FunctionCallArguments extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyBlock extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyItem extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyExpression extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyCall extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyLocalDefinition extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyAssignment extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyIdentifierOrList extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyIdentifierList extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyStackAssignment extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface LabelDefinition extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblySwitch extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyCase extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyFunctionDefinition extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyFunctionReturns extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyFor extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyIf extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface AssemblyLiteral extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface SubAssembly extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface TupleExpression extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface ElementaryTypeNameExpression extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface NumberLiteral extends BaseASTNode {} // tslint:disable-line:no-empty-interface -export interface Identifier extends BaseASTNode {} // tslint:disable-line:no-empty-interface +export interface WhileStatement extends BaseASTNode { type: 'WhileStatement'; } +export interface SimpleStatement extends BaseASTNode { type: 'SimpleStatement'; } +export interface ForStatement extends BaseASTNode { type: 'ForStatement'; } +export interface InlineAssemblyStatement extends BaseASTNode { type: 'InlineAssemblyStatement'; } +export interface DoWhileStatement extends BaseASTNode { type: 'DoWhileStatement'; } +export interface ContinueStatement extends BaseASTNode { type: 'ContinueStatement'; } +export interface BreakStatement extends BaseASTNode { type: 'BreakStatement'; } +export interface ReturnStatement extends BaseASTNode { type: 'ReturnStatement'; } +export interface ThrowStatement extends BaseASTNode { type: 'ThrowStatement'; } +export interface VariableDeclarationStatement extends BaseASTNode { type: 'VariableDeclarationStatement'; } +export interface IdentifierList extends BaseASTNode { type: 'IdentifierList'; } +export interface ElementaryTypeName extends BaseASTNode { type: 'ElementaryTypeName'; } +export interface Expression extends BaseASTNode { type: 'Expression'; } +export interface PrimaryExpression extends BaseASTNode { type: 'PrimaryExpression'; } +export interface ExpressionList extends BaseASTNode { type: 'ExpressionList'; } +export interface NameValueList extends BaseASTNode { type: 'NameValueList'; } +export interface NameValue extends BaseASTNode { type: 'NameValue'; } +export interface FunctionCallArguments extends BaseASTNode { type: 'FunctionCallArguments'; } +export interface AssemblyBlock extends BaseASTNode { type: 'AssemblyBlock'; } +export interface AssemblyItem extends BaseASTNode { type: 'AssemblyItem'; } +export interface AssemblyExpression extends BaseASTNode { type: 'AssemblyExpression'; } +export interface AssemblyCall extends BaseASTNode { type: 'AssemblyCall'; } +export interface AssemblyLocalDefinition extends BaseASTNode { type: 'AssemblyLocalDefinition'; } +export interface AssemblyAssignment extends BaseASTNode { type: 'AssemblyAssignment'; } +export interface AssemblyIdentifierOrList extends BaseASTNode { type: 'AssemblyIdentifierOrList'; } +export interface AssemblyIdentifierList extends BaseASTNode { type: 'AssemblyIdentifierList'; } +export interface AssemblyStackAssignment extends BaseASTNode { type: 'AssemblyStackAssignment'; } +export interface LabelDefinition extends BaseASTNode { type: 'LabelDefinition'; } +export interface AssemblySwitch extends BaseASTNode { type: 'AssemblySwitch'; } +export interface AssemblyCase extends BaseASTNode { type: 'AssemblyCase'; } +export interface AssemblyFunctionDefinition extends BaseASTNode { type: 'AssemblyFunctionDefinition'; } +export interface AssemblyFunctionReturns extends BaseASTNode { type: 'AssemblyFunctionReturns'; } +export interface AssemblyFor extends BaseASTNode { type: 'AssemblyFor'; } +export interface AssemblyIf extends BaseASTNode { type: 'AssemblyIf'; } +export interface AssemblyLiteral extends BaseASTNode { type: 'AssemblyLiteral'; } +export interface SubAssembly extends BaseASTNode { type: 'SubAssembly'; } +export interface TupleExpression extends BaseASTNode { type: 'TupleExpression'; } +export interface ElementaryTypeNameExpression extends BaseASTNode { type: 'ElementaryTypeNameExpression'; } +export interface NumberLiteral extends BaseASTNode { type: 'NumberLiteral'; } +export interface Identifier extends BaseASTNode { type: 'Identifier'; } export type BinOp = | "+" | "-" @@ -153,11 +248,13 @@ export type BinOp = | "/=" | "%="; export interface BinaryOperation extends BaseASTNode { + type: 'BinaryOperation'; left: ASTNode; right: ASTNode; operator: BinOp; } export interface Conditional extends BaseASTNode { + type: 'Conditional'; trueExpression: ASTNode; falseExpression: ASTNode; } diff --git a/types/spotify-web-playback-sdk/index.d.ts b/types/spotify-web-playback-sdk/index.d.ts index 452da250cd..91e821960c 100644 --- a/types/spotify-web-playback-sdk/index.d.ts +++ b/types/spotify-web-playback-sdk/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Festify Dev Team // Marcus Weiner // Moritz Gunz +// Daniel Almaguer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -118,6 +119,7 @@ declare namespace Spotify { previousTrack(): Promise; resume(): Promise; seek(pos_ms: number): Promise; + setName(name: string): Promise; setVolume(volume: number): Promise; togglePlay(): Promise; } diff --git a/types/spotify-web-playback-sdk/spotify-web-playback-sdk-tests.ts b/types/spotify-web-playback-sdk/spotify-web-playback-sdk-tests.ts index 93956f3138..fd92f5eed5 100644 --- a/types/spotify-web-playback-sdk/spotify-web-playback-sdk-tests.ts +++ b/types/spotify-web-playback-sdk/spotify-web-playback-sdk-tests.ts @@ -45,6 +45,10 @@ player.getVolume().then((volume: number) => { console.log(`The volume of the player is ${volume_percentage}%`); }); +player.setName("New player name").then(() => { + console.log("Player name updated!"); +}); + player.setVolume(0.5).then(() => { console.log("Volume updated!"); }); diff --git a/types/storybook__addon-info/index.d.ts b/types/storybook__addon-info/index.d.ts index 9e5089d443..6adc628c31 100644 --- a/types/storybook__addon-info/index.d.ts +++ b/types/storybook__addon-info/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for @storybook/addon-info 3.4 +// Type definitions for @storybook/addon-info 4.1 // Project: https://github.com/storybooks/storybook, https://github.com/storybooks/storybook/tree/master/addons/info // Definitions by: Mark Kornblum // Mattias Wikstrom +// Kevin Lee // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -22,11 +23,22 @@ export interface Options { propTables?: React.ComponentType[] | false; propTablesExclude?: React.ComponentType[]; styles?: object; + components?: { [key: string]: React.ComponentType }; marksyConf?: object; maxPropsIntoLine?: number; maxPropObjectKeys?: number; maxPropArrayLength?: number; maxPropStringLength?: number; + TableComponent?: React.ComponentType<{ + propDefinitions: Array<{ + property: string; + propType: object | string; // TODO: info about what this object is... + required: boolean; + description: string; + defaultValue: any; + }> + }>; + excludedPropTypes?: string[]; } // TODO: it would be better to use type inference for the parameters diff --git a/types/storybook__addon-info/storybook__addon-info-tests.tsx b/types/storybook__addon-info/storybook__addon-info-tests.tsx index 505780bf7e..0e581c822d 100644 --- a/types/storybook__addon-info/storybook__addon-info-tests.tsx +++ b/types/storybook__addon-info/storybook__addon-info-tests.tsx @@ -6,6 +6,38 @@ import { setDefaults, withInfo } from '@storybook/addon-info'; const { Component } = React; +const TableComponent = ({ propDefinitions }: { propDefinitions: Array<{ + property: string; + propType: { [key: string]: any} | string; + required: boolean; + description: string; + defaultValue: any; +}> }) => ( + + + + + + + + + + + + {propDefinitions.map(row => ( + + + + + + + ))} + +
    propertypropTyperequireddefaultdescription
    {row.property}{row.required ? 'yes' : '-'} + {row.defaultValue === undefined ? '-' : row.defaultValue} + {row.description}
    +); + addDecorator(withInfo); setDefaults({ @@ -31,11 +63,14 @@ storiesOf('Component', module) header: true, source: true, styles: {}, + components: {}, marksyConf: {}, maxPropObjectKeys: 1, maxPropArrayLength: 2, maxPropsIntoLine: 3, maxPropStringLength: 4, + TableComponent, + excludedPropTypes: [], })(() => Click the "?" mark at top-right to view the info. ) diff --git a/types/storybook__addon-storyshots/index.d.ts b/types/storybook__addon-storyshots/index.d.ts index bc265f125c..546386ce40 100644 --- a/types/storybook__addon-storyshots/index.d.ts +++ b/types/storybook__addon-storyshots/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/storybooks/storybook/tree/master/addons/storyshots, https://github.com/storybooks/storybook/tree/master/addons/storyshorts/storyshots-core // Definitions by: Bradley Ayers // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 3.1 import * as React from 'react'; import { StoryObject } from '@storybook/react'; diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index 2b46cbb3af..41e591c839 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -16,6 +16,7 @@ // Simon Schick // Slava Yultyyev // Corey Psoinos +// Saransh Kataria // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -3383,6 +3384,12 @@ declare namespace Stripe { * May only be set if type=service. */ statement_descriptor?: string; + + /** + * A label that represents units of this product, such as seat(s), in Stripe and on customers’ receipts and invoices. + * Only available on products of type=service. + */ + unit_label?: string; } interface IProductUpdateOptions extends IDataOptionsWithMetadata { diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index a7dea63e06..c89b50c86d 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -5,6 +5,7 @@ // Adam Lavin // Jessica Franco // Jason Killian +// Sebastian Silbermann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 @@ -45,9 +46,9 @@ export type StyledProps

    = ThemedStyledProps>; // Wrap in an outer-level conditional type to allow distribution over props that are unions type Defaultize = P extends any ? string extends keyof P ? P : - & Pick> - & Partial>> - & Partial>> + & PickU> + & Partial>> + & Partial>> : never; type ReactDefaultizedProps = C extends { defaultProps: infer D; } @@ -64,13 +65,13 @@ export type StyledComponentProps< // The props that are made optional by .attrs A extends keyof any > = WithOptionalTheme< - Omit< + OmitU< ReactDefaultizedProps< C, React.ComponentPropsWithRef > & O, A - > & Partial & O, A>>, + > & Partial & O, A>>, T > & WithChildrenIfReactComponentClass; @@ -345,8 +346,10 @@ export type ThemedCssFunction = BaseThemedCssFunction< >; // Helper type operators -type Omit = Pick>; -type WithOptionalTheme

    = Omit & { +// Pick that distributes over union types +export type PickU = T extends any ? {[P in K]: T[P]} : never; +export type OmitU = T extends any ? PickU> : never; +type WithOptionalTheme

    = OmitU & { theme?: T; }; type AnyIfEmpty = keyof T extends never ? any : T; diff --git a/types/styled-components/test/index.tsx b/types/styled-components/test/index.tsx index a37c33f315..067cdc7d89 100644 --- a/types/styled-components/test/index.tsx +++ b/types/styled-components/test/index.tsx @@ -1030,3 +1030,32 @@ const WrapperFunc = (props: WrapperProps) =>

    ; const StyledWrapperFunc = styled(WrapperFunc)``; // No `children` in props, so this should generate an error const wrapperFunc = Text; // $ExpectError + +function unionTest() { + interface Book { + kind: 'book'; + author: string; + } + + interface Magazine { + kind: 'magazine'; + issue: number; + } + + type SomethingToRead = (Book | Magazine); + + const Readable: React.FunctionComponent = props => { + if (props.kind === 'magazine') { + return
    magazine #{props.issue}
    ; + } + + return
    magazine #{props.author}
    ; + }; + + const StyledReadable = styled(Readable)` + font-size: ${props => props.kind === 'book' ? 16 : 14} + `; + + ; + ; // $ExpectError +} diff --git a/types/superagent/index.d.ts b/types/superagent/index.d.ts index 7915277b37..de09e3ae7b 100644 --- a/types/superagent/index.d.ts +++ b/types/superagent/index.d.ts @@ -7,6 +7,7 @@ // Alec Zopf // Adam Haglund // Lukas Elmer +// Jesse Rogers // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -116,6 +117,7 @@ declare namespace request { type: string; unauthorized: boolean; xhr: XMLHttpRequest; + redirects: string[]; } interface Request extends Promise { diff --git a/types/superagent/superagent-tests.ts b/types/superagent/superagent-tests.ts index b261a551d7..e7b032907a 100644 --- a/types/superagent/superagent-tests.ts +++ b/types/superagent/superagent-tests.ts @@ -202,6 +202,7 @@ request('/search') const contentLength = res.header['content-length']; const contentType: string = res.type; const charset: string = res.charset; + const redirects: string[] = res.redirects; }); // Getting response 'Set-Cookie' diff --git a/types/superagent/v2/index.d.ts b/types/superagent/v2/index.d.ts index 52ee4a149f..140ae0aefc 100644 --- a/types/superagent/v2/index.d.ts +++ b/types/superagent/v2/index.d.ts @@ -89,6 +89,7 @@ declare namespace request { forbidden: boolean; xhr: XMLHttpRequest; get(header: string): string; + redirects: string[]; } interface Request extends Promise /* extends NodeJS.WritableStream */ { diff --git a/types/superagent/v2/superagent-tests.ts b/types/superagent/v2/superagent-tests.ts index e0f0fcc592..a9ff954e4d 100644 --- a/types/superagent/v2/superagent-tests.ts +++ b/types/superagent/v2/superagent-tests.ts @@ -181,6 +181,7 @@ request('/search') const contentLength = res.header['content-length']; const contentType: string = res.type; const charset: string = res.charset; + const redirects: string[] = res.redirects; }); // Custom parsers diff --git a/types/swagger-schema-official/index.d.ts b/types/swagger-schema-official/index.d.ts index 09d31cc8e7..11cfd05520 100644 --- a/types/swagger-schema-official/index.d.ts +++ b/types/swagger-schema-official/index.d.ts @@ -47,24 +47,29 @@ export interface BaseParameter { } export interface BodyParameter extends BaseParameter { + in: 'body'; schema?: Schema; } export interface QueryParameter extends BaseParameter, BaseSchema { + in: 'query'; type: string; allowEmptyValue?: boolean; } export interface PathParameter extends BaseParameter, BaseSchema { + in: 'path'; type: string; required: boolean; } export interface HeaderParameter extends BaseParameter, BaseSchema { + in: 'header'; type: string; } export interface FormDataParameter extends BaseParameter, BaseSchema { + in: 'formData'; type: string; collectionFormat?: string; allowEmptyValue?: boolean; diff --git a/types/swagger-schema-official/swagger-schema-official-tests.ts b/types/swagger-schema-official/swagger-schema-official-tests.ts index 4fb3e55f07..4d46e4aa86 100644 --- a/types/swagger-schema-official/swagger-schema-official-tests.ts +++ b/types/swagger-schema-official/swagger-schema-official-tests.ts @@ -1373,7 +1373,6 @@ const reference_support: swagger.Spec = { { "in": "body", "name": "bodyParameter", - "type": "string", "description": "The body parameter" } ], diff --git a/types/theo/index.d.ts b/types/theo/index.d.ts index de15c0238a..dc67721b95 100644 --- a/types/theo/index.d.ts +++ b/types/theo/index.d.ts @@ -93,10 +93,10 @@ export function registerFormat( name: Format | T, format: FormatResultFn | string ): void; -export function registerTransform( - name: Transform | T, - valueTransforms: ValueTransform[] | T[] -): void; +export function registerTransform< + T extends string = never, + V extends string = never +>(name: Transform | T, valueTransforms: ValueTransform[] | V[]): void; export function registerValueTransform( name: ValueTransform | T, predicate: (prop: Prop) => boolean, diff --git a/types/theo/theo-tests.ts b/types/theo/theo-tests.ts index ceaaf9649c..c854fc0dc3 100644 --- a/types/theo/theo-tests.ts +++ b/types/theo/theo-tests.ts @@ -11,8 +11,30 @@ theo.convert({ } }); +theo.convertSync({ + transform: { + type: "raw", + file: "file", + data: "data" + }, + format: { + type: "custom-properties.css" + } +}); + +// Register a provided transform with a provided value transform +theo.registerTransform("web", ["color/hex"]); + +// Register a provided transform with custom value transform theo.registerTransform("web", ["relative/pixelValue"]); +// Register a custom transform with custom value transform +theo.registerTransform("custom", ["relative/pixelValue"]); + +// Register a custom transform with provided value transform +theo.registerTransform("custom", ["color/rgb"]); + +// Register custom formatting function for a provided format theo.registerFormat( "cssmodules.css", `{{#each props as |prop|}} @@ -20,6 +42,7 @@ theo.registerFormat( {{/each}}` ); +// Register a custom value transform theo.registerValueTransform( "relative/pixelValue", prop => prop.get("category") === "sizing", @@ -28,3 +51,13 @@ theo.registerValueTransform( return parseFloat(value.replace(/rem/g, "")) * 16; } ); + +// Override a custom value transform +theo.registerValueTransform( + "relative/pixel", + prop => prop.get("category") === "sizing", + prop => { + const value = prop.get("value").toString(); + return `${parseFloat(value.replace(/rem/g, "")) * 16}px`; + } +); diff --git a/types/toastr/index.d.ts b/types/toastr/index.d.ts index 8d5d163f7b..847cb2e7fc 100644 --- a/types/toastr/index.d.ts +++ b/types/toastr/index.d.ts @@ -320,10 +320,19 @@ interface Toastr { (toast: JQuery, clearOptions: {force: boolean}): void; }; /** - * Removes all toasts (without animation) + * Removes toasts (without animation) */ remove: { + /** + * Removes all toasts (without animation) + */ (): void; + /** + * Removes specific toast (without animation) + * + * @param toast Toast to remove + */ + (toast: JQuery): void; }; /** * Create an error toast diff --git a/types/tokenizr/index.d.ts b/types/tokenizr/index.d.ts new file mode 100644 index 0000000000..1b1615e1b8 --- /dev/null +++ b/types/tokenizr/index.d.ts @@ -0,0 +1,268 @@ +// Type definitions for tokenizr 1.5 +// Project: https://github.com/rse/tokenizr +// Definitions by: Nicholas Sorokin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Tokenizr { + constructor(); + + /** + * Configure a tokenization after-rule callback + */ + after(action: Action): this; + + /** + * Execute multiple alternative callbacks + */ + alternatives(...alternatives: Array<(this: this) => any>): any; + + /** + * Configure a tokenization before-rule callback + */ + before(action: Action): this; + + /** + * Open tokenization transaction + */ + begin(): this; + + /** + * Close (successfully) tokenization transaction + */ + commit(): this; + + /** + * Consume the current token (by expecting it to be a particular symbol) + */ + consume(type: string, value: any): Token; + + /** + * Configure debug operation + */ + debug(enableDebug: boolean): this; + + /** + * Determine depth of still open tokenization transaction + */ + depth(): number; + + /** + * Create an error message for the current position + */ + error(message?: string): ParsingError; + + /** + * Configure a tokenization finish callback + */ + finish(action: (this: ActionContext, ctx: ActionContext) => void): this; + + /** + * Provide (new) input string to tokenize + */ + input(input: string): this; + + /** + * Peek at the next token or token at particular offset + */ + peek(offset?: number): Token; + + /** + * Pop state + */ + pop(): string; + + /** + * Push state + */ + push(state: string): this; + + /** + * Reset the internal state + */ + reset(): this; + + /** + * Close (unsuccessfully) tokenization transaction + */ + rollback(): this; + + /** + * Configure a tokenization rule + */ + rule(pattern: RegExp, action: RuleAction, name?: string): this; + rule( + state: string, + pattern: RegExp, + action: RuleAction, + name: string + ): this; + + /** + * Skip one or more tokens + */ + skip(len?: number): this; + + /** + * Get/set state + */ + state(): string; + /** + * Replaces the current state + */ + state(state: string): this; + + /** + * Set a tag + */ + tag(tag: string): this; + + /** + * Check whether tag is set + */ + tagged(tag: string): boolean; + + /** + * Determine and return next token + */ + token(): Token | null; + + /** + * Determine and return all tokens + */ + tokens(): Token[]; + + /** + * Unset a tag + */ + untag(tag: string): this; + + static readonly ParsingError: typeof ParsingError; + static readonly ActionContext: typeof ActionContext; + static readonly Token: typeof Token; +} + +type Action = ( + this: ActionContext, + ctx: ActionContext, + found: RegExpExecArray, + rule: { + state: string; + pattern: RegExp; + action: RuleAction; + name: string; + } +) => void; + +type RuleAction = ( + this: ActionContext, + ctx: ActionContext, + found: RegExpExecArray +) => void; + +declare class ActionContext { + constructor(e: any); + + /** + * Accept current matching as a new token + */ + accept(type: string, value?: any): this; + + /** + * Store and retrieve user data attached to context + */ + data(key: string, value?: any): any; + + /** + * Mark current matching to be ignored + */ + ignore(): this; + + /** + * Retrieve information of current matching + */ + info(): { line: number; column: number; pos: number; len: number }; + + /** + * Pop state + */ + pop(): string; + + /** + * Push state + */ + push(state: string): this; + + /** + * Rark current matching to be rejected + */ + reject(): this; + + /** + * Mark current matching to be repeated from scratch + */ + repeat(): this; + + /** + * Get/set state + */ + state(): string; + /** + * Replaces the current state + */ + state(state: string): this; + + /** + * Immediately stop tokenization + */ + stop(): this; + + /** + * Set a tag + */ + tag(tag: string): this; + + /** + * Check whether tag is set + */ + tagged(tag: string): boolean; + + /** + * Unset a tag + */ + untag(tag: string): this; +} + +declare class ParsingError extends Error { + constructor( + message: string, + pos: number, + line: number, + column: number, + input: string + ); + + /** + * Render a useful string representation + */ + toString(): string; +} + +declare class Token { + constructor( + type: string, + value: any, + text: string, + pos?: number, + line?: number, + column?: number + ); + + isA(type: string, value?: any): boolean; + + /** + * Render a useful string representation + */ + toString(): string; +} + +export = Tokenizr; diff --git a/types/tokenizr/tokenizr-tests.ts b/types/tokenizr/tokenizr-tests.ts new file mode 100644 index 0000000000..a633a14a75 --- /dev/null +++ b/types/tokenizr/tokenizr-tests.ts @@ -0,0 +1,42 @@ +import Tokenizr = require('tokenizr'); + +const lexer = new Tokenizr(); + +lexer.rule(/[a-zA-Z_][a-zA-Z0-9_]*/, (ctx, match) => { + ctx.accept('id'); +}); + +lexer.rule(/[+-]?[0-9]+/, (ctx, match) => { + ctx.accept('number', parseInt(match[0], 10)); +}); + +lexer.rule(/"((?:\\"|[^\r\n])*)"/, (ctx, match) => { + ctx.accept('string', match[1].replace(/\\"/g, '"')); +}); + +lexer.rule(/\/\/[^\r\n]*\r?\n/, (ctx, match) => { + ctx.ignore(); +}); + +lexer.rule(/[ \t\r\n]+/, (ctx, match) => { + ctx.ignore(); +}); + +lexer.rule(/./, (ctx, match) => { + ctx.accept('char'); +}); + +const cfg = `foo { + baz = 1 // sample comment + bar { + quux = 42 + hello = "hello \"world\"!" + } + quux = 7 +}`; + +lexer.input(cfg); +lexer.debug(true); +lexer.tokens().forEach(token => { + // ... +}); diff --git a/types/tokenizr/tsconfig.json b/types/tokenizr/tsconfig.json new file mode 100644 index 0000000000..7b24906172 --- /dev/null +++ b/types/tokenizr/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "tokenizr-tests.ts"] +} diff --git a/types/tokenizr/tslint.json b/types/tokenizr/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/tokenizr/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/transducers-js/transducers-js-tests.ts b/types/transducers-js/transducers-js-tests.ts index 3e69ae06ed..f0f5facf41 100644 --- a/types/transducers-js/transducers-js-tests.ts +++ b/types/transducers-js/transducers-js-tests.ts @@ -161,12 +161,12 @@ function advancedIntoExample() { const string: string = into("", t.map((s: string) => s + s), ["a", "b"]); const object1: { [key: string]: number } = into( {}, - t.map((s: string) => [s, s.length]), + t.map((s: string) => [s, s.length] as [string, number]), ["a", "b"], ); const object2: { [key: string]: boolean } = into( {}, - t.map((kv: [string, number]) => [kv[0], true]), + t.map((kv: [string, number]) => [kv[0], true] as [string, boolean]), { a: 1, b: 2 } ); } diff --git a/types/vexflow/index.d.ts b/types/vexflow/index.d.ts index c25ac00958..2840f35872 100644 --- a/types/vexflow/index.d.ts +++ b/types/vexflow/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for VexFlow v1.2.85 +// Type definitions for VexFlow v1.2.88 // Project: http://vexflow.com // Definitions by: Roman Quiring // Sebastian Haas // Basti Hoffmann // Simon Schmid +// Benjamin Giesinger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped //inconsistent namespace: this is a helper funtion from tables.js and should not pollute the global namespace! @@ -54,8 +55,8 @@ declare namespace Vex { beginPath() : IRenderContext; moveTo(x : number, y : number) : IRenderContext; lineTo(x : number, y : number) : IRenderContext; - bezierCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : IRenderContext; - quadraticCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number) : IRenderContext; + bezierCurveTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : IRenderContext; + quadraticCurveTo(x1 : number, y1 : number, x2 : number, y2 : number) : IRenderContext; arc(x : number, y : number, radius : number, startAngle : number, endAngle : number, antiClockwise : boolean) : IRenderContext; glow() : IRenderContext; fill() : IRenderContext; @@ -103,6 +104,7 @@ declare namespace Vex { const STAVE_LINE_THICKNESS : number; const TIME4_4 : {num_beats : number, beat_value : number, resolution : number}; const unicode : {[name : string] : string}; //inconsistent API: this should be private and have a wrapper function like the other tables + const DEFAULT_NOTATION_FONT_SCALE: number; function clefProperties(clef : string) : {line_shift : number}; function keyProperties(key : string, clef : string, params : {octave_shift? : number}) : {key : string, octave : number, line : number, int_value : number, accidental : string, code : number, stroke : number, shift_right : number, displaced : boolean}; function integerToNote(integer : number) : string; @@ -211,8 +213,9 @@ declare namespace Vex { drawRepeatBar(stave : Stave, x : number, begin : boolean) : void; } - class Beam { + class Beam { constructor(notes : StemmableNote[], auto_stem? : boolean); + setStyle(style : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}) : Beam; setContext(context : IRenderContext) : Beam; getNotes() : StemmableNote[]; getBeamCount() : number; @@ -275,8 +278,8 @@ declare namespace Vex { beginPath() : CanvasContext; moveTo(x : number, y : number) : CanvasContext; lineTo(x : number, y : number) : CanvasContext; - bezierCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : CanvasContext; - quadraticCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number) : CanvasContext; + bezierCurveTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : CanvasContext; + quadraticCurveTo(x1 : number, y1 : number, x2 : number, y2 : number) : CanvasContext; arc(x : number, y : number, radius : number, startAngle : number, endAngle : number, antiClockwise : boolean) : CanvasContext; glow() : CanvasContext; fill() : CanvasContext; @@ -438,8 +441,9 @@ declare namespace Vex { } class FretHandFinger extends Modifier { - constructor(number : number); + constructor(number : number|string); static format(nums : FretHandFinger[], state : {left_shift : number, right_shift : number, text_line : number}) : void; + finger: number|string; getNote() : Note; setNote(note : Note) : FretHandFinger; getIndex() : number; @@ -488,11 +492,16 @@ declare namespace Vex { class GraceNote extends StaveNote { constructor(note_struct : {slash? : boolean, type? : string, dots? : number, duration : string, clef? : string, keys : string[], octave_shift? : number, auto_stem? : boolean, stem_direction? : number}); + static LEDGER_LINE_OFFSET : number; getStemExtension() : number; getCategory() : string; draw() : void; } + namespace GraceNote { + const SCALE : number; + } + class GraceNoteGroup extends Modifier { //TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed setWidth(width : number) : Modifier; @@ -621,7 +630,8 @@ declare namespace Vex { getTickMultiplier() : Fraction; applyTickMultiplier(numerator : number, denominator : number) : void; setDuration(duration : Fraction) : void; - + preFormatted : boolean; + constructor(note_struct : {type? : string, dots? : number, duration : string}); getPlayNote() : any; setPlayNote(note : any) : Note; @@ -757,8 +767,8 @@ declare namespace Vex { beginPath() : RaphaelContext; moveTo(x : number, y : number) : RaphaelContext; lineTo(x : number, y : number) : RaphaelContext; - bezierCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : RaphaelContext; - quadraticCurveToTo(x1 : number, y1 : number, x : number, y : number) : RaphaelContext; //inconsistent name: x, y -> x2, y2 + bezierCurveTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : RaphaelContext; + quadraticCurveTo(x1 : number, y1 : number, x : number, y : number) : RaphaelContext; //inconsistent name: x, y -> x2, y2 arc(x : number, y : number, radius : number, startAngle : number, endAngle : number, antiClockwise : boolean) : RaphaelContext; glow() : {width : number, fill : boolean, opacity : number, offsetx : number, offsety : number, color : string}; //inconsistent type : Object -> RaphaelContext fill() : RaphaelContext; @@ -805,6 +815,7 @@ declare namespace Vex { class Stave { constructor(x : number, y : number, width : number, options? : {vertical_bar_width? : number, glyph_spacing_px? : number, num_lines? : number, fill_style? : string, spacing_between_lines_px? : number, space_above_staff_ln? : number, space_below_staff_ln? : number, top_text_position? : number}); + options: {vertical_bar_width? : number, glyph_spacing_px? : number, num_lines? : number, fill_style? : string, left_bar? : boolean, right_bar? : boolean, spacing_between_lines_px? : number, space_above_staff_ln? : number, space_below_staff_ln? : number, top_text_position? : number}; resetLines() : void; setNoteStartX(x : number) : Stave; getNoteStartX() : number; @@ -827,7 +838,7 @@ declare namespace Vex { setRepetitionTypeRight(type : Repetition.type, y : number) : Stave; setVoltaType(type : Volta.type, number_t : number, y : number) : Stave; setSection(section : string, y : number) : Stave; - setTempo(tempo : {name? : string, duration : string, dots : number, bpm : number}, y : number) : Stave; + setTempo(tempo : {name? : string, duration : string, dots : boolean, bpm : number}, y : number) : Stave; setText(text : string, position : Modifier.Position, options? : {shift_x? : number, shift_y? : number, justification? : TextNote.Justification}) : Stave; getHeight() : number; getSpacingBetweenLines() : number; @@ -858,10 +869,15 @@ declare namespace Vex { getConfigForLines() : {visible : boolean}[]; setConfigForLine(line_number : number, line_config : {visible : boolean}) : Stave; setConfigForLines(lines_configuration : {visible : boolean}[]) : Stave; + getModifiers(position? : number, category? : string) : StaveModifier[]; } class StaveConnector { constructor(top_stave : Stave, bottom_stave : Stave); + top_stave : Stave; + bottom_stave : Stave; + thickness : number; + x_shift : number; setContext(ctx : IRenderContext) : StaveConnector; setType(type : StaveConnector.type) : StaveConnector; setText(text : string, text_options? : {shift_x? : number, shift_y? : number}) : StaveConnector; @@ -918,6 +934,9 @@ declare namespace Vex { addToStaveEnd(stave : Stave, firstGlyph : boolean) : StaveModifier; addModifier() : void; addEndModifier() : void; + getPosition() : number; + getWidth() : number; + getPadding(index: number) : number; } namespace StaveModifier { @@ -929,10 +948,13 @@ declare namespace Vex { //TODO remove the following lines once TypeScript allows subclass overrides with type changes and/or inconsistencies mentioned below are fixed buildStem() : StemmableNote; setStave(stave : Stave) : Note; - addModifier(modifier : Modifier, index? : number) : Note; + //TODO: vexflow actualy managed to have Note use modifier, index and stavenote index,modifier. To use the function in + // Typescript we need to allow both. The name is the correct type :( + addModifier(index : any, modifier? : any) : Note; getModifierStartXY() : {x : number, y : number}; getDots() : number; - + x_shift: number; + constructor(note_struct : {type? : string, dots? : number, duration : string, clef? : string, keys : string[], octave_shift? : number, auto_stem? : boolean, stem_direction? : number}); static DEBUG : boolean; static format(notes : StaveNote[] , state : {left_shift : number, right_shift : number, text_line : number}) : boolean; @@ -959,11 +981,11 @@ declare namespace Vex { getLineForRest() : number; getModifierStartXY(position : Modifier.Position, index : number) : {x : number, y : number}; setStyle(style : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}) : void; // inconsistent type: void -> StaveNote + setStemStyle(style : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}) : void; setKeyStyle(index : number, style : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}) : StaveNote; setKeyLine(index : number, line : number) : StaveNote; getKeyLine(index : number) : number; addToModifierContext(mContext : ModifierContext) : StaveNote; - addModifier(index : number, modifier : Modifier) : StaveNote; addAccidental(index : number, accidental : Accidental) : StaveNote; addArticulation(index : number, articulation : Articulation) : StaveNote; addAnnotation(index : number, annotation : Annotation) : StaveNote; @@ -1084,6 +1106,9 @@ declare namespace Vex { constructor(note_struct : {type? : string, dots? : number, duration : string}); static DEBUG : boolean; + flag: Glyph; + getAttribute(attr : string) : any; + setFlagStyle(style_struct : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}) : void; getStem() : Stem; setStem(stem : Stem) : StemmableNote; buildStem() : StemmableNote; @@ -1108,8 +1133,11 @@ declare namespace Vex { //TODO remove the following lines once TypeScript allows subclass overrides with type changes setNote(note : Note) : StringNumber; - constructor(number : number); + // actually this is not really consistent in the vexflow code "ctx.measureText(this.string_number).width" looks + // like it is a string. But from the use of it it might be a number ?! + constructor(number : number|string); static format(nums : StringNumber[], state : {left_shift : number, right_shift : number, text_line : number}) : boolean; + string_number : number|string; getNote() : Note; setNote(note : StemmableNote) : StringNumber; getIndex() : number; @@ -1130,7 +1158,7 @@ declare namespace Vex { } class Stroke extends Modifier { - constructor(type : Stroke.Type, options : {all_voices? : boolean}); + constructor(type : Stroke.Type, options? : {all_voices? : boolean}); static format(strokes : Stroke[], state : {left_shift : number, right_shift : number, text_line : number}) : boolean; getPosition() : Modifier.Position; addEndNote(note : Note) : Stroke; @@ -1138,14 +1166,18 @@ declare namespace Vex { } namespace Stroke { - const enum Type {BRUSH_DOWN = 1, BRUSH_UP, ROLL_DOWN, ROLL_UP, RASQUEDO_DOWN, RASQUEDO_UP} + const enum Type {BRUSH_DOWN = 1, BRUSH_UP, ROLL_DOWN, ROLL_UP, RASQUEDO_DOWN, RASQUEDO_UP, ARPEGGIO_DIRECTIONLESS} const CATEGORY : string; } class SVGContext implements IRenderContext { constructor(element : HTMLElement); + svg: SVGElement; + state: any; + attributes: any; + lineWidth: number; iePolyfill() : boolean; - setFont(family : string, size : number, weight? : number) : SVGContext; + setFont(family : string, size : number, weight? : number|string) : SVGContext; setRawFont(font : string) : SVGContext; setFillStyle(style : string) : SVGContext; setBackgroundFillStyle(style : string) : SVGContext; @@ -1165,8 +1197,8 @@ declare namespace Vex { beginPath() : SVGContext; moveTo(x : number, y : number) : SVGContext; lineTo(x : number, y : number) : SVGContext; - bezierCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : SVGContext; - quadraticCurveToTo(x1 : number, y1 : number, x : number, y : number) : SVGContext; //inconsistent: x, y -> x2, y2 + bezierCurveTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : SVGContext; + quadraticCurveTo(x1 : number, y1 : number, x : number, y : number) : SVGContext; //inconsistent: x, y -> x2, y2 arc(x : number, y : number, radius : number, startAngle : number, endAngle : number, antiClockwise : boolean) : SVGContext; closePath() : SVGContext; glow() : SVGContext; @@ -1236,6 +1268,9 @@ declare namespace Vex { class TextBracket { constructor(bracket_data : {start : Note, stop : Note, text? : string, superscript? : string, position? : TextBracket.Positions}); static DEBUG : boolean; + start : Note; + stop : Note; + position : TextBracket.Positions; applyStyle(context : IRenderContext) : TextBracket; setDashed(dashed : boolean, dash? : number[]) : TextBracket; setFont(font : {family : string, size : number, weight : string}) : TextBracket; @@ -1372,7 +1407,7 @@ declare namespace Vex { } class Tuplet { - constructor(notes : StaveNote[], options? : {num_notes? : number, beats_occupied? : number}); + constructor(notes : StaveNote[], options? : {location? : number, bracketed? : boolean, ratioed : boolean, num_notes? : number, notes_occupied? : number, y_offset? : number}); attach() : void; detach() : void; setContext(context : IRenderContext) : Tuplet; diff --git a/types/wait-for-localhost/index.d.ts b/types/wait-for-localhost/index.d.ts deleted file mode 100644 index 080c8a800c..0000000000 --- a/types/wait-for-localhost/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for wait-for-localhost 2.0 -// Project: https://github.com/sindresorhus/wait-for-localhost#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = waitForLocalhost; - -declare function waitForLocalhost(port?: number): Promise; diff --git a/types/wait-for-localhost/wait-for-localhost-tests.ts b/types/wait-for-localhost/wait-for-localhost-tests.ts deleted file mode 100644 index 95d43efee2..0000000000 --- a/types/wait-for-localhost/wait-for-localhost-tests.ts +++ /dev/null @@ -1,5 +0,0 @@ -import waitForLocalhost = require('wait-for-localhost'); - -// $ExpectType Promise -waitForLocalhost(); -waitForLocalhost(8080); diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 1c423c428c..fe3dc638e1 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -610,6 +610,8 @@ declare namespace webpack { name?: boolean | string | ((...args: any[]) => any); /** Assign modules to a cache group (modules from different cache groups are tried to keep in separate chunks) */ cacheGroups?: false | string | ((...args: any[]) => any) | RegExp | { [key: string]: CacheGroupsOptions | false }; + /** Override the default name separator (~) when generating names automatically (name: true) */ + automaticNameDelimiter?: string; } interface RuntimeChunkOptions { /** The name or name factory for the runtime chunks. */ diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index 8c06b3de10..e2a9c7a5fb 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -87,16 +87,14 @@ declare namespace wx { * @version 1.4.0 */ onProgressUpdate( - callback?: ( - res: { - /** 上传进度百分比 */ - progress: number; - /** 已经上传的数据长度,单位 Bytes */ - totalBytesSent: number; - /** 预期需要上传的数据总长度,单位 Bytes */ - totalBytesExpectedToSend: number; - } - ) => void + callback?: (res: { + /** 上传进度百分比 */ + progress: number; + /** 已经上传的数据长度,单位 Bytes */ + totalBytesSent: number; + /** 预期需要上传的数据总长度,单位 Bytes */ + totalBytesExpectedToSend: number; + }) => void ): void; /** * 中断下载任务 @@ -135,16 +133,14 @@ declare namespace wx { * @version 1.4.0 */ onProgressUpdate( - callback?: ( - res: { - /** 下载进度百分比 */ - progress: number; - /** 已经下载的数据长度,单位 Bytes */ - totalBytesWritten: number; - /** 预期需要下载的数据总长度,单位 Bytes */ - totalBytesExpectedToWrite: number; - } - ) => void + callback?: (res: { + /** 下载进度百分比 */ + progress: number; + /** 已经下载的数据长度,单位 Bytes */ + totalBytesWritten: number; + /** 预期需要下载的数据总长度,单位 Bytes */ + totalBytesExpectedToWrite: number; + }) => void ): void; /** * 中断下载任务 @@ -1147,12 +1143,7 @@ declare namespace wx { * @version 1.1.0 */ function onNetworkStatusChange( - callback: ( - res: { - isConnected: boolean; - networkType: networkType; - } - ) => void + callback: (res: { isConnected: boolean; networkType: networkType }) => void ): void; // 设备-----加速度计 interface AccelerometerData { @@ -1391,11 +1382,7 @@ declare namespace wx { * @version 1.1.0 */ function onBluetoothDeviceFound( - callback: ( - res: { - devices: BluetoothDevice[]; - } - ) => void + callback: (res: { devices: BluetoothDevice[] }) => void ): void; interface GetConnectedBluetoothDevicesOptions extends BaseOptions { services: string[]; @@ -1604,43 +1591,39 @@ declare namespace wx { * 监听低功耗蓝牙连接的错误事件,包括设备丢失,连接异常断开等等。 */ function onBLEConnectionStateChanged( - callback: ( - res: { - /** - * 蓝牙设备 id,参考 device 对象 - */ - deviceId: string; - /** - * 连接目前的状态 - */ - connected: boolean; - } - ) => void + callback: (res: { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 连接目前的状态 + */ + connected: boolean; + }) => void ): void; /** * 监听低功耗蓝牙设备的特征值变化。必须先启用notify接口才能接收到设备推送的notification。 */ function onBLECharacteristicValueChange( - callback: ( - res: { - /** - * 蓝牙设备 id,参考 device 对象 - */ - deviceId: string; - /** - * 特征值所属服务 uuid - */ - serviceId: string; - /** - * 特征值 uuid - */ - characteristicId: string; - /** - * 特征值最新的值 - */ - value: ArrayBuffer; - } - ) => void + callback: (res: { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 特征值所属服务 uuid + */ + serviceId: string; + /** + * 特征值 uuid + */ + characteristicId: string; + /** + * 特征值最新的值 + */ + value: ArrayBuffer; + }) => void ): void; // #region iBeacon interface StartBeaconDiscoveryOptions extends BaseOptions { @@ -3729,9 +3712,9 @@ declare namespace wx { type DefaultProps = object | Record; - type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (( - k: infer I, - ) => void) + type UnionToIntersection = (U extends any + ? (k: U) => void + : never) extends ((k: infer I) => void) ? I : never; @@ -3743,20 +3726,26 @@ declare namespace wx { __DO_NOT_USE_INTERNAL_FIELD_METHODS: Methods; } - type UnboxBehaviorData = T extends Behavior<{}, {}, {}> ? T['__DO_NOT_USE_INTERNAL_FIELD_DATA'] : {}; - type UnboxBehaviorProps = T extends Behavior<{}, {}, {}> ? T['__DO_NOT_USE_INTERNAL_FIELD_PROPS'] : {}; - type UnboxBehaviorMethods = T extends Behavior<{}, {}, {}> ? T['__DO_NOT_USE_INTERNAL_FIELD_METHODS'] : {}; + type UnboxBehaviorData = T extends Behavior<{}, {}, {}> + ? T["__DO_NOT_USE_INTERNAL_FIELD_DATA"] + : {}; + type UnboxBehaviorProps = T extends Behavior<{}, {}, {}> + ? T["__DO_NOT_USE_INTERNAL_FIELD_PROPS"] + : {}; + type UnboxBehaviorMethods = T extends Behavior<{}, {}, {}> + ? T["__DO_NOT_USE_INTERNAL_FIELD_METHODS"] + : {}; - type UnboxBehaviorsMethods< - Behaviors extends Array | string> + type UnboxBehaviorsMethods< + Behaviors extends Array | string> > = UnboxBehaviorMethods>>; - type UnboxBehaviorsData< - Behaviors extends Array | string> + type UnboxBehaviorsData< + Behaviors extends Array | string> > = UnboxBehaviorData>>; - type UnboxBehaviorsProps< - Behaviors extends Array | string> + type UnboxBehaviorsProps< + Behaviors extends Array | string> > = UnboxBehaviorProps>>; // CombinedInstance models the `this`, i.e. instance type for (user defined) component @@ -3765,7 +3754,7 @@ declare namespace wx { Data, Methods, Props, - Behaviors extends Array | string> + Behaviors extends Array | string> > = Methods & Instance & UnboxBehaviorsMethods; type Prop = (() => T) | { new (...args: any[]): T & object }; @@ -3791,6 +3780,13 @@ declare namespace wx { type PropsDefinition = ArrayPropsDefinition | RecordPropsDefinition; + /** + * https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/observer.html + */ + interface ObserversDefs { + [expression: string]: (this: V, ...fields: any[]) => any; + } + interface ComponentRelation { /** 目标组件的相对关系,可选的值为 parent 、 child 、 ancestor 、 descendant */ type: "parent" | "child" | "ancestor" | "descendant"; @@ -3808,7 +3804,7 @@ declare namespace wx { Data, Methods, Props, - Behaviors extends Array | string> + Behaviors extends Array | string> > = object & ComponentOptions & ThisType, Behaviors>>; @@ -3872,7 +3868,7 @@ declare namespace wx { Data = DefaultData, Methods = DefaultMethods, Props = PropsDefinition, - Behaviors extends Array | string> = [] + Behaviors extends Array | string> = [] > extends Partial { /** * 组件的对外属性,是属性名到属性设置的映射表 @@ -3886,6 +3882,12 @@ declare namespace wx { */ data?: Data; + /** + * 数据监听器可以用于监听和响应任何属性和数据字段的变化。从小程序基础库版本 2.6.1 开始支持 + * @since 2.6.1 + */ + observers?: ObserversDefs; + /** * 组件的方法,包括事件响应函数和任意的自定义方法 * 关于事件响应函数的使用 @@ -3925,7 +3927,7 @@ declare namespace wx { * 类似于mixins和traits的组件间代码复用机制 * 参见 [behaviors](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/custom-component/behaviors.html) */ - behaviors?: Behaviors; + behaviors?: Behaviors; /** * 组件生命周期声明对象,组件的生命周期:created、attached、ready、moved、detached将收归到lifetimes字段内进行声明, @@ -3965,7 +3967,11 @@ declare namespace wx { /** * Component实例方法 */ - interface Component | string> = []> { + interface Component< + D, + P, + B extends Array | string> = [] + > { /** * 组件的文件路径 */ @@ -3981,20 +3987,24 @@ declare namespace wx { /** * 组件数据,包括内部数据和属性值 */ - data: D & UnboxBehaviorsData & { - [key in keyof (P & UnboxBehaviorsProps)]: PropValueType< - (P & UnboxBehaviorsProps)[key] - > - }; + data: D & + UnboxBehaviorsData & + { + [key in keyof (P & UnboxBehaviorsProps)]: PropValueType< + (P & UnboxBehaviorsProps)[key] + > + }; /** * 组件数据,包括内部数据和属性值(与 data 一致) */ - properties: D & UnboxBehaviorsData & { - [key in keyof (P & UnboxBehaviorsProps)]: PropValueType< - (P & UnboxBehaviorsProps)[key] - > - }; + properties: D & + UnboxBehaviorsData & + { + [key in keyof (P & UnboxBehaviorsProps)]: PropValueType< + (P & UnboxBehaviorsProps)[key] + > + }; /** * 将数据从逻辑层发送到视图层,同时改变对应的 this.data 的值 * 1. 直接修改 this.data 而不调用 this.setData 是无法改变页面的状态的,还会造成数据不一致。 @@ -4397,7 +4407,12 @@ declare function App( declare function getApp(): wx.App; // #endregion // #region Compontent组件 -declare function Component | string> = []>( +declare function Component< + D, + M, + P, + B extends Array | string> = [] +>( options?: wx.ThisTypedComponentOptionsWithRecordProps< wx.Component, D, @@ -4414,7 +4429,12 @@ declare function Component | st * 每个组件可以引用多个 behavior * behavior 也可以引用其他 behavior */ -declare function Behavior | string> = []>( +declare function Behavior< + D, + M, + P, + B extends Array | string> = [] +>( options?: wx.ThisTypedComponentOptionsWithRecordProps< wx.Component, D, @@ -4422,7 +4442,11 @@ declare function Behavior | str P, B > -): wx.Behavior, P & wx.UnboxBehaviorsProps, M & wx.UnboxBehaviorsMethods>; +): wx.Behavior< + D & wx.UnboxBehaviorsData, + P & wx.UnboxBehaviorsProps, + M & wx.UnboxBehaviorsMethods +>; // #endregion // #region Page /** diff --git a/types/weixin-app/weixin-app-tests.ts b/types/weixin-app/weixin-app-tests.ts index fb717d0c31..a824028862 100644 --- a/types/weixin-app/weixin-app-tests.ts +++ b/types/weixin-app/weixin-app-tests.ts @@ -16,7 +16,7 @@ const parentBehavior = Behavior({ } }, data: { - myParentBehaviorData: "", + myParentBehaviorData: "" }, methods: { myParentBehaviorMethod(input: number) { @@ -26,31 +26,40 @@ const parentBehavior = Behavior({ }); function createBehaviorWithUnionTypes(n: number) { - const properties = n % 2 < 1 ? { - unionPropA: { - type: String, - }, - } : { - unionPropB: { - type: Number, - }, - }; + const properties = + n % 2 < 1 + ? { + unionPropA: { + type: String + } + } + : { + unionPropB: { + type: Number + } + }; - const data = n % 4 < 2 ? { - unionDataA: 'a', - } : { - unionDataB: 1, - }; + const data = + n % 4 < 2 + ? { + unionDataA: "a" + } + : { + unionDataB: 1 + }; - const methods = n % 8 < 4 ? { - unionMethodA(a: number) { - return n + 1; - }, - } : { - unionMethodB(a: string) { - return {value: a}; - }, - }; + const methods = + n % 8 < 4 + ? { + unionMethodA(a: number) { + return n + 1; + } + } + : { + unionMethodB(a: string) { + return { value: a }; + } + }; return Behavior({ properties, @@ -63,7 +72,7 @@ const behavior = Behavior({ behaviors: [ createBehaviorWithUnionTypes(1), parentBehavior, - "wx://form-field", + "wx://form-field" ], properties: { myBehaviorProperty: { @@ -168,7 +177,7 @@ Component({ console.log(this.unionMethodA(5)); } if (this.unionMethodB) { - console.log(this.unionMethodB('test').value); + console.log(this.unionMethodB("test").value); } console.log(this.data.unionDataA); console.log(this.data.unionDataB); @@ -568,3 +577,26 @@ App({ }); } }); + +Component({ + observers: { + "name, age": function nameAgeObserver(name: string, age: number) { + this.setData({ + nameStr: `Dear ${name}`, + ageStr: `${age}` + }); + } + }, + properties: { + name: { + type: String + }, + age: { + type: Number + } + }, + data: { + nameStr: "", + ageStr: "" + } +}); diff --git a/types/word-extractor/index.d.ts b/types/word-extractor/index.d.ts new file mode 100644 index 0000000000..c6e6289774 --- /dev/null +++ b/types/word-extractor/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for word-extractor 0.3 +// Project: https://github.com/morungos/node-word-extractor +// Definitions by: Rodrigo Saboya +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class WordExtractor { + extract(documentPath: string): Promise; +} + +export = WordExtractor; + +declare namespace WordExtractor { + class Document { + getBody(): string; + getFootnotes(): string; + getHeaders(): string; + getAnnotations(): string; + getEndNotes(): string; + } +} diff --git a/types/detect-browser/tsconfig.json b/types/word-extractor/tsconfig.json similarity index 92% rename from types/detect-browser/tsconfig.json rename to types/word-extractor/tsconfig.json index b1319407fc..436687e1ff 100644 --- a/types/detect-browser/tsconfig.json +++ b/types/word-extractor/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "detect-browser-tests.ts" + "word-extractor-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/word-extractor/tslint.json b/types/word-extractor/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/word-extractor/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/word-extractor/word-extractor-tests.ts b/types/word-extractor/word-extractor-tests.ts new file mode 100644 index 0000000000..a177b9d5c5 --- /dev/null +++ b/types/word-extractor/word-extractor-tests.ts @@ -0,0 +1,13 @@ +import WordExtractor = require("word-extractor"); + +const extractor = new WordExtractor(); + +let temp: string; + +const doc = extractor.extract('/path/to/file.doc').then(document => { + temp = document.getBody(); + temp = document.getAnnotations(); + temp = document.getEndNotes(); + temp = document.getFootnotes(); + temp = document.getHeaders(); +}); diff --git a/types/words-to-numbers/index.d.ts b/types/words-to-numbers/index.d.ts index 97ab92be8b..bbb0eb4ed9 100644 --- a/types/words-to-numbers/index.d.ts +++ b/types/words-to-numbers/index.d.ts @@ -3,5 +3,5 @@ // Definitions by: James Frowen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export declare function wordsToNumbers(text: string, options?: { fuzzy: boolean }): string | number | null; +export function wordsToNumbers(text: string, options?: { fuzzy: boolean }): string | number | null; export default wordsToNumbers; diff --git a/types/yeoman-generator/index.d.ts b/types/yeoman-generator/index.d.ts index 6415ad7957..fe39171825 100644 --- a/types/yeoman-generator/index.d.ts +++ b/types/yeoman-generator/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for yeoman-generator 3.0 +// Type definitions for yeoman-generator 3.1 // Project: https://github.com/yeoman/generator, http://yeoman.io // Definitions by: Kentaro Okuno // Jay Anslow // Ika // Joshua Cherry +// Arthur Corenzan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -71,7 +72,7 @@ declare namespace Generator { writeJSON(filepath: string, contents: {}, replacer?: (key: string, value: any) => any, space?: number): void; extendJSON(filepath: string, contents: {}, replacer?: (key: string, value: any) => any, space?: number): void; delete(filepath: string, options?: {}): void; - copy(from: string, to: string, options?: {}): void; + copy(from: string, to: string, options?: {}, context?: {}, templateOptions?: {}): void; copyTpl(from: string, to: string, context: {}, templateOptions?: {}, copyOptions?: {}): void; move(from: string, to: string, options?: {}): void; exists(filepath: string): boolean; diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index dc73ae6bd9..7e03517143 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -70,7 +70,7 @@ export interface Schema { withMutation(fn: (current: this) => void): void; default(value: any): this; default(): T; - nullable(isNullable: boolean): this; + nullable(isNullable?: boolean): this; required(message?: TestOptionsMessage): this; notRequired(): this; typeError(message?: TestOptionsMessage): this; diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index c6717e95ad..fdead13b2b 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -148,6 +148,7 @@ mixed.default({ number: 5 }); mixed.default(() => ({ number: 5 })); mixed.default(); mixed.nullable(true); +mixed.nullable(); mixed.required(); mixed.required("Foo"); mixed.required(() => "Foo"); diff --git a/types/zipkin-context-cls/tsconfig.json b/types/zipkin-context-cls/tsconfig.json index 57430d50b2..af624fda93 100644 --- a/types/zipkin-context-cls/tsconfig.json +++ b/types/zipkin-context-cls/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, @@ -20,4 +21,4 @@ "index.d.ts", "zipkin-context-cls-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/zipkin-transport-http/tsconfig.json b/types/zipkin-transport-http/tsconfig.json index 7ed663b14b..be30a49dab 100644 --- a/types/zipkin-transport-http/tsconfig.json +++ b/types/zipkin-transport-http/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, @@ -20,4 +21,4 @@ "index.d.ts", "zipkin-transport-http-tests.ts" ] -} \ No newline at end of file +}