diff --git a/notNeededPackages.json b/notNeededPackages.json index 1521fd7426..4289393363 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", @@ -1098,6 +1116,12 @@ "sourceRepoURL": "http://fian.my.id/Waves", "asOfVersion": "0.7.6" }, + { + "libraryName": "normalize-url", + "typingsPackageName": "normalize-url", + "sourceRepoURL": "https://github.com/sindresorhus/normalize-url", + "asOfVersion": "4.2.0" + }, { "libraryName": "Normalizr", "typingsPackageName": "normalizr", @@ -1122,11 +1146,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 +1812,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/adone/test/glosses/system/process.ts b/types/adone/test/glosses/system/process.ts index 9ffd3c33a5..9aed20b696 100644 --- a/types/adone/test/glosses/system/process.ts +++ b/types/adone/test/glosses/system/process.ts @@ -223,7 +223,7 @@ namespace adoneTests.system.process { }); ret.on("message", () => {}); - ret.stdout.pipe(adone.fs.createWriteStream(__filename)); + ret.stdout!.pipe(adone.fs.createWriteStream(__filename)); } } @@ -811,7 +811,7 @@ namespace adoneTests.system.process { }); ret.on("message", () => {}); - ret.stdout.pipe(adone.fs.createWriteStream(__filename)); + ret.stdout!.pipe(adone.fs.createWriteStream(__filename)); } } 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/angular-ui-router/angular-ui-router-tests.ts b/types/angular-ui-router/angular-ui-router-tests.ts index 889e92bfc9..d7dfcbfbde 100644 --- a/types/angular-ui-router/angular-ui-router-tests.ts +++ b/types/angular-ui-router/angular-ui-router-tests.ts @@ -33,7 +33,7 @@ myApp.config(( $urlMatcherFactory.type("fullType", { decode: (val) => parseInt(val, 10), encode: (val) => val && val.toString(), - equals: (a, b) => this.is(a) && a === b, + equals: function (a, b) { return this.is(a) && a === b }, is: (val) => angular.isNumber(val) && isFinite(val) && val % 1 === 0, pattern: /\d+/ }); 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/autoprefixer/index.d.ts b/types/autoprefixer/index.d.ts index faf11371db..1681c5d838 100644 --- a/types/autoprefixer/index.d.ts +++ b/types/autoprefixer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for autoprefixer 9.1 +// Type definitions for autoprefixer 9.4 // Project: https://github.com/postcss/autoprefixer // Definitions by: Armando Meziat , murt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -15,7 +15,7 @@ declare namespace autoprefixer { remove?: boolean; supports?: boolean; flexbox?: boolean | 'no-2009'; - grid?: boolean; + grid?: boolean | 'autoplace' | 'no-autoplace'; stats?: any; ignoreUnknownVersions?: boolean; } diff --git a/types/awesomplete/awesomplete-tests.ts b/types/awesomplete/awesomplete-tests.ts index a3c66875a4..b019e25ca3 100644 --- a/types/awesomplete/awesomplete-tests.ts +++ b/types/awesomplete/awesomplete-tests.ts @@ -46,7 +46,7 @@ new Awesomplete('input[data-multiple]', { return Awesomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]); }, - replace: (text: string) => { + replace(text: string) { const before = this.input.value.match(/^.+,\s*|/)[0]; this.input.value = `${before}${text}, `; } 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/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 3301feebb5..6ebccd452a 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -26,6 +26,7 @@ // James Gregory // Erik Dalén // Loïk Gaonac'h +// Roberto Zen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -34,7 +35,7 @@ export interface APIGatewayEventRequestContext { accountId: string; apiId: string; authorizer?: AuthResponseContext | null; - connectedAt: number; + connectedAt?: number; connectionId?: string; domainName?: string; eventType?: string; 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/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/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/cavy/cavy-tests.tsx b/types/cavy/cavy-tests.tsx new file mode 100644 index 0000000000..e33d0366a7 --- /dev/null +++ b/types/cavy/cavy-tests.tsx @@ -0,0 +1,40 @@ +import * as React from 'react'; +import { TextInput, View, Text } from 'react-native'; + +import { hook, TestScope, WithTestHook, Tester } from 'cavy'; + +type Props = WithTestHook<{ + foo: string; +}>; + +class SampleComponent extends React.Component { + render() { + return ( + + {this.props.foo} + + + ); + } +} + +const HookedSampleComponent = hook(SampleComponent); // $ExpectType ComponentClass<{ foo: string; }, any> + +function sampleSpec(spec: TestScope) { + spec.describe('it has a name and callback', () => { + spec.it('it has a name and callback', async () => { + spec.component.reRender(); // $ExpectType void + spec.component.clearAsync(); // $ExpectType Promise + spec.findComponent('View.Sample'); // $ExpectType Promise> + spec.press('View.Sample'); // $ExpectType Promise + spec.fillIn('Input.Sample', "hello world"); // $ExpectType Promise + spec.pause(1000); // $ExpectType Promise + spec.exists('View.Sample'); // $ExpectType Promise + spec.notExists('View.MissingSample'); // $ExpectType Promise + }); + }); +} + + + +; diff --git a/types/cavy/index.d.ts b/types/cavy/index.d.ts new file mode 100644 index 0000000000..5e74edfe48 --- /dev/null +++ b/types/cavy/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for cavy 0.6 +// Project: https://github.com/pixielabs/cavy +// Definitions by: Tyler Hoffman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +import * as React from 'react'; + +export {}; + +type RefCallback = (element: React.ReactNode | null) => void; + +export type TestHookGenerator = (label: string, callback?: RefCallback) => RefCallback; + +export type WithTestHook = T & { generateTestHook: TestHookGenerator }; + +export function hook(component: React.ComponentClass>): React.ComponentClass; + +export interface TesterProps { + specs: Array<(spec: TestScope) => void>; + waitTime: number; + sendReport?: boolean; +} + +export class Tester extends React.Component { + reRender(): void; + clearAsync(): Promise; +} + +export class TestScope { + component: Tester; + findComponent(identifier: string): Promise; + describe(label: string, fn: () => void): void; + it(label: string, fn: () => void): void; + press(identifier: string): Promise; + fillIn(identifier: string, str: string): Promise; + pause(time: number): Promise; + exists(identifier: string): Promise; + notExists(identifier: string): Promise; +} diff --git a/types/cavy/tsconfig.json b/types/cavy/tsconfig.json new file mode 100644 index 0000000000..4b78de6410 --- /dev/null +++ b/types/cavy/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "jsx": "react", + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cavy-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/internal-ip/tslint.json b/types/cavy/tslint.json similarity index 100% rename from types/internal-ip/tslint.json rename to types/cavy/tslint.json 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/chocolatechipjs/chocolatechipjs-tests.ts b/types/chocolatechipjs/chocolatechipjs-tests.ts index a723d1b8f9..93cd698da7 100644 --- a/types/chocolatechipjs/chocolatechipjs-tests.ts +++ b/types/chocolatechipjs/chocolatechipjs-tests.ts @@ -213,7 +213,7 @@ $('ul').undelegate('click', 'li', () => { $('li').on('click', () => { $.noop; }); -$('ul').on('click', 'li', () => { +$('ul').on('click', 'li', function() { console.log($(this).text()); }); $('li').off('click'); 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/ckeditor__ckeditor5-core/index.d.ts b/types/ckeditor__ckeditor5-core/index.d.ts index e3de076471..bc07e94fd3 100644 --- a/types/ckeditor__ckeditor5-core/index.d.ts +++ b/types/ckeditor__ckeditor5-core/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for @ckeditor/ckeditor5-core 11.0 -// Project: https://github.com/ckeditor/ckeditor5-core, https://ckeditor.com +// Project: https://github.com/ckeditor/ckeditor5-core, https://ckeditor.com/ckeditor-5 // Definitions by: denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/ckeditor__ckeditor5-engine/index.d.ts b/types/ckeditor__ckeditor5-engine/index.d.ts index 4d3e3f4a97..227862c0e3 100644 --- a/types/ckeditor__ckeditor5-engine/index.d.ts +++ b/types/ckeditor__ckeditor5-engine/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for @ckeditor/ckeditor5-engine 11.0 -// Project: https://github.com/ckeditor/ckeditor5-engine, https://ckeditor.com +// Project: https://github.com/ckeditor/ckeditor5-engine, https://ckeditor.com/ckeditor-5 // Definitions by: denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/ckeditor__ckeditor5-utils/index.d.ts b/types/ckeditor__ckeditor5-utils/index.d.ts index 3d943969de..fa270c8ba5 100644 --- a/types/ckeditor__ckeditor5-utils/index.d.ts +++ b/types/ckeditor__ckeditor5-utils/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for @ckeditor/ckeditor5-utils 10.2 -// Project: https://github.com/ckeditor/ckeditor5-utils, https://ckeditor.com +// Project: https://github.com/ckeditor/ckeditor5-utils, https://ckeditor.com/ckeditor-5 // Definitions by: denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index 82fc32a7d3..891361627f 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -878,7 +878,7 @@ export class Buy implements Resource { /** * Associated transaction (e.g. a bank, fiat account) */ - transaction: ResourceRef; + transaction: ResourceRef | null; /** * Amount in bitcoin, litecoin or ethereum @@ -896,7 +896,7 @@ export class Buy implements Resource { subtotal: MoneyHash; /** - * Fee associated to this buy + * Fees associated to this buy */ fees: Fee[]; @@ -935,6 +935,26 @@ export class Buy implements Resource { */ requires_completion_step: boolean; + /** + * Transfer identifier + */ + id: string; + + /** + * Reference code shown in user's dashboard. + */ + user_reference: string; + + /** + * ISO timestamp + */ + created_at: string; + + /** + * ISO timestamp + */ + updated_at: string; + /** * Completes a buy that is created in commit: false state. * If the exchange rate has changed since the buy was created, this call will fail with the error “The exchange rate updated while you @@ -995,7 +1015,7 @@ export class Sell implements Resource { /** * Associated transaction (e.g. a bank, fiat account) */ - transaction: ResourceRef; + transaction: ResourceRef | null; /** * Amount in bitcoin, litecoin or ethereum @@ -1013,9 +1033,9 @@ export class Sell implements Resource { subtotal: MoneyHash; /** - * Fee associated to this sell + * Fees associated to this sell */ - fee: MoneyHash; + fees: MoneyHash[]; /** * Has this sell been committed? @@ -1032,6 +1052,26 @@ export class Sell implements Resource { */ payout_at?: string; + /** + * Transfer identifier + */ + id: string; + + /** + * Reference code shown in user's dashboard. + */ + user_reference: string; + + /** + * ISO timestamp + */ + created_at: string; + + /** + * ISO timestamp + */ + updated_at: string; + /** * Completes a sell that is created in commit: false state. * If the exchange rate has changed since the sell was created, this call will fail with the error “The exchange rate updated while you 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/complex.js/complex.js-tests.ts b/types/complex.js/complex.js-tests.ts new file mode 100644 index 0000000000..0edef20998 --- /dev/null +++ b/types/complex.js/complex.js-tests.ts @@ -0,0 +1,61 @@ +import Complex from "complex.js"; + +Complex.ZERO; +Complex.PI; +Complex.E; +Complex.I; +Complex.INFINITY; +Complex.EPSILON; +Complex.ONE; +Complex.NAN; + +new Complex(1, 0); +new Complex(1, 0).abs(); +new Complex(1, 0).acos(); +new Complex(1, 0).acot(); +new Complex(1, 0).acoth(); +new Complex(1, 0).acsc(); +new Complex(1, 0).acsch(); +new Complex(1, 0).add(1, 2); +new Complex(1, 0).arg(); +new Complex(1, 0).asec(); +new Complex(1, 0).asech(); +new Complex(1, 0).asin(); +new Complex(1, 0).asinh(); +new Complex(1, 0).atan(); +new Complex(1, 0).atanh(); +new Complex(1, 0).ceil(5); +new Complex(1, 0).clone(); +new Complex(1, 0).conjugate(); +new Complex(1, 0).cos(); +new Complex(1, 0).cosh(); +new Complex(1, 0).cot(); +new Complex(1, 0).coth(); +new Complex(1, 0).csc(); +new Complex(1, 0).csch(); +new Complex(1, 0).div(3, 1); +new Complex(1, 0).equals(5, 3); +new Complex(1, 0).exp(); +new Complex(1, 0).floor(6); +new Complex(1, 0).inverse(); +new Complex(1, 0).isFinite(); +new Complex(1, 0).isInfinite(); +new Complex(1, 0).isNaN(); +new Complex(1, 0).isZero(); +new Complex(1, 0).log(); +new Complex(1, 0).mul(3, 1); +new Complex(1, 0).neg(); +new Complex(1, 0).pow(1, 2); +new Complex(1, 0).round(3); +new Complex(1, 0).sec(); +new Complex(1, 0).sech(); +new Complex(1, 0).sign(); +new Complex(1, 0).sin(); +new Complex(1, 0).sinh(); +new Complex(1, 0).sqrt(); +new Complex(1, 0).sub(5, 1); +new Complex(1, 0).tan(); +new Complex(1, 0).tanh(); +new Complex(1, 0).toString(); +new Complex(1, 0).toVector(); +new Complex(1, 0).valueOf(); diff --git a/types/complex.js/index.d.ts b/types/complex.js/index.d.ts new file mode 100644 index 0000000000..487fc4e30d --- /dev/null +++ b/types/complex.js/index.d.ts @@ -0,0 +1,304 @@ +// Type definitions for complex.js 2.0 +// Project: https://github.com/infusion/Complex.js +// Definitions by: Adam Zerella +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Complex { + /** + * A complex zero value (south pole on the Riemann Sphere). + */ + static ZERO: Complex; + + /** + * A complex one instance. + */ + static ONE: Complex; + + /** + * A complex infinity value (north pole on the Riemann Sphere). + */ + static INFINITY: Complex; + + /** + * A complex NaN value (not on the Riemann Sphere). + */ + static NAN: Complex; + + /** + * An imaginary number i instance. + */ + static I: Complex; + + /** + * A complex PI instance. + */ + static PI: Complex; + + /** + * A complex euler number instance. + */ + static E: Complex; + + /** + * A small epsilon value used for equals() comparison in order to circumvent double inprecision. + */ + static EPSILON: number; + + constructor(x: number, y: number); + + /** + * Returns the complex sign, defined as the complex number + * normalized by it's absolute value. + */ + sign(): Complex; + + /** + * Adds another complex number. + */ + add(a: number, b: number): Complex; + + /** + * Subtracts another complex number. + */ + sub(a: number, b: number): Complex; + + /** + * Multiplies the number with another complex number. + */ + mul(a: number, b: number): Complex; + + /** + * Divides the number by another complex number. + */ + div(a: number, b: number): Complex; + + /** + * Returns the number raised to the complex exponent. + */ + pow(a: number, b: number): Complex; + + /** + * Returns the complex square root of the number. + */ + sqrt(): Complex; + + /** + * Returns e^n with complex exponent n + */ + exp(): Complex; + + /** + * Returns the natural logarithm (base E) of the actual complex number. + */ + log(): Complex; + + /** + * Calculates the magnitude of the complex number. + */ + abs(): number; + + /** + * Calculate the angle of the complex number. + */ + arg(): number; + + /** + * Calculates the multiplicative inverse of the complex number (1 / z). + */ + inverse(): Complex; + + /** + * Calculates the conjugate of the complex number (multiplies the imaginary part with -1). + */ + conjugate(): Complex; + + /** + * Negates the number (multiplies both the real and imaginary part with -1) in order to get the additive inverse. + */ + neg(): Complex; + + /** + * Floors the complex number parts towards zero. + */ + floor(places: number): Complex; + + /** + * Ceils the complex number parts off zero. + */ + ceil(places: number): Complex; + + /** + * Rounds the complex number parts. + */ + round(places: number): Complex; + + /** + * Checks if both numbers are exactly the same, + * if both numbers are infinite they are considered not equal. + */ + equals(a: number, b: number): boolean; + + /** + * Checks if the given number is not a number. + */ + isNaN(): boolean; + + /** + * Determines whether or not a complex number is at the zero pole of the + * Riemann sphere. + */ + isZero(): boolean; + + /** + * Checks if the given number is finite. + */ + isFinite(): boolean; + + /** + * Determines whether or not a complex number is at the infinity pole of the + * Riemann sphere. + */ + isInfinite(): boolean; + + /** + * Returns a new Complex instance with the same real and imaginary properties. + */ + clone(): Complex; + + /** + * Returns a Vector of the actual complex number with two components. + */ + toVector(): number[]; + + /** + * Returns a string representation of the actual number. As of v1.9.0 the output is a bit more human readable. + */ + toString(): string; + + /** + * Returns the real part of the number if imaginary part is zero. Otherwise null. + */ + valueOf(): number|undefined; + + /** + * Calculate the sine of the complex number. + */ + sin(): Complex; + + /** + * Calculate the complex arcus sinus. + */ + asin(): Complex; + + /** + * Calculate the complex sinh. + */ + sinh(): Complex; + + /** + * Calculate the complex asinh. + */ + asinh(): Complex; + + /** + * Calculate the cosine. + */ + cos(): Complex; + + /** + * Calculate the complex arcus cosinus. + */ + acos(): Complex; + + /** + * Calculate the complex cosh. + */ + cosh(): Complex; + + /** + * Calculate the complex asinh. + */ + acosh(): Complex; + + /** + * Calculate the tangent. + */ + tan(): Complex; + + /** + * Calculate the complex arcus tangent. + */ + atan(): Complex; + + /** + * Calculate the complex tanh. + */ + tanh(): Complex; + + /** + * Calculate the complex atanh. + */ + atanh(): Complex; + + /** + * Calculate the cotangent. + */ + cot(): Complex; + + /** + * Calculate the complex arcus cotangent. + */ + acot(): Complex; + + /** + * Calculate the complex coth. + */ + coth(): Complex; + + /** + * Calculate the complex acoth. + */ + acoth(): Complex; + + /** + * Calculate the secant. + */ + sec(): Complex; + + /** + * Calculate the complex arcus secant. + */ + asec(): Complex; + + /** + * Calculate the complex sech. + */ + sech(): Complex; + + /** + * Calculate the complex asech. + */ + asech(): Complex; + + /** + * Calculate the cosecans. + */ + csc(): Complex; + + /** + * Calculate the complex arcus cosecans. + */ + acsc(): Complex; + + /** + * Calculate the complex csch. + */ + csch(): Complex; + + /** + * Calculate the complex acsch. + */ + acsch(): Complex; +} + +export default Complex; diff --git a/types/complex.js/tsconfig.json b/types/complex.js/tsconfig.json new file mode 100644 index 0000000000..b4af58b032 --- /dev/null +++ b/types/complex.js/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", + "complex.js-tests.ts" + ] +} diff --git a/types/complex.js/tslint.json b/types/complex.js/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/complex.js/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file 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/consul/consul-tests.ts b/types/consul/consul-tests.ts index 988890766d..263b5beff5 100644 --- a/types/consul/consul-tests.ts +++ b/types/consul/consul-tests.ts @@ -511,6 +511,7 @@ consul = new Consul(); // Consul.Health { let health: Consul.Health = consul.health; + let name: string; health = new HealthStatic(consul); consul = health.consul; 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/cross-spawn/cross-spawn-tests.ts b/types/cross-spawn/cross-spawn-tests.ts index 6cb36510d8..f6dac4ea72 100644 --- a/types/cross-spawn/cross-spawn-tests.ts +++ b/types/cross-spawn/cross-spawn-tests.ts @@ -8,7 +8,7 @@ pw.on('error', (err: Error) => { console.log(err); }); -const r1: Error = spawn.sync('foo').error; +const r1: Error | undefined = spawn.sync('foo').error; const r2: string[] = spawn.sync('foo').output; const r3: Buffer = spawn.sync('foo').stdout; const r4: Buffer = spawn.sync('foo').stderr; diff --git a/types/datatables.net/datatables.net-tests.ts b/types/datatables.net/datatables.net-tests.ts index de739a673a..d6903ce1db 100644 --- a/types/datatables.net/datatables.net-tests.ts +++ b/types/datatables.net/datatables.net-tests.ts @@ -578,7 +578,7 @@ $('#example tbody').on('click', 'td', () => { const cell_invalidate_1 = cell.invalidate(); const cell_invalidate_2 = cell.invalidate("data"); -$('#example tbody').on('click', 'td', () => { +$('#example tbody').on('click', 'td', function() { this.innerHTML = (parseInt(this.innerHTML, 10) + 1).toString(); dt.cell(this).invalidate().draw(); }); @@ -773,7 +773,7 @@ let column_search_set = column.search("string"); column_search_set = column.search("string", true); column_search_set = column.search("string", true, false); column_search_set = column.search("string", true, false, true); -$('#column3_search').on('keyup', () => { +$('#column3_search').on('keyup', function() { dt .columns(3) .search((this as HTMLInputElement).value) diff --git a/types/date-and-time/date-and-time-tests.ts b/types/date-and-time/date-and-time-tests.ts new file mode 100644 index 0000000000..aae667f2bc --- /dev/null +++ b/types/date-and-time/date-and-time-tests.ts @@ -0,0 +1,86 @@ +import * as date from "date-and-time"; + +const now = new Date(); +// $ExpectType string +date.format(now, "YYYY/MM/DD HH:mm:ss"); // => '2015/01/02 23:14:05' +// $ExpectType string +date.format(now, "ddd MMM DD YYYY"); // => 'Fri Jan 02 2015' +// $ExpectType string +date.format(now, "hh:mm A [GMT]Z"); // => '11:14 p.m. GMT-0800' +// $ExpectType string +date.format(now, "hh:mm A [GMT]Z", true); // => '07:14 a.m. GMT+0000' + +// $ExpectType number | Date +date.parse("2015/01/02 23:14:05", "YYYY/MM/DD HH:mm:ss"); // => date object +// $ExpectType number | Date +date.parse("02-01-2015", "DD-MM-YYYY"); // => date object +// $ExpectType number | Date +date.parse("Jam 1 2017", "MMM D YYYY"); // => NaN + +// $ExpectType boolean +date.isValid("2015/01/02 23:14:05", "YYYY/MM/DD HH:mm:ss"); // => true +// $ExpectType boolean +date.isValid("29-02-2015", "DD-MM-YYYY"); // => false + +// $ExpectType Date +date.addYears(now, 1); // => Date object + +// $ExpectType Date +date.addMonths(now, 1); // => Date object + +// $ExpectType Date +date.addDays(now, -1); // => Date object + +// $ExpectType Date +date.addHours(now, -1); // => Date object + +// $ExpectType Date +date.addMinutes(now, 2); // => Date object + +// $ExpectType Date +date.addSeconds(now, -3); // => Date object + +// $ExpectType Date +date.addMilliseconds(now, 1); // => Date object + +const today = new Date(2015, 0, 2); +const yesterday = new Date(2015, 0, 1); + +// $ExpectType Subtract +date.subtract(today, yesterday); +// $ExpectType number +date.subtract(today, yesterday).toDays(); // => 1 = today - yesterday +// $ExpectType number +date.subtract(today, yesterday).toHours(); // => 24 +// $ExpectType number +date.subtract(today, yesterday).toMinutes(); // => 1440 +// $ExpectType number +date.subtract(today, yesterday).toSeconds(); // => 86400 +// $ExpectType number +date.subtract(today, yesterday).toMilliseconds(); // => 86400000 + +const date1 = new Date(2015, 0, 2); +const date2 = new Date(2012, 0, 2); +// $ExpectType boolean +date.isLeapYear(date1); // => false +// $ExpectType boolean +date.isLeapYear(date2); // => true + +const date1_ = new Date(2017, 0, 2, 0); // Jan 2 2017 00:00:00 +const date2_ = new Date(2017, 0, 2, 23, 59); // Jan 2 2017 23:59:00 +const date3 = new Date(2017, 0, 1, 23, 59); // Jan 1 2017 23:59:00 +// $ExpectType boolean +date.isSameDay(date1_, date2_); // => true +// $ExpectType boolean +date.isSameDay(date1_, date3); // => false + +// $ExpectType string +date.locale(); + +// $ExpectType any +date.getLocales(); + +// $ExpectType void +date.setLocales("en", { + A: ["AM", "PM"] +}); diff --git a/types/date-and-time/index.d.ts b/types/date-and-time/index.d.ts new file mode 100644 index 0000000000..76f82809b3 --- /dev/null +++ b/types/date-and-time/index.d.ts @@ -0,0 +1,150 @@ +// Type definitions for date-and-time 0.6 +// Project: https://github.com/knowledgecode/date-and-time +// Definitions by: Daniel Plisetsky +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type getDelta = () => number; + +export interface Subtract { + toMilliseconds: getDelta; + toSeconds: getDelta; + toMinutes: getDelta; + toHours: getDelta; + toDays: getDelta; +} + +/** + * Formatting a date + * @param dateObj - Date object + * @param formatString - Format string + * @param [utc] - Output as UTC + * @returns The formatted string + * + */ +export function format( + dateObj: Date, + formatString: string, + utc?: boolean +): string; + +/** + * Parsing a date string + * @param dateString - date string + * @param formatString - format string + * @param [utc] - input as UTC + * @returns the constructed date or NaN + */ +export function parse( + dateString: string, + formatString: string, + utc?: boolean +): Date | number; + +/** + * Validation + * @param dateString - Date string + * @param formatString - Format string + * @returns Whether the date string is a valid date + */ +export function isValid(dateString: string, formatString: string): boolean; + +/** + * Adding years + * @param dateObj - Date object + * @param years - Adding year + * @returns The date after adding the value + */ +export function addYears(dateObj: Date, years: number): Date; + +/** + * Adding months + * @param dateObj - Date object + * @param months - Adding month + * @returns The date after adding the value + */ +export function addMonths(dateObj: Date, months: number): Date; + +/** + * Adding days + * @param dateObj - Date object + * @param days - Adding day + * @returns The date after adding the value + */ +export function addDays(dateObj: Date, days: number): Date; + +/** + * Adding hours + * @param dateObj - Date object + * @param hours - Adding hour + * @returns The date after adding the value + */ +export function addHours(dateObj: Date, hours: number): Date; + +/** + * Adding minutes + * @param dateObj - Date object + * @param minutes - Adding minute + * @returns The date after adding the value + */ +export function addMinutes(dateObj: Date, minutes: number): Date; + +/** + * Adding seconds + * @param dateObj - date object + * @param seconds - adding second + * @returns The date after adding the value + */ +export function addSeconds(dateObj: Date, seconds: number): Date; + +/** + * Adding milliseconds + * @param dateObj - Date object + * @param milliseconds - Adding millisecond + * @returns The date after adding the value + */ +export function addMilliseconds(dateObj: Date, milliseconds: number): Date; + +/** + * Subtracting + * @param date1 - Date object + * @param date2 - Date object + * @returns The result object after subtracting the date + */ +export function subtract(date1: Date, date2: Date): Subtract; + +/** + * Leap year + * @param dateObj - Date object + * @returns Whether the year is a leap year + */ +export function isLeapYear(dateObj: Date): boolean; + +/** + * Comparison of dates + * @param date1 - Target for comparison + * @param date2 - Target for comparison + * @returns Whether the dates are the same day (times are ignored) + */ +export function isSameDay(date1: Date, date2: Date): boolean; + +/** + * Setting a locale + * @param [code] - Language code + * @returns Current language code + */ +export function locale(code?: string): string; + +/** + * Getting a definition of locale + * @param [code] - Language code + * @returns Definition of locale + */ +export function getLocales(code?: string): any; + +/** + * Adding a new definition of locale + * @param code - Language code + * @param options - Definition of locale + * @returns + */ +export function setLocales(code: string, options: any): void; diff --git a/types/date-and-time/tsconfig.json b/types/date-and-time/tsconfig.json new file mode 100644 index 0000000000..96001a795d --- /dev/null +++ b/types/date-and-time/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", "date-and-time-tests.ts"] +} diff --git a/types/internal-ip/v2/tslint.json b/types/date-and-time/tslint.json similarity index 100% rename from types/internal-ip/v2/tslint.json rename to types/date-and-time/tslint.json 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/driftless/driftless-tests.ts b/types/driftless/driftless-tests.ts new file mode 100644 index 0000000000..22df64c992 --- /dev/null +++ b/types/driftless/driftless-tests.ts @@ -0,0 +1,5 @@ +import * as driftless from "driftless"; + +driftless.setDriftlessTimeout(() => "OK", 10); // $ExpectType number +const interval = driftless.setDriftlessInterval((a) => "OK" + a, 100, "foo"); // $ExpectType number +driftless.clearDriftless(interval); // $ExpectType void diff --git a/types/driftless/index.d.ts b/types/driftless/index.d.ts new file mode 100644 index 0000000000..8fddd26dae --- /dev/null +++ b/types/driftless/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for driftless 2.0 +// Project: https://github.com/dbkaplun/driftless +// Definitions by: Dan Delany +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function setDriftlessTimeout( + callback: ((...args: any[]) => void) | string, + delayMs: number, + ...params: any[] +): number; + +export function setDriftlessInterval( + callback: ((...args: any[]) => void) | string, + delayMs: number, + ...params: any[] +): number; + +export function clearDriftless( + id: number, + options?: { + customClearTimeout?: (...args: any[]) => void; + } +): void; diff --git a/types/internal-ip/tsconfig.json b/types/driftless/tsconfig.json similarity index 93% rename from types/internal-ip/tsconfig.json rename to types/driftless/tsconfig.json index 99d54932e0..3e61f98da4 100644 --- a/types/internal-ip/tsconfig.json +++ b/types/driftless/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "internal-ip-tests.ts" + "driftless-tests.ts" ] } diff --git a/types/p-map/tslint.json b/types/driftless/tslint.json similarity index 100% rename from types/p-map/tslint.json rename to types/driftless/tslint.json 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/ember-data/index.d.ts b/types/ember-data/index.d.ts index 601a45faf3..6cb514556c 100644 --- a/types/ember-data/index.d.ts +++ b/types/ember-data/index.d.ts @@ -543,8 +543,9 @@ export namespace DS { * invoking the callback with the name of each relationship and its relationship * descriptor. */ - eachRelationship( - callback: (name: string, details: RelationshipMeta) => void, + eachRelationship( + this: T, + callback: (name: string, details: RelationshipMeta) => void, binding?: any ): any; /** diff --git a/types/ember-data/test/relationships.ts b/types/ember-data/test/relationships.ts index dee9519b34..13a526ba6a 100644 --- a/types/ember-data/test/relationships.ts +++ b/types/ember-data/test/relationships.ts @@ -26,7 +26,7 @@ p.eachRelationship((n, meta) => { let m: 'belongsTo' | 'hasMany' = meta.kind; }); -class Comment extends DS.Model { +export class Comment extends DS.Model { author = DS.attr('string'); } diff --git a/types/ember-data/test/store.ts b/types/ember-data/test/store.ts index 9c1194c711..b6bb25993c 100644 --- a/types/ember-data/test/store.ts +++ b/types/ember-data/test/store.ts @@ -1,6 +1,7 @@ import Ember from 'ember'; import DS from 'ember-data'; import { assertType } from './lib/assert'; +import { Comment } from './relationships'; declare const store: DS.Store; @@ -119,7 +120,7 @@ const MyRouteAsync = Ember.Route.extend({ const store = this.get('store'); return await store.findRecord('post-comment', 1); }, - async afterModel(): Promise> { + async afterModel(): Promise> { const post = await this.get('store').findRecord('post', 1); return await post.get('comments'); } @@ -132,7 +133,7 @@ class MyRouteAsyncES6 extends Ember.Route { async model(): Promise { return await this.store.findRecord('post-comment', 1); } - async afterModel(): Promise> { + async afterModel(): Promise> { const post = await this.store.findRecord('post', 1); return await post.get('comments'); } diff --git a/types/ember-data/v2/index.d.ts b/types/ember-data/v2/index.d.ts index 3afd091ffe..e6dd65eb3b 100644 --- a/types/ember-data/v2/index.d.ts +++ b/types/ember-data/v2/index.d.ts @@ -525,7 +525,7 @@ export namespace DS { * invoking the callback with the name of each relationship and its relationship * descriptor. */ - eachRelationship(callback: (name: string, details: RelationshipMeta) => void, binding?: any): any; + eachRelationship(this: T, callback: (name: string, details: RelationshipMeta) => void, binding?: any): any; /** * Represents the model's class name as a string. This can be used to look up the model's class name through * `DS.Store`'s modelFor method. diff --git a/types/ember-data/v2/test/relationships.ts b/types/ember-data/v2/test/relationships.ts index 06795c0e26..21e66c6be5 100644 --- a/types/ember-data/v2/test/relationships.ts +++ b/types/ember-data/v2/test/relationships.ts @@ -26,7 +26,7 @@ p.eachRelationship((n, meta) => { let m: 'belongsTo' | 'hasMany' = meta.kind; }); -class Comment extends DS.Model { +export class Comment extends DS.Model { author = DS.attr('string'); } diff --git a/types/ember-data/v2/test/store.ts b/types/ember-data/v2/test/store.ts index 2584e7bdf3..902ea99852 100644 --- a/types/ember-data/v2/test/store.ts +++ b/types/ember-data/v2/test/store.ts @@ -1,6 +1,7 @@ import Ember from 'ember'; import DS from 'ember-data'; import { assertType } from './lib/assert'; +import { Comment } from './relationships'; declare const store: DS.Store; @@ -119,7 +120,7 @@ const MyRouteAsync = Ember.Route.extend({ const store = this.get('store'); return await store.findRecord('post-comment', 1); }, - async afterModel(): Promise> { + async afterModel(): Promise> { const post = await this.get('store').findRecord('post', 1); return await post.get('comments'); } @@ -132,7 +133,7 @@ class MyRouteAsyncES6 extends Ember.Route { async model(): Promise { return await this.store.findRecord('post-comment', 1); } - async afterModel(): Promise> { + async afterModel(): Promise> { const post = await this.store.findRecord('post', 1); return await post.get('comments'); } diff --git a/types/ember/v2/test/mixin.ts b/types/ember/v2/test/mixin.ts index a89f490a11..46566a9df9 100755 --- a/types/ember/v2/test/mixin.ts +++ b/types/ember/v2/test/mixin.ts @@ -6,7 +6,7 @@ interface EditableMixin { isEditing: boolean; } -const EditableMixin: Ember.Mixin = Ember.Mixin.create({ +const EditableMixin = Ember.Mixin.create({ edit() { this.get('controller'); console.log('starting to edit'); 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/execa/execa-tests.ts b/types/execa/execa-tests.ts index ecc966d3d5..632388106e 100644 --- a/types/execa/execa-tests.ts +++ b/types/execa/execa-tests.ts @@ -43,8 +43,8 @@ execa.shell('echo unicorns').then(result => result.stdout.toLocaleLowerCase()); result = execa.shellSync('noop foo').stdout; } -execa('echo', ['unicorns']).stdout.pipe(process.stdout); -execa('echo', ['unicorns']).stderr.pipe(process.stderr); +execa('echo', ['unicorns']).stdout!.pipe(process.stdout); +execa('echo', ['unicorns']).stderr!.pipe(process.stderr); execa('forever', { extendEnv: false }).pid; execa('forever', { argv0: 'hi' }).pid; @@ -85,7 +85,7 @@ async () => { async () => { const child = execa('stdin'); - child.stdin.end('unicorns'); + child.stdin!.end('unicorns'); const { stdout } = await child; assert(stdout === 'unicorns'); }; @@ -104,7 +104,7 @@ async () => { stdio: [null, 'ignore', null] }); - child.stdout.setEncoding('utf8'); + child.stdout!.setEncoding('utf8'); assert(child.pid === 0); child.kill(); diff --git a/types/expectations/expectations-tests.ts b/types/expectations/expectations-tests.ts index 4e994e7546..8f8bd25985 100644 --- a/types/expectations/expectations-tests.ts +++ b/types/expectations/expectations-tests.ts @@ -1,6 +1,6 @@ // transplant from https://github.com/spmason/expectations/blob/695c25bd35bb1751533a8082a5aa378e3e1b381f/test/expect.tests.js -var root = this; +var root = window; // Stub mocha functions const {describe, it, before, after, beforeEach, afterEach} = null as any as { @@ -451,7 +451,7 @@ describe('expect', ()=> { describe('extensibility', ()=> { it('allows you to add your own assertions', ()=> { - expect.addAssertion('toBeFoo', ()=> { + expect.addAssertion('toBeFoo', function () { if (this.value === 'foo') { return this.pass(); } diff --git a/types/expectations/tsconfig.json b/types/expectations/tsconfig.json index 857a8a1eef..ea4017a1a3 100644 --- a/types/expectations/tsconfig.json +++ b/types/expectations/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": false, @@ -20,4 +21,4 @@ "index.d.ts", "expectations-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/expo-localization/index.d.ts b/types/expo-localization/index.d.ts index 21c6ca8756..b79c777319 100644 --- a/types/expo-localization/index.d.ts +++ b/types/expo-localization/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for expo-localization 1.0 -// Project: https://docs.expo.io/ +// Project: https://docs.expo.io/versions/latest/sdk/localization // Definitions by: Bartosz Dotryw // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 5cc59d0941..8e973de1ab 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -103,7 +103,7 @@ export function log(...values: any[]): void; export function warn(...values: any[]): void; /////////////////////////////////////////////////////////////////////////////// -// Data Object Interfaces - These intrface are not specific part of fabric, +// Data Object Interfaces - These interface are not specific part of fabric, // They are just helpful for for defining function parameters ////////////////////////////////////////////////////////////////////////////// interface IDataURLOptions { @@ -135,12 +135,15 @@ interface IDataURLOptions { * Cropping height. Introduced in v1.2.14 */ height?: number; + enableRetinaScaling?: boolean; + withoutTransform?: boolean; + withoutShadow?: boolean; } interface IEvent { e: Event; target?: Object; - transform?: { corner: string }; + transform?: { corner: string }; } interface IFillOptions { @@ -175,6 +178,14 @@ interface IToSVGOptions { * Encoding of SVG output */ encoding: string; + /** + * desired width of svg with or without units + */ + width: number; + /** + * desired height of svg with or without units + */ + height: number; } interface IViewBox { @@ -329,6 +340,14 @@ interface ICanvasAnimation { * @chainable */ fxRemove(object: Object): T; + + /** + * Same as {@link fabric.Canvas.prototype.straightenObject}, but animated + * @param {fabric.Object} object Object to straighten + * @return {fabric.Canvas} thisArg + * @chainable + */ + fxStraightenObject(object: Object): T; } interface IObjectAnimation { /** @@ -421,6 +440,12 @@ export class Color { */ toHex(): string; + /** + * Returns color representation in HEXA format + * @return {String} ex: FF5555CC + */ + toHexa(): string; + /** * Gets value of alpha channel for this color */ @@ -495,100 +520,87 @@ export class Color { interface IGradientOptions { /** - * @param [options.type] Type of gradient 'radial' or 'linear' + * Horizontal offset for aligning gradients coming from SVG when outside pathgroups + * @type Number */ + offsetX?: number; + /** + * Vertical offset for aligning gradients coming from SVG when outside pathgroups + * @type Number + */ + offsetY?: number; type?: string; - /** - * x-coordinate of start point - */ - x1?: number; - /** - * y-coordinate of start point - */ - y1?: number; - /** - * x-coordinate of end point - */ - x2?: number; - /** - * y-coordinate of end point - */ - y2?: number; - /** - * Radius of start point (only for radial gradients) - */ - r1?: number; - /** - * Radius of end point (only for radial gradients) - */ - r2?: number; + coords?: {x1?: number, y1?: number, x2?: number, y2?: number, r1?: number, r2?: number}; /** * Color stops object eg. {0:string; 1:string; */ colorStops?: any; + gradientTransform?: any; } -interface IGradient extends IGradientOptions { +export interface Gradient extends IGradientOptions { } +export class Gradient { /** * Adds another colorStop * @param colorStop Object with offset and color */ - addColorStop(colorStop: any): IGradient; + addColorStop(colorStop: any): Gradient; /** * Returns object representation of a gradient */ - toObject(): any; + toObject(propertiesToInclude?: any): any; /** * Returns SVG representation of an gradient - * @param object Object to create a gradient for - * @param normalize Whether coords should be normalized - * @return SVG representation of an gradient (linear/radial) + * @param {Object} object Object to create a gradient for + * @return {String} SVG representation of an gradient (linear/radial) */ - toSVG(object: Object, normalize?: boolean): string; - + toSVG(object: any): string; /** * Returns an instance of CanvasGradient * @param ctx Context to render on */ - toLive(ctx: CanvasRenderingContext2D, object?: PathGroup): CanvasGradient; -} -interface IGrandientStatic { - new(options?: IGradientOptions): IGradient; + toLive(ctx: CanvasRenderingContext2D): CanvasGradient; /** - * Returns instance from an SVG element - * @param el SVG gradient element + * Returns {@link fabric.Gradient} instance from an SVG element + * @static + * @memberOf fabric.Gradient + * @param {SVGGradientElement} el SVG gradient element + * @param {fabric.Object} instance + * @return {fabric.Gradient} Gradient instance + * @see http://www.w3.org/TR/SVG/pservers.html#LinearGradientElement + * @see http://www.w3.org/TR/SVG/pservers.html#RadialGradientElement */ - fromElement(el: SVGGradientElement, instance: Object): IGradient; + static fromElement(el: SVGGradientElement, instance: Object): Gradient; /** - * Returns instance from its object representation - * @param [options] Options object + * Returns {@link fabric.Gradient} instance from its object representation + * @static + * @memberOf fabric.Gradient + * @param {Object} obj + * @param {Object} [options] Options object */ - fromObject(obj: any, options: any[]): IGradient; + static forObject(obj: any, options?: IGradientOptions): Gradient; } - export class Intersection { constructor(status?: string); - /** * Appends a point to intersection */ - appendPoint(point: Point): void; + appendPoint(point: Point): Intersection; /** * Appends points to intersection */ - appendPoints(points: Point[]): void; - + appendPoints(points: Point[]): Intersection; /** - * Checks if polygon intersects another polygon + * Checks if one line intersects another */ - static intersectPolygonPolygon(points1: Point[], points2: Point[]): Intersection; + static intersectLineLine(a1: Point, a2: Point, b1: Point, b2: Point): Intersection; /** * Checks if line intersects polygon */ static intersectLinePolygon(a1: Point, a2: Point, points: Point[]): Intersection; /** - * Checks if one line intersects another + * Checks if polygon intersects another polygon */ - static intersectLineLine(a1: Point, a2: Point, b1: Point, b2: Point): Intersection; + static intersectPolygonPolygon(points1: Point[], points2: Point[]): Intersection; /** * Checks if polygon intersects rectangle */ @@ -599,231 +611,293 @@ interface IPatternOptions { /** * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat) */ - repeat: string; + repeat?: string; /** * Pattern horizontal offset from object's left/top corner */ - offsetX: number; + offsetX?: number; /** * Pattern vertical offset from object's left/top corner */ - offsetY: number; + offsetY?: number; + /** + * crossOrigin value (one of "", "anonymous", "use-credentials") + * @see https://developer.mozilla.org/en-US/docs/HTML/CORS_settings_attributes + * @type String + */ + crossOrigin?: '' | 'anonymous' | 'use-credentials'; + /** + * Transform matrix to change the pattern, imported from svgs + */ + patternTransform?: number[]; /** * The source for the pattern */ source: string | HTMLImageElement; - /** - * Transform matrix to change the pattern, imported from svgs - */ - patternTransform?: number[]; } export interface Pattern extends IPatternOptions { } export class Pattern { constructor(options?: IPatternOptions); - - initialise(options?: IPatternOptions): Pattern; - /** - * Returns an instance of CanvasPattern - */ - toLive(ctx: CanvasRenderingContext2D): Pattern; - /** * Returns object representation of a pattern + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} Object representation of a pattern instance */ - toObject(): any; + toObject(propertiesToInclude: any): any; /** * Returns SVG representation of a pattern + * @param {fabric.Object} object + * @return {String} SVG representation of a pattern */ toSVG(object: Object): string; + setOptions(options: IPatternOptions): void; + /** + * Returns an instance of CanvasPattern + * @param {CanvasRenderingContext2D} ctx Context to create pattern + * @return {CanvasPattern} + */ + toLive(ctx: CanvasRenderingContext2D): CanvasPattern; } - export class Point { x: number; y: number; - + type: string; constructor(x: number, y: number); - /** * Adds another point to this one and returns another one + * @param {fabric.Point} that + * @return {fabric.Point} new Point instance with added values */ add(that: Point): Point; - /** * Adds another point to this one + * @param {fabric.Point} that + * @return {fabric.Point} thisArg + * @chainable */ addEquals(that: Point): Point; - /** * Adds value to this point and returns a new one + * @param {Number} scalar + * @return {fabric.Point} new Point with added value */ scalarAdd(scalar: number): Point; - /** * Adds value to this point + * @param {Number} scalar + * @return {fabric.Point} thisArg + * @chainable */ scalarAddEquals(scalar: number): Point; - /** * Subtracts another point from this point and returns a new one + * @param {fabric.Point} that + * @return {fabric.Point} new Point object with subtracted values */ subtract(that: Point): Point; - /** * Subtracts another point from this point + * @param {fabric.Point} that + * @return {fabric.Point} thisArg + * @chainable */ subtractEquals(that: Point): Point; - /** * Subtracts value from this point and returns a new one + * @param {Number} scalar + * @return {fabric.Point} */ scalarSubtract(scalar: number): Point; - /** * Subtracts value from this point + * @param {Number} scalar + * @return {fabric.Point} thisArg + * @chainable */ scalarSubtractEquals(scalar: number): Point; - /** - * Miltiplies this point by a value and returns a new one + * Multiplies this point by a value and returns a new one + * @param {Number} scalar + * @return {fabric.Point} */ multiply(scalar: number): Point; - /** - * Miltiplies this point by a value + * Multiplies this point by a value + * @param {Number} scalar + * @return {fabric.Point} thisArg + * @chainable */ multiplyEquals(scalar: number): Point; - /** * Divides this point by a value and returns a new one + * @param {Number} scalar + * @return {fabric.Point} */ divide(scalar: number): Point; - /** * Divides this point by a value + * @param {Number} scalar + * @return {fabric.Point} thisArg + * @chainable */ divideEquals(scalar: number): Point; - /** * Returns true if this point is equal to another one + * @param {fabric.Point} that + * @return {Boolean} */ eq(that: Point): Point; - /** * Returns true if this point is less than another one + * @param {fabric.Point} that + * @return {Boolean} */ lt(that: Point): Point; - /** * Returns true if this point is less than or equal to another one + * @param {fabric.Point} that + * @return {Boolean} */ lte(that: Point): Point; - /** * Returns true if this point is greater another one + * @param {fabric.Point} that + * @return {Boolean} */ gt(that: Point): Point; - /** * Returns true if this point is greater than or equal to another one + * @param {fabric.Point} that + * @return {Boolean} */ gte(that: Point): Point; - /** * Returns new point which is the result of linear interpolation with this one and another one + * @param {fabric.Point} that + * @param {Number} t , position of interpolation, between 0 and 1 default 0.5 + * @return {fabric.Point} */ lerp(that: Point, t: number): Point; - /** * Returns distance from this point and another one + * @param {fabric.Point} that + * @return {Number} */ distanceFrom(that: Point): number; - /** * Returns the point between this point and another one + * @param {fabric.Point} that + * @return {fabric.Point} */ midPointFrom(that: Point): Point; - /** * Returns a new point which is the min of this and another one + * @param {fabric.Point} that + * @return {fabric.Point} */ min(that: Point): Point; - /** * Returns a new point which is the max of this and another one + * @param {fabric.Point} that + * @return {fabric.Point} */ max(that: Point): Point; - /** * Returns string representation of this point + * @return {String} */ toString(): string; - /** * Sets x/y of this point + * @param {Number} x + * @param {Number} y + * @chainable */ setXY(x: number, y: number): Point; - + /** + * Sets x of this point + * @param {Number} x + * @chainable + */ + setX(x: number): Point; + /** + * Sets y of this point + * @param {Number} y + * @chainable + */ + setY(y: number): Point; /** * Sets x/y of this point from another point + * @param {fabric.Point} that + * @chainable */ setFromPoint(that: Point): Point; - /** * Swaps x/y of this point and another point + * @param {fabric.Point} that */ swap(that: Point): Point; + /** + * return a cloned instance of the point + * @return {fabric.Point} + */ + clone(): Point; } - interface IShadowOptions { - /** - * Whether the shadow should affect stroke operations - */ - affectStrike: boolean; - /** - * Shadow blur - */ - blur: number; /** * Shadow color */ - color: string; + color?: string; /** - * Indicates whether toObject should include default values + * Shadow blur */ - includeDefaultValues: boolean; + blur?: number; /** * Shadow horizontal offset */ - offsetX: number; + offsetX?: number; /** * Shadow vertical offset */ - offsetY: number; + offsetY?: number; + /** + * Whether the shadow should affect stroke operations + */ + affectStrike?: boolean; + /** + * Indicates whether toObject should include default values + */ + includeDefaultValues?: boolean; } export interface Shadow extends IShadowOptions { } export class Shadow { - constructor(options?: IShadowOptions); + constructor(options?: IShadowOptions| string); initialize(options?: IShadowOptions | string): Shadow; /** - * Returns object representation of a shadow - */ - toObject(): any; - /** - * Returns a string representation of an instance, CSS3 text-shadow declaration + * Returns a string representation of an instance + * @see http://www.w3.org/TR/css-text-decor-3/#text-shadow + * @return {String} Returns CSS3 text-shadow declaration */ toString(): string; /** * Returns SVG representation of a shadow + * @param {fabric.Object} object + * @return {String} SVG representation of a shadow */ toSVG(object: Object): string; - /** - * Regex matching shadow offsetX, offsetY and blur, Static + * Returns object representation of a shadow + * @return {Object} Object representation of a shadow instance + */ + toObject(): any; + /** + * Regex matching shadow offsetX, offsetY and blur (ex: "2px 2px 10px rgba(0,0,0,0.2)", "rgb(0,255,0) 2px 2px") + * @static + * @field + * @memberOf fabric.Shadow */ - reOffsetsAndBlur: RegExp; - static reOffsetsAndBlur: RegExp; } @@ -852,162 +926,239 @@ interface ICanvasDimensionsOptions { } interface IStaticCanvasOptions { - /** - * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas - */ - allowTouchScrolling?: boolean; - - /** - * When true, canvas is scaled by devicePixelRatio for better rendering on retina screens - */ - enableRetinaScaling?: boolean; - - /** - * Indicates whether this canvas will use image smoothing, this is on by default in browsers - */ - imageSmoothingEnabled?: boolean; - - /** - * Indicates whether objects should remain in current stack position when selected. - * When false objects are brought to top and rendered as part of the selection group - */ - preserveObjectStacking?: boolean; - - /** - * The transformation (in the format of Canvas transform) which focuses the viewport - */ - viewportTransform?: number[]; - - freeDrawingColor?: string; - freeDrawingLineWidth?: number; - /** * Background color of canvas instance. - * Should be set via setBackgroundColor + * Should be set via {@link fabric.StaticCanvas#setBackgroundColor}. + * @type {(String|fabric.Pattern)} */ backgroundColor?: string | Pattern; /** * Background image of canvas instance. - * Should be set via setBackgroundImage - * Backwards incompatibility note: The "backgroundImageOpacity" and "backgroundImageStretch" properties are deprecated since 1.3.9. + * Should be set via {@link fabric.StaticCanvas#setBackgroundImage}. + * Backwards incompatibility note: The "backgroundImageOpacity" + * and "backgroundImageStretch" properties are deprecated since 1.3.9. + * Use {@link fabric.Image#opacity}, {@link fabric.Image#width} and {@link fabric.Image#height}. + * since 2.4.0 image caching is active, please when putting an image as background, add to the + * canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom + * vale. As an alternative you can disable image objectCaching + * @type fabric.Image */ backgroundImage?: Image | string; - backgroundImageOpacity?: number; - backgroundImageStretch?: number; - /** - * Function that determines clipping of entire canvas area - * Being passed context as first argument. See clipping canvas area - */ - clipTo?(context: CanvasRenderingContext2D): void; - - /** - * Indicates whether object controls (borders/controls) are rendered above overlay image - */ - controlsAboveOverlay?: boolean; - - /** - * Indicates whether toObject/toDatalessObject should include default values - */ - includeDefaultValues?: boolean; /** * Overlay color of canvas instance. - * Should be set via setOverlayColor + * Should be set via {@link fabric.StaticCanvas#setOverlayColor} + * @since 1.3.9 + * @type {(String|fabric.Pattern)} */ overlayColor?: string | Pattern; /** * Overlay image of canvas instance. - * Should be set via setOverlayImage - * Backwards incompatibility note: The "overlayImageLeft" and "overlayImageTop" properties are deprecated since 1.3.9. + * Should be set via {@link fabric.StaticCanvas#setOverlayImage}. + * Backwards incompatibility note: The "overlayImageLeft" + * and "overlayImageTop" properties are deprecated since 1.3.9. + * Use {@link fabric.Image#left} and {@link fabric.Image#top}. + * since 2.4.0 image caching is active, please when putting an image as overlay, add to the + * canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom + * vale. As an alternative you can disable image objectCaching + * @type fabric.Image */ overlayImage?: Image; - overlayImageLeft?: number; - overlayImageTop?: number; /** - * Indicates whether add, insertAt and remove should also re-render canvas. - * Disabling this option could give a great performance boost when adding/removing a lot of objects to/from canvas at once - * (followed by a manual rendering after addition/deletion) + * Indicates whether toObject/toDatalessObject should include default values + * if set to false, takes precedence over the object value. + * @type Boolean + */ + includeDefaultValues?: boolean; + /** + * Indicates whether objects' state should be saved + * @type Boolean + */ + stateful?: boolean; + /** + * Indicates whether {@link fabric.Collection.add}, {@link fabric.Collection.insertAt} and {@link fabric.Collection.remove}, + * {@link fabric.StaticCanvas.moveTo}, {@link fabric.StaticCanvas.clear} and many more, should also re-render canvas. + * Disabling this option will not give a performance boost when adding/removing a lot of objects to/from canvas at once + * since the renders are quequed and executed one per frame. + * Disabling is suggested anyway and managing the renders of the app manually is not a big effort ( canvas.requestRenderAll() ) + * Left default to true to do not break documentation and old app, fiddles. + * @type Boolean */ renderOnAddRemove?: boolean; /** - * Indicates whether objects' state should be saved + * Function that determines clipping of entire canvas area + * Being passed context as first argument. + * If you are using code minification, ctx argument can be minified/manglied you should use + * as a workaround `var ctx = arguments[0];` in the function; + * See clipping canvas area in {@link https://github.com/kangax/fabric.js/wiki/FAQ} + * @deprecated since 2.0.0 + * @type Function */ - stateful?: boolean; + clipTo?(context: CanvasRenderingContext2D): void; + /** + * Indicates whether object controls (borders/controls) are rendered above overlay image + * @type Boolean + */ + controlsAboveOverlay?: boolean; + /** + * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas + * @type Boolean + */ + allowTouchScrolling?: boolean; + /** + * Indicates whether this canvas will use image smoothing, this is on by default in browsers + */ + imageSmoothingEnabled?: boolean; + /** + * The transformation (in the format of Canvas transform) which focuses the viewport + */ + viewportTransform?: number[]; + /** + * if set to false background image is not affected by viewport transform + * @since 1.6.3 + * @type Boolean + */ + backgroundVpt?: boolean; + /** + * if set to false overlay image is not affected by viewport transform + * @since 1.6.3 + * @type Boolean + */ + overlayVpt?: boolean; + /** + * When true, canvas is scaled by devicePixelRatio for better rendering on retina screens + * @type Boolean + */ + enableRetinaScaling?: boolean; + /** + * Describe canvas element extension over design + * properties are tl,tr,bl,br. + * if canvas is not zoomed/panned those points are the four corner of canvas + * if canvas is viewportTransformed you those points indicate the extension + * of canvas element in plain untrasformed coordinates + * The coordinates get updated with @method calcViewportBoundaries. + * @memberOf fabric.StaticCanvas.prototype + */ + vptCoords?: {tl: number, tr: number, bl: number, br: number} + /** + * Based on vptCoords and object.aCoords, skip rendering of objects that + * are not included in current viewport. + * May greatly help in applications with crowded canvas and use of zoom/pan + * If One of the corner of the bounding box of the object is on the canvas + * the objects get rendered. + * @memberOf fabric.StaticCanvas.prototype + * @type Boolean + */ + skipOffscreen?: boolean; + /** + * a fabricObject that, without stroke define a clipping area with their shape. filled in black + * the clipPath object gets used when the canvas has rendered, and the context is placed in the + * top left corner of the canvas. + * clipPath will clip away controls, if you do not want this to happen use controlsAboveOverlay = true + * @type fabric.Object + */ + clipPath?: Object; + /** + * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true, + * a zoomed canvas will then produce zoomed SVG output. + * @type Boolean + */ + svgViewportTransformation?: boolean; + } export interface StaticCanvas extends IObservable, IStaticCanvasOptions, ICollection, ICanvasAnimation { } export class StaticCanvas { /** * Constructor - * @param element element to initialize instance on - * @param [options] Options object + * @param {HTMLElement | String} el element to initialize instance on + * @param {Object} [options] Options object + * @return {Object} thisArg */ constructor(element: HTMLCanvasElement | string, options?: ICanvasOptions); /** * Calculates canvas element offset relative to the document * This method is also attached as "resize" event handler of window + * @return {fabric.Canvas} instance + * @chainable */ - calcOffset(): this; + calcOffset(): Canvas; /** * Sets {@link fabric.StaticCanvas#overlayImage|overlay image} for this canvas - * @param image fabric.Image instance or URL of an image to set overlay to - * @param callback callback to invoke when image is loaded and set as an overlay - * @param [options] Optional options to set for the {@link fabric.Image|overlay image}. + * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set overlay to + * @param {Function} callback callback to invoke when image is loaded and set as an overlay + * @param {Object} [options] Optional options to set for the {@link fabric.Image|overlay image}. + * @return {fabric.Canvas} thisArg + * @chainable */ - setOverlayImage(image: Image | string, callback: (img: HTMLImageElement) => void, options?: IImageOptions): this; + setOverlayImage(image: Image | string, callback: Function, options?: IImageOptions): Canvas; /** * Sets {@link fabric.StaticCanvas#backgroundImage|background image} for this canvas - * @param image fabric.Image instance or URL of an image to set background to - * @param callback Callback to invoke when image is loaded and set as background - * @param [options] Optional options to set for the {@link fabric.Image|background image}. + * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set background to + * @param {Function} callback Callback to invoke when image is loaded and set as background + * @param {Object} [options] Optional options to set for the {@link fabric.Image|background image}. + * @return {fabric.Canvas} thisArg + * @chainable */ - setBackgroundImage(image: Image | string, callback?: (img: HTMLImageElement) => void, options?: IImageOptions): this; + setBackgroundImage(image: Image | string, callback: Function, options?: IImageOptions): Canvas; /** - * Sets {@link fabric.StaticCanvas#overlayColor|background color} for this canvas - * @param overlayColor Color or pattern to set background color to - * @param callback Callback to invoke when background color is set + * Sets {@link fabric.StaticCanvas#overlayColor|foreground color} for this canvas + * @param {(String|fabric.Pattern)} overlayColor Color or pattern to set foreground color to + * @param {Function} callback Callback to invoke when foreground color is set + * @return {fabric.Canvas} thisArg + * @chainable */ - setOverlayColor(overlayColor: string | Pattern, callback: (pattern: Pattern | undefined) => void): this; + setOverlayColor(overlayColor: string | Pattern, callback: Function): Canvas; /** * Sets {@link fabric.StaticCanvas#backgroundColor|background color} for this canvas - * @param backgroundColor Color or pattern to set background color to - * @param callback Callback to invoke when background color is set + * @param {(String|fabric.Pattern)} backgroundColor Color or pattern to set background color to + * @param {Function} callback Callback to invoke when background color is set + * @return {fabric.Canvas} thisArg + * @chainable */ - setBackgroundColor(backgroundColor: string | Pattern, callback: (pattern: Pattern | undefined) => void): StaticCanvas; + setBackgroundColor(backgroundColor: string | Pattern, callback: Function): Canvas; /** * Returns canvas width (in px) + * @return {Number} */ getWidth(): number; /** * Returns canvas height (in px) + * @return {Number} */ getHeight(): number; /** * Sets width of this canvas instance - * @param value Value to set width to - * @param [options] Options object + * @param {Number|String} value Value to set width to + * @param {Object} [options] Options object + * @return {fabric.Canvas} instance + * @chainable true */ - setWidth(value: number | string, options?: ICanvasDimensionsOptions): this; + setWidth(value: number | string, options?: ICanvasDimensionsOptions): Canvas; /** * Sets height of this canvas instance * @param value Value to set height to * @param [options] Options object + * @return {fabric.Canvas} instance + * @chainable true */ - setHeight(value: number | string, options?: ICanvasDimensionsOptions): this; + setHeight(value: number | string, options?: ICanvasDimensionsOptions): Canvas; /** * Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em) * @param dimensions Object with width/height properties * @param [options] Options object + * @return {fabric.Canvas} thisArg + * @chainable */ - setDimensions(dimensions: ICanvasDimensions, options?: ICanvasDimensionsOptions): this; + setDimensions(dimensions: ICanvasDimensions, options?: ICanvasDimensionsOptions): Canvas; /** * Returns canvas zoom level @@ -1016,191 +1167,295 @@ export class StaticCanvas { /** * Sets viewport transform of this canvas instance - * @param vpt the transform in the form of context.transform + * @param {Array} vpt the transform in the form of context.transform + * @return {fabric.Canvas} instance + * @chainable */ - setViewportTransform(vpt: number[]): this; + setViewportTransform(vpt: number[]): Canvas; /** * Sets zoom level of this canvas instance, zoom centered around point - * @param point to zoom with respect to - * @param value to set zoom to, less than 1 zooms out + * @param {fabric.Point} point to zoom with respect to + * @param {Number} value to set zoom to, less than 1 zooms out + * @return {fabric.Canvas} instance + * @chainable true */ - zoomToPoint(point: Point, value: number): this; + zoomToPoint(point: Point, value: number): Canvas; /** * Sets zoom level of this canvas instance - * @param value to set zoom to, less than 1 zooms out + * @param {Number} value to set zoom to, less than 1 zooms out + * @return {fabric.Canvas} instance + * @chainable */ - setZoom(value: number): this; + setZoom(value: number): Canvas; /** * Pan viewport so as to place point at top left corner of canvas - * @param point to move to + * @param {fabric.Point} point to move to + * @return {fabric.Canvas} instance + * @chainable */ - absolutePan(point: Point): this; + absolutePan(point: Point): Canvas; /** * Pans viewpoint relatively - * @param point (position vector) to move by + * @param {fabric.Point} point (position vector) to move by + * @return {fabric.Canvas} instance + * @chainable */ - relativePan(point: Point): this; + relativePan(point: Point): Canvas; /** * Returns element corresponding to this instance + * @return {HTMLCanvasElement} */ getElement(): HTMLCanvasElement; - /** - * Returns currently selected object, if any - */ - getActiveObject(): Object; - - /** - * Returns currently selected group of object, if any - */ - getActiveGroup(): Group; - /** * Clears specified context of canvas element * @param ctx Context to clear * @chainable */ - clearContext(ctx: CanvasRenderingContext2D): this; + clearContext(ctx: CanvasRenderingContext2D): Canvas; /** * Returns context of canvas where objects are drawn + * @return {CanvasRenderingContext2D} */ getContext(): CanvasRenderingContext2D; /** * Clears all contexts (background, main, top) of an instance - */ - clear(): this; - - /** - * Renders both the top canvas and the secondary container canvas. - * @param [allOnTop] Whether we want to force all images to be rendered on the top canvas + * @return {fabric.Canvas} thisArg * @chainable */ - renderAll(allOnTop?: boolean): this; + clear(): Canvas; /** - * Append a renderAll request to next animation frame. a boolean flag will avoid appending more. + * Renders the canvas + * @return {fabric.Canvas} instance * @chainable */ - requestRenderAll(): this; + renderAll(): Canvas; /** - * Method to render only the top canvas. - * Also used to render the group selection box. + * Function created to be instance bound at initialization + * used in requestAnimationFrame rendering + * Let the fabricJS call it. If you call it manually you could have more + * animationFrame stacking on to of each other + * for an imperative rendering, use canvas.renderAll + * @private + * @return {fabric.Canvas} instance * @chainable */ - renderTop(): StaticCanvas; + renderAndReset(): Canvas; + + /** + * Append a renderAll request to next animation frame. + * unless one is already in progress, in that case nothing is done + * a boolean flag will avoid appending more. + * @return {fabric.Canvas} instance + * @chainable + */ + requestRenderAll(): Canvas; + + /** + * Calculate the position of the 4 corner of canvas with current viewportTransform. + * helps to determinate when an object is in the current rendering viewport using + * object absolute coordinates ( aCoords ) + * @return {Object} points.tl + * @chainable + */ + calcViewportBoundaries(): {tl: Point, br: Point, tr: Point, bl: Point}; + + /** + * Renders background, objects, overlay and controls. + * @param {CanvasRenderingContext2D} ctx + * @param {Array} objects to render + * @return {fabric.Canvas} instance + * @chainable + */ + renderCanvas(ctx: CanvasRenderingContext2D, objects: Object[] ): Canvas; + + /** + * Paint the cached clipPath on the lowerCanvasEl + * @param {CanvasRenderingContext2D} ctx Context to render on + */ + drawClipPathOnCanvas(ctx: CanvasRenderingContext2D): void; /** * Returns coordinates of a center of canvas. * Returned value is an object with top and left properties + * @return {Object} object with "top" and "left" number values */ getCenter(): { top: number; left: number; }; - /** - * Centers object horizontally. - * You might need to call `setCoords` on an object after centering, to update controls area. - * @param object Object to center horizontally - */ - centerObjectH(object: Object): this; /** - * Centers object vertically. - * You might need to call `setCoords` on an object after centering, to update controls area. - * @param object Object to center vertically + * Centers object horizontally in the canvas + * @param {fabric.Object} object Object to center horizontally + * @return {fabric.Canvas} thisArg */ - centerObjectV(object: Object): this; + centerObjectH(object: Object): Canvas; /** - * Centers object vertically and horizontally. - * You might need to call `setCoords` on an object after centering, to update controls area. - * @param object Object to center vertically and horizontally + * Centers object vertically in the canvas + * @param {fabric.Object} object Object to center vertically + * @return {fabric.Canvas} thisArg + * @chainable */ - centerObject(object: Object): this; + centerObjectV(object: Object): Canvas; + + /** + * Centers object vertically and horizontally in the canvas + * @param {fabric.Object} object Object to center vertically and horizontally + * @return {fabric.Canvas} thisArg + * @chainable + */ + centerObject(object: Object): Canvas; + + /** + * Centers object vertically and horizontally in the viewport + * @param {fabric.Object} object Object to center vertically and horizontally + * @return {fabric.Canvas} thisArg + * @chainable + */ + viewportCenterObject(object: Object): Canvas; + + /** + * Centers object horizontally in the viewport, object.top is unchanged + * @param {fabric.Object} object Object to center vertically and horizontally + * @return {fabric.Canvas} thisArg + * @chainable + */ + viewportCenterObjectH(object: Object): Canvas; + + /** + * Centers object Vertically in the viewport, object.top is unchanged + * @param {fabric.Object} object Object to center vertically and horizontally + * @return {fabric.Canvas} thisArg + * @chainable + */ + viewportCenterObjectV(object: Object): Canvas; + + /** + * Calculate the point in canvas that correspond to the center of actual viewport. + * @return {fabric.Point} vpCenter, viewport center + */ + getVpCenter(): Point; /** * Returs dataless JSON representation of canvas - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {String} json string */ toDatalessJSON(propertiesToInclude?: string[]): string; /** * Returns object representation of canvas - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance */ toObject(propertiesToInclude?: string[]): any; /** * Returns dataless object representation of canvas - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance */ toDatalessObject(propertiesToInclude?: string[]): any; - /** - * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true, - * a zoomed canvas will then produce zoomed SVG output. - */ - svgViewportTransformation: boolean; - /** * Returns SVG representation of canvas * @param [options] Options object for SVG output * @param [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation. + * @return {String} SVG string */ - toSVG(options: IToSVGOptions, reviver?: Function): string; + toSVG(options?: IToSVGOptions, reviver?: Function): string; /** - * Moves an object to the bottom of the stack of drawn objects - * @param object Object to send to back + * Moves an object or the objects of a multiple selection + * to the bottom of the stack of drawn objects + * @param {fabric.Object} object Object to send to back + * @return {fabric.Canvas} thisArg * @chainable */ - sendToBack(object: Object): this; + sendToBack(object: Object): Canvas; /** - * Moves an object to the top of the stack of drawn objects - * @param object Object to send + * Moves an object or the objects of a multiple selection + * to the top of the stack of drawn objects + * @param {fabric.Object} object Object to send + * @return {fabric.Canvas} thisArg * @chainable */ - bringToFront(object: Object): this; + bringToFront(object: Object): Canvas; /** - * Moves an object down in stack of drawn objects - * @param object Object to send - * @param [intersecting] If `true`, send object behind next lower intersecting object + * Moves an object or a selection down in stack of drawn objects + * An optional paramter, intersecting allowes to move the object in behind + * the first intersecting object. Where intersection is calculated with + * bounding box. If no intersection is found, there will not be change in the + * stack. + * @param {fabric.Object} object Object to send + * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object + * @return {fabric.Canvas} thisArg * @chainable */ - sendBackwards(object: Object): this; + sendBackwards(object: Object, intersecting?: boolean): Canvas; /** - * Moves an object up in stack of drawn objects - * @param object Object to send - * @param [intersecting] If `true`, send object in front of next upper intersecting object + * Moves an object or a selection up in stack of drawn objects + * An optional paramter, intersecting allowes to move the object in front + * of the first intersecting object. Where intersection is calculated with + * bounding box. If no intersection is found, there will not be change in the + * stack. + * @param {fabric.Object} object Object to send + * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object + * @return {fabric.Canvas} thisArg * @chainable */ - bringForward(object: Object): this; + bringForward(object: Object, intersecting?: boolean): Canvas; + /** * Moves an object to specified level in stack of drawn objects - * @param object Object to send - * @param index Position to move to + * @param {fabric.Object} object Object to send + * @param {Number} index Position to move to + * @return {fabric.Canvas} thisArg * @chainable */ - moveTo(object: Object, index: number): this; + moveTo(object: Object, index: number): Canvas; /** - * Clears a canvas element and removes all event listeners - */ - dispose(): this; + * Clears a canvas element and dispose objects + * @return {fabric.Canvas} thisArg + * @chainable */ + dispose(): Canvas; /** * Returns a string representation of an instance + * @return {String} string representation of an instance */ toString(): string; + /** + * @static + * @type String + * @default + */ + static EMPTY_JSON: string; + + /** + * Provides a way to check support of some of the canvas methods + * (either those of HTMLCanvasElement itself, or rendering context) + * + * @param {String} methodName Method to check support for; + * Could be one of "setLineDash" + * @return {Boolean | null} `true` if method is supported (or at least exists), + * `null` if canvas element or context can not be initialized + */ + supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; + /** * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately * @param [options] Options object @@ -1208,29 +1463,17 @@ export class StaticCanvas { toDataURL(options?: IDataURLOptions): string; /** - * Provides a way to check support of some of the canvas methods - * (either those of HTMLCanvasElement itself, or rendering context) - * @param methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" - * @return `true` if method is supported (or at least exists), null` if canvas element or context can not be initialized + * Returns JSON representation of canvas + * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; + static toJSON(propertiesToInclude?: string[]): string; - /** - * Populates canvas with data from the specified JSON. - * JSON format must conform to the one of toJSON formats - * @param json JSON string or object - * @param callback Callback, invoked when json is parsed - * and corresponding objects (e.g: {@link fabric.Image}) - * are initialized - * @param [reviver] Method for further parsing of JSON elements, called after each fabric object created. - */ - loadFromJSON(json: string | any, callback: () => void, reviver?: Function): this; /** * Clones canvas instance * @param [callback] Receives cloned instance as a first argument * @param [properties] Array of properties to include in the cloned canvas and children */ - clone(callback: (canvas: StaticCanvas) => void, properties?: string[]): void; + clone(callback?: any, properties?: string[]): void; /** * Clones canvas instance without cloning existing data. @@ -1238,48 +1481,72 @@ export class StaticCanvas { * but leaves data empty (so that you can populate it with your own) * @param [callback] Receives cloned instance as a first argument */ - cloneWithoutData(callback: (canvas: StaticCanvas) => void): void; + cloneWithoutData(callback?: any): void; /** - * Callback; invoked right before object is about to be scaled/rotated + * Populates canvas with data from the specified dataless JSON. + * JSON format must conform to the one of {@link fabric.Canvas#toDatalessJSON} + * @deprecated since 1.2.2 + * @param {String|Object} json JSON string or object + * @param {Function} callback Callback, invoked when json is parsed + * and corresponding objects (e.g: {@link fabric.Image}) + * are initialized + * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created. + * @return {fabric.Canvas} instance + * @chainable + * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#deserialization} */ - onBeforeScaleRotate(target: Object): void; - - // Functions from object straighten mixin - // -------------------------------------------------------------------------------------------------------------------------------- - + loadFromDatalessJSON(json: any, callback: Function, reviver?: Function): Canvas; + /** + * Populates canvas with data from the specified JSON. + * JSON format must conform to the one of {@link fabric.Canvas#toJSON} + * @param {String|Object} json JSON string or object + * @param {Function} callback Callback, invoked when json is parsed + * and corresponding objects (e.g: {@link fabric.Image}) + * are initialized + * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created. + * @return {fabric.Canvas} instance + */ + loadFromJSON(json: any, callback: Function, reviver?: Function): Canvas; + /** + * Creates markup containing SVG font faces, + * font URLs for font faces must be collected by developers + * and are not extracted from the DOM by fabricjs + * @param {Array} objects Array of fabric objects + * @return {String} + */ + createSVGFontFacesMarkup(objects: any[]): string; + /** + * Creates markup containing SVG referenced elements like patterns, gradients etc. + * @return {String} + */ + createSVGRefElementsMarkup(): string; /** * Straightens object, then rerenders canvas - * @param object Object to straighten + * @param {fabric.Object} object Object to straighten + * @return {fabric.Canvas} thisArg + * @chainable */ - straightenObject(object: Object): this; - - /** - * Same as straightenObject, but animated - * @param object Object to straighten - */ - fxStraightenObject(object: Object): this; - - static EMPTY_JSON: string; - /** - * Provides a way to check support of some of the canvas methods - * (either those of HTMLCanvasElement itself, or rendering context) - * @param methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" - */ - static supports(methodName: "getImageData" | "toDataURL" | "toDataURLWithQuality" | "setLineDash"): boolean; - /** - * Returns JSON representation of canvas - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - static toJSON(propertiesToInclude?: string[]): string; + straightenObject(object: Object): Canvas; } interface ICanvasOptions extends IStaticCanvasOptions { /** * When true, objects can be transformed by one side (unproportionally) + * @type Boolean */ uniScaleTransform?: boolean; + /** + * Indicates which key enable unproportional scaling + * values: 'altKey', 'shiftKey', 'ctrlKey'. + * If `null` or 'none' or any other string that is not a modifier key + * feature is disabled feature disabled. + * @since 1.6.2 + * @type String + */ + uniScaleKey?: string; + /** * When true, objects use center point as the origin of scale transformation. * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). @@ -1292,6 +1559,28 @@ interface ICanvasOptions extends IStaticCanvasOptions { */ centeredRotation?: boolean; + /** + * Indicates which key enable centered Transform + * values: 'altKey', 'shiftKey', 'ctrlKey'. + * If `null` or 'none' or any other string that is not a modifier key + * feature is disabled feature disabled. + * @since 1.6.2 + * @type String + * @default + */ + centeredKey?: string; + + /** + * Indicates which key enable alternate action on corner + * values: 'altKey', 'shiftKey', 'ctrlKey'. + * If `null` or 'none' or any other string that is not a modifier key + * feature is disabled feature disabled. + * @since 1.6.2 + * @type String + * @default + */ + altActionKey?: string; + /** * Indicates that canvas is interactive. This property should not be changed. */ @@ -1302,6 +1591,32 @@ interface ICanvasOptions extends IStaticCanvasOptions { */ selection?: boolean; + /** + * Indicates which key or keys enable multiple click selection + * Pass value as a string or array of strings + * values: 'altKey', 'shiftKey', 'ctrlKey'. + * If `null` or empty or containing any other string that is not a modifier key + * feature is disabled. + * @since 1.6.2 + * @type String|Array + * @default + */ + selectionKey?: string | string[]; + + /** + * Indicates which key enable alternative selection + * in case of target overlapping with active object + * values: 'altKey', 'shiftKey', 'ctrlKey'. + * For a series of reason that come from the general expectations on how + * things should work, this feature works only for preserveObjectStacking true. + * If `null` or 'none' or any other string that is not a modifier key + * feature is disabled. + * @since 1.6.5 + * @type null|String + * @default + */ + altSelectionKey?: string | null; + /** * Color of selection */ @@ -1311,7 +1626,7 @@ interface ICanvasOptions extends IStaticCanvasOptions { * Default dash array pattern * If not empty the selection border is dashed */ - selectionDashArray?: any[]; + selectionDashArray?: number[]; /** * Color of the border of selection (usually slightly darker than color of selection itself) @@ -1323,6 +1638,13 @@ interface ICanvasOptions extends IStaticCanvasOptions { */ selectionLineWidth?: number; + /** + * Select only shapes that are fully contained in the dragged selection rectangle. + * @type Boolean + * @default + */ + selectionFullyContained?: boolean; + /** * Default cursor value used when hovering over an object on canvas */ @@ -1348,6 +1670,14 @@ interface ICanvasOptions extends IStaticCanvasOptions { */ rotationCursor?: string; + /** + * Cursor value used for disabled elements ( corners with disabled action ) + * @type String + * @since 2.0.0 + * @default + */ + notAllowedCursor?: string; + /** * Default element class that's given to wrapper (div) element of canvas */ @@ -1374,6 +1704,54 @@ interface ICanvasOptions extends IStaticCanvasOptions { * and then mouseup finalizes it and adds an instance of `fabric.Path` onto canvas. */ isDrawingMode?: boolean; + + /** + * Indicates whether objects should remain in current stack position when selected. + * When false objects are brought to top and rendered as part of the selection group + * @type Boolean + */ + preserveObjectStacking?: boolean; + + /** + * Indicates the angle that an object will lock to while rotating. + * @type Number + * @since 1.6.7 + */ + snapAngle?: number; + + /** + * Indicates the distance from the snapAngle the rotation will lock to the snapAngle. + * When `null`, the snapThreshold will default to the snapAngle. + * @type null|Number + * @since 1.6.7 + * @default + */ + snapThreshold?: null | number; + + /** + * Indicates if the right click on canvas can output the context menu or not + * @type Boolean + * @since 1.6.5 + * @default + */ + stopContextMenu?: boolean; + + /** + * Indicates if the canvas can fire right click events + * @type Boolean + * @since 1.6.5 + * @default + */ + fireRightClick?: boolean; + + /** + * Indicates if the canvas can fire middle click events + * @type Boolean + * @since 1.7.8 + * @default + */ + fireMiddleClick?: boolean; + } export interface Canvas extends StaticCanvas { } export interface Canvas extends ICanvasOptions { } @@ -1386,106 +1764,129 @@ export class Canvas { constructor(element: HTMLCanvasElement | string, options?: ICanvasOptions); _objects: Object[]; - /** - * Checks if point is contained within an area of given object - * @param e Event object - * @param target Object to test against - */ - containsPoint(e: Event, target: Object): boolean; - /** - * Deactivates all objects on canvas, removing any active group or object - * @return thisArg - */ - deactivateAll(): Canvas; - /** - * Deactivates all objects and dispatches appropriate events - * @param [e] Event (passed along when firing) - * @return thisArg - */ - deactivateAllWithDispatch(e?: Event): Canvas; - /** - * Discards currently active group - * @param [e] Event (passed along when firing) - * @return thisArg - */ - discardActiveGroup(e?: Event): Canvas; - /** - * Discards currently active object - * @param [e] Event (passed along when firing) - * @return thisArg + * Renders both the top canvas and the secondary container canvas. + * @return {fabric.Canvas} instance * @chainable */ - discardActiveObject(e?: Event): Canvas; + renderAll(): Canvas; /** - * Draws objects' controls (borders/controls) - * @param ctx Context to render controls on + * Method to render only the top canvas. + * Also used to render the group selection box. + * @return {fabric.Canvas} thisArg + * @chainable */ - drawControls(ctx: CanvasRenderingContext2D): void; + renderTop(): Canvas; + /** + * Checks if point is contained within an area of given object + * @param {Event} e Event object + * @param {fabric.Object} target Object to test against + * @param {Object} [point] x,y object of point coordinates we want to check. + * @return {Boolean} true if point is contained within an area of given object + */ + containsPoint(e: Event, target: Object, point?: {x: number, y: number}): boolean; + /** + * Returns true if object is transparent at a certain location + * @param {fabric.Object} target Object to check + * @param {Number} x Left coordinate + * @param {Number} y Top coordinate + * @return {Boolean} + */ + isTargetTransparent(target: Object, x: number, y: number): boolean; + /** + * Set the cursor type of the canvas element + * @param {String} value Cursor type of the canvas element. + * @see http://www.w3.org/TR/css3-ui/#cursor + */ + setCursor(value: string): void; /** * Method that determines what object we are clicking on - * @param e mouse event - * @param skipGroup when true, group is skipped and only objects are traversed through + * the skipGroup parameter is for internal use, is needed for shift+click action + * @param {Event} e mouse event + * @param {Boolean} skipGroup when true, activeGroup is skipped and only objects are traversed through + * @return {fabric.Object} the target found */ - findTarget(e: MouseEvent, skipGroup: boolean): Canvas; + findTarget(e: MouseEvent, skipGroup: boolean): Object; /** - * Returns currently active group - * @return Current group + * Returns pointer coordinates without the effect of the viewport + * @param {Object} pointer with "x" and "y" number values + * @return {Object} object with "x" and "y" number values */ - getActiveGroup(): Group; - /** - * Returns currently active object - * @return active object - */ - getActiveObject(): Object; - /** - * Returns an array with the current selected objects - * @return {Object[]} array of active objects - */ - getActiveObjects(): Object[]; + restorePointerVpt(pointer: Point): any; /** * Returns pointer coordinates relative to canvas. - * @return object with "x" and "y" number values + * Can return coordinates with or without viewportTransform. + * ignoreZoom false gives back coordinates that represent + * the point clicked on canvas element. + * ignoreZoom true gives back coordinates after being processed + * by the viewportTransform ( sort of coordinates of what is displayed + * on the canvas where you are clicking. + * ignoreZoom true = HTMLElement coordinates relative to top,left + * ignoreZoom false, default = fabric space coordinates, the same used for shape position + * To interact with your shapes top and left you want to use ignoreZoom true + * most of the time, while ignoreZoom false will give you coordinates + * compatible with the object.oCoords system. + * of the time. + * @param {Event} e + * @param {Boolean} ignoreZoom + * @return {Object} object with "x" and "y" number values */ - getPointer(e: Event, ignoreZoom?: boolean, upperCanvasEl?: CanvasRenderingContext2D): { x: number; y: number; }; + getPointer(e: Event, ignoreZoom?: boolean): { x: number; y: number; }; /** * Returns context of canvas where object selection is drawn + * @return {CanvasRenderingContext2D} */ getSelectionContext(): CanvasRenderingContext2D; /** * Returns element on which object selection is drawn + * @return {HTMLCanvasElement} */ getSelectionElement(): HTMLCanvasElement; /** - * Returns true if object is transparent at a certain location - * @param target Object to check - * @param x Left coordinate - * @param y Top coordinate + * Returns currently active object + * @return {fabric.Object} active object */ - isTargetTransparent(target: Object, x: number, y: number): boolean; + getActiveObject(): Object; /** - * Sets active group to a speicified one - * @param group Group to set as a current one - * @param [e] Event (passed along when firing) + * Returns an array with the current selected objects + * @return {fabric.Object} active object */ - setActiveGroup(group: Group, e?: Event): Canvas; + getActiveObjects(): Object[]; /** * Sets given object as the only active object on canvas - * @param object Object to set as an active one - * @param [e] Event (passed along when firing "object:selected") + * @param {fabric.Object} object Object to set as an active one + * @param {Event} [e] Event (passed along when firing "object:selected") + * @return {fabric.Canvas} thisArg + * @chainable */ setActiveObject(object: Object, e?: Event): Canvas; /** - * Set the cursor type of the canvas element - * @param value Cursor type of the canvas element. - * @see http://www.w3.org/TR/css3-ui/#cursor + * Discards currently active object and fire events. If the function is called by fabric + * as a consequence of a mouse event, the event is passed as a parameter and + * sent to the fire function for the custom events. When used as a method the + * e param does not have any application. + * @param {event} e + * @return {fabric.Canvas} thisArg + * @chainable */ - setCursor(value: string): void; - + discardActiveObject(e?: Event): Canvas; /** - * Removes all event listeners + * Clears a canvas element and removes all event listeners + * @return {fabric.Canvas} thisArg + * @chainable */ - removeListeners(): void; + dispose(): Canvas; + /** + * Clears all contexts (background, main, top) of an instance + * @return {fabric.Canvas} thisArg + * @chainable + */ + clear(): Canvas; + /** + * Draws objects' controls (borders/controls) + * @param {CanvasRenderingContext2D} ctx Context to render controls on + */ + drawControls(ctx: CanvasRenderingContext2D): void; static EMPTY_JSON: string; /** @@ -1499,6 +1900,10 @@ export class Canvas { * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ static toJSON(propertiesToInclude?: string[]): string; + /** + * Removes all event listeners + */ + removeListeners(): void; } /////////////////////////////////////////////////////////////////////////////// @@ -1514,7 +1919,6 @@ interface ICircleOptions extends IObjectOptions { * Start angle of the circle, moving clockwise */ startAngle?: number; - /** * End angle of the circle */ @@ -1523,12 +1927,6 @@ interface ICircleOptions extends IObjectOptions { export interface Circle extends Object, ICircleOptions { } export class Circle { constructor(options?: ICircleOptions); - - /** - * Returns complexity of an instance - * @return complexity of this instance - */ - complexity(): number; /** * Returns horizontal radius of an object (according to how an object is scaled) */ @@ -1541,20 +1939,12 @@ export class Circle { * Sets radius of an object (and updates width accordingly) */ setRadius(value: number): number; - - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; /** * Returns svg representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance + * @return {Array} an array of strings with the specific svg representation + * of the instance */ - toSVG(reviver?: Function): string; - + _toSVG(): string; /** * List of attribute names to account for when parsing SVG element (used by {@link fabric.Circle.fromElement}) */ @@ -1585,88 +1975,65 @@ interface IEllipseOptions extends IObjectOptions { export interface Ellipse extends Object, IEllipseOptions { } export class Ellipse { constructor(options?: IEllipseOptions); - /** * Returns horizontal radius of an object (according to how an object is scaled) */ getRx(): number; - /** * Returns Vertical radius of an object (according to how an object is scaled) */ getRy(): number; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; /** * Returns svg representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance + * @return {Array} an array of strings with the specific svg representation + * of the instance */ - toSVG(reviver?: Function): string; - /** - * Returns complexity of an instance - * @return complexity - */ - complexity(): number; - + _toSVG(): string; /** * List of attribute names to account for when parsing SVG element (used by {@link fabric.Ellipse.fromElement}) */ static ATTRIBUTE_NAMES: string[]; - /** * Returns Ellipse instance from an SVG element * @param element Element to parse * @param [options] Options object */ static fromElement(element: SVGElement, options?: IEllipseOptions): Ellipse; - /** * Returns Ellipse instance from an object representation * @param object Object to create an instance from */ static fromObject(object: any): Ellipse; } - -export interface Group extends Object, ICollection { } +interface IGroupOptions extends IObjectOptions { + /** + * Indicates if click events should also check for subtargets + * @type Boolean + */ + subTargetCheck?: boolean; + /** + * setOnGroup is a method used for TextBox that is no more used since 2.0.0 The behavior is still + * available setting this boolean to true. + * @type Boolean + * @since 2.0.0 + * @default + */ + useSetOnGroup?: boolean; +} +export interface Group extends Object, ICollection, IGroupOptions { } export class Group { /** * Constructor * @param objects Group objects * @param [options] Options object */ - constructor(items?: any[], options?: IObjectOptions); - - activateAllObjects(): Group; + constructor(objects?: Object[], options?: IGroupOptions, isAlreadyGrouped?: boolean); /** * Adds an object to a group; Then recalculates group's dimension, position. * @return thisArg * @chainable */ addWithUpdate(object: Object): Group; - containsPoint(point: Point): boolean; - /** - * Destroys a group (restoring state of its objects) - * @return thisArg - * @chainable - */ - destroy(): Group; - /** - * make a group an active selection, remove the group from canvas - * the group has to be on canvas for this to work. - * @return {fabric.ActiveSelection} thisArg - * @chainable - */ - toActiveSelection(): ActiveSelection; - /** - * Checks whether this group was moved (since `saveCoords` was called last) - * @return true if an object was moved (since fabric.Group#saveCoords was called) - */ - hasMoved(): boolean; /** * Removes an object from a group; Then recalculates group's dimension, position. * @return thisArg @@ -1679,42 +2046,79 @@ export class Group { */ render(ctx: CanvasRenderingContext2D): void; /** - * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`) - * @param object Zero or more fabric instances - * @return thisArg - * @chainable + * Decide if the object should cache or not. Create its own cache level + * objectCaching is a global flag, wins over everything + * needsItsOwnCache should be used when the object drawing method requires + * a cache step. None of the fabric classes requires it. + * Generally you do not cache objects in groups because the group outside is cached. + * @return {Boolean} */ - remove(...object: Object[]): Group; + shouldCache(): boolean; /** - * Saves coordinates of this instance (to be used together with `hasMoved`) - * @saveCoords - * @return thisArg + * Check if this object or a child object will cast a shadow + * @return {Boolean} + */ + willDrawShadow(): boolean; + /** + * Check if this group or its parent group are caching, recursively up + * @return {Boolean} + */ + isOnACache(): boolean; + /** + * Execute the drawing operation for an object on a specified context + * @param {CanvasRenderingContext2D} ctx Context to render on + */ + drawObject(ctx: CanvasRenderingContext2D): void; + /** + * Check if cache is dirty + */ + isCacheDirty(skipCanvas?: boolean): boolean; + /** + * Realises the transform from this group onto the supplied object + * i.e. it tells you what would happen if the supplied object was in + * the group, and then the group was destroyed. It mutates the supplied + * object. + * @param {fabric.Object} object + * @return {fabric.Object} transformedObject + */ + realizeTransform(object: Object): Object; + /** + * Destroys a group (restoring state of its objects) + * @return {fabric.Group} thisArg * @chainable */ - saveCoords(): Group; + destroy(): Group; + /** + * make a group an active selection, remove the group from canvas + * the group has to be on canvas for this to work. + * @return {fabric.ActiveSelection} thisArg + * @chainable + */ + toActiveSelection(): ActiveSelection; + /** + * Destroys a group (restoring state of its objects) + * @return {fabric.Group} thisArg + * @chainable + */ + ungroupOnCanvas(): Group; /** * Sets coordinates of all group objects * @return thisArg * @chainable */ setObjectsCoords(): Group; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns string represenation of a group - */ - toString(): string; /** * Returns svg representation of an instance * @param [reviver] Method for further parsing of svg representation. * @return svg representation of an instance */ toSVG(reviver?: Function): string; - + /** + * Returns svg clipPath representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toClipPathSVG(reviver?: Function): string; /** * Returns {@link fabric.Group} instance from an object representation * @param object Object to create a group from @@ -1726,42 +2130,33 @@ export class Group { /////////////////////////////////////////////////////////////////////////////// // ActiveSelection ////////////////////////////////////////////////////////////////////////////// -export interface ActiveSelection extends Object, ICollection { } +export interface ActiveSelection extends Group, ICollection { } export class ActiveSelection { /** * Constructor * @param objects ActiveSelection objects * @param [options] Options object */ - constructor(items?: Object[], options?: IObjectOptions); - + constructor(objects?: Object[], options?: IObjectOptions); /** - * Change te activeSelection to a normal group, - * High level function that automatically adds it to canvas as - * active object. no events fired. - */ + * Change te activeSelection to a normal group, + * High level function that automatically adds it to canvas as + * active object. no events fired. + */ toGroup(): Group; - /** - * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`) - * @param object Zero or more fabric instances - * @return thisArg - * @chainable + * If returns true, deselection is cancelled. + * @since 2.0.0 + * @return {Boolean} [cancel] */ - remove(...object: Object[]): Group; - - /** - * Returns string represenation of a group - */ - toString(): string; - + onDeselect(): boolean; /** * Returns {@link fabric.ActiveSelection} instance from an object representation * @memberOf fabric.ActiveSelection * @param object Object to create a group from * @param [callback] Callback to invoke when an ActiveSelection instance is created */ - static fromObject(object: Group, callback: (activeSelection: ActiveSelection) => void): void; + static fromObject(object: any, callback: Function): void; } interface IImageOptions extends IObjectOptions { @@ -1769,26 +2164,38 @@ interface IImageOptions extends IObjectOptions { * crossOrigin value (one of "", "anonymous", "allow-credentials") */ crossOrigin?: string; - /** - * AlignX value, part of preserveAspectRatio (one of "none", "mid", "min", "max") - * This parameter defines how the picture is aligned to its viewport when image element width differs from image width. + * When calling {@link fabric.Image.getSrc}, return value from element src with `element.getAttribute('src')`. + * This allows for relative urls as image src. + * @since 2.7.0 + * @type Boolean */ - alignX?: string; - + srcFromAttribute?: boolean; /** - * AlignY value, part of preserveAspectRatio (one of "none", "mid", "min", "max") - * This parameter defines how the picture is aligned to its viewport when image element height differs from image height. + * minimum scale factor under which any resizeFilter is triggered to resize the image + * 0 will disable the automatic resize. 1 will trigger automatically always. + * number bigger than 1 are not implemented yet. + * @type Number */ - alignY?: string; - + minimumScaleTrigger?: number; /** - * meetOrSlice value, part of preserveAspectRatio (one of "meet", "slice"). - * if meet the image is always fully visibile, if slice the viewport is always filled with image. - * @see http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute + * key used to retrieve the texture representing this image + * @since 2.0.0 + * @type String */ - meetOrSlice?: string; - + cacheKey?: string; + /** + * Image crop in pixels from original image size. + * @since 2.0.0 + * @type Number + */ + cropX?: number; + /** + * Image crop in pixels from original image size. + * @since 2.0.0 + * @type Number + */ + cropY?: number; /** * Image filter array */ @@ -1801,44 +2208,12 @@ export class Image { * @param element Image element * @param [options] Options object */ - constructor(element: HTMLImageElement, objObjects: IObjectOptions); - - initialize(element?: string | HTMLImageElement, options?: IImageOptions): void; - /** - * Applies filters assigned to this image (from "filters" array) or from filter param - * @param {Array} filters to be applied - * @return {thisArg} return the fabric.Image object - * @chainable - */ - applyFilters(filters?: IBaseFilter[]): Image; - /** - * Returns a clone of an instance - * @param callback Callback is invoked with a clone as a first argument - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - clone(callback?: Function, propertiesToInclude?: string[]): void; - /** - * Returns complexity of an instance - * @return complexity of this instance - */ - complexity(): number; + constructor(element?: string | HTMLImageElement, options?: IImageOptions); /** * Returns image element which this instance if based on * @return Image element */ getElement(): HTMLImageElement; - /** - * Returns original size of an image - * @return Object with "width" and "height" properties - */ - getOriginalSize(): { width: number; height: number; }; - /** - * Returns source of an image - * @return Source of an image - */ - getSrc(): string; - render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; - /** * Sets image element for this instance to a specified one. * If filters defined they are applied to new image. @@ -1847,35 +2222,63 @@ export class Image { * @param [options] Options object */ setElement(element: HTMLImageElement, callback: Function, options: IImageOptions): Image; + /** + * Delete a single texture if in webgl mode + */ + removeTexture(key: any): void; + /** + * Delete textures, reference to elements and eventually JSDOM cleanup + */ + dispose(): void; /** * Sets crossOrigin value (on an instance and corresponding image element) */ setCrossOrigin(value: string): Image; /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return Object representation of an instance + * Returns original size of an image + * @return Object with "width" and "height" properties */ - toObject(propertiesToInclude?: string[]): any; + getOriginalSize(): { width: number; height: number; }; /** - * Returns string representation of an instance - * @return String representation of an instance + * Returns true if an image has crop applied, inspecting values of cropX,cropY,width,hight. + * @return {Boolean} */ - toString(): string; + hasCrop(): boolean; /** - * Returns SVG representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance + * Returns svg representation of an instance + * @return {Array} an array of strings with the specific svg representation + * of the instance */ - toSVG(reviver?: Function): string; + _toSVG(): string; + /** + * Returns source of an image + * @return Source of an image + */ + getSrc(): string; /** * Sets source of an image - * @param src Source string (URL) - * @param [callback] Callback is invoked when image has been loaded (and all filters have been applied) - * @param [options] Options object + * @param {String} src Source string (URL) + * @param {Function} [callback] Callback is invoked when image has been loaded (and all filters have been applied) + * @param {Object} [options] Options object + * @return {fabric.Image} thisArg + * @chainable */ setSrc(src: string, callback?: Function, options?: IImageOptions): Image; - + applyResizeFilters(): void; + /** + * Applies filters assigned to this image (from "filters" array) or from filter param + * @param {Array} filters to be applied + * @return {thisArg} return the fabric.Image object + * @chainable + */ + applyFilters(filters?: IBaseFilter[]): Image; + /** + * Calculate offset for center and scale factor for the image in order to respect + * the preserveAspectRatio attribute + * @private + * @return {Object} + */ + parsePreserveAspectRatioAttribute(): any; /** * Creates an instance of fabric.Image from an URL string * @param url URL to create an image from @@ -1883,44 +2286,38 @@ export class Image { * @param [imgOptions] Options object */ static fromURL(url: string, callback?: (image: Image) => void, imgOptions?: IImageOptions): Image; - /** - * Creates an instance of fabric.Image from its object representation - * @param object Object to create an instance from - * @param [callback] Callback to invoke when an image instance is created - */ - static fromObject(object: any, callback: (image: Image) => void): void; /** * Returns Image instance from an SVG element * @param element Element to parse * @param callback Callback to execute when fabric.Image object is created * @param [options] Options object */ - static fromElement(element: SVGElement, callback: (image: Image) => void, options?: IImageOptions): void; + static fromElement(element: SVGElement, callback: Function, options?: IImageOptions): Image; /** * Default CSS class name for canvas */ static CSS_CANVAS: string; - static filters: IAllFilters; + static ATTRIBUTE_NAMES: string[]; } interface ILineOptions extends IObjectOptions { /** * x value or first line edge */ - x1: number; + x1?: number; /** * x value or second line edge */ - x2: number; + x2?: number; /** * y value or first line edge */ - y1: number; + y1?: number; /** * y value or second line edge */ - y2: number; + y2?: number; } export interface Line extends Object, ILineOptions { } export class Line { @@ -1929,39 +2326,32 @@ export class Line { * @param [points] Array of points * @param [options] Options object */ - constructor(points?: number[], objObjects?: IObjectOptions); + constructor(points?: number[], objObjects?: ILineOptions); /** - * Returns complexity of an instance - * @return complexity + * Returns svg representation of an instance + * @return {Array} an array of strings with the specific svg representation + * of the instance */ - complexity(): number; - initialize(points?: number[], options?: ILineOptions): Line; - /** - * Returns object representation of an instance - * @methd toObject - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude: string[]): any; - /** - * Returns SVG representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - - static ATTRIBUTE_NAMES: string[]; + _toSVG(): string; /** * Returns fabric.Line instance from an SVG element - * @param element Element to parse - * @param [options] Options object + * @static + * @memberOf fabric.Line + * @param {SVGElement} element Element to parse + * @param {Object} [options] Options object + * @param {Function} [callback] callback function invoked after parsing */ - static fromElement(element: SVGElement, options?: ILineOptions): Line; + static fromElement(element: SVGElement, callback?: Function, options?: ILineOptions): Line; /** * Returns fabric.Line instance from an object representation * @param object Object to create an instance from */ static fromObject(object: any): Line; + static ATTRIBUTE_NAMES: string[]; + /** + * Produces a function that calculates distance from canvas edge to Line origin. + */ + makeEdgeToOriginGetter(propertyNames: {origin: number, axis1: any, axis2: any, dimension: any}, originValues: {nearest: any, center: any, farthest: any}): Function; } interface IObjectOptions { @@ -2012,17 +2402,7 @@ interface IObjectOptions { */ scaleY?: number; - /** - * Object skew factor (horizontal) - */ - skewX?: number; - - /** - * Object skew factor (vertical) - */ - skewY?: number; - - /** + /** * When true, an object is rendered as flipped horizontally */ flipX?: boolean; @@ -2042,6 +2422,21 @@ interface IObjectOptions { */ angle?: number; + /** + * Object skew factor (horizontal) + */ + skewX?: number; + + /** + * Object skew factor (vertical) + */ + skewY?: number; + + /** + * Size of object's controlling corners (in pixels) + */ + cornerSize?: number; + /** * When true, object's controlling corners are rendered as transparent inside (i.e. stroke instead of fill) */ @@ -2052,6 +2447,11 @@ interface IObjectOptions { */ hoverCursor?: string; + /** + * Default cursor value used when moving an object on canvas + */ + moveCursor?: string; + /** * Padding between object and its controlling borders (in pixels) */ @@ -2062,26 +2462,16 @@ interface IObjectOptions { */ borderColor?: string; - /** - * Array specifying dash pattern of an object's border (hasBorder must be true) - */ - borderDashArray?: number[]; + /** + * Array specifying dash pattern of an object's border (hasBorder must be true) + */ + borderDashArray?: number[]; /** * Color of controlling corners of an object (when it's active) */ cornerColor?: string; - /** - * Array specifying dash pattern of an object's control (hasBorder must be true) - */ - cornerDashArray?: number[]; - - /** - * Size of object's controlling corners (in pixels) - */ - cornerSize?: number; - /** * Color of controlling corners of an object (when it's active and transparentCorners false) */ @@ -2092,6 +2482,11 @@ interface IObjectOptions { */ cornerStyle?: "rect" | "circle"; + /** + * Array specifying dash pattern of an object's control (hasBorder must be true) + */ + cornerDashArray?: number[]; + /** * When true, this object will use center point as the origin of transformation * when being scaled via the controls. @@ -2129,9 +2524,11 @@ interface IObjectOptions { backgroundColor?: string; /** - * When `true`, object is cached on an additional canvas. + * Selection Background color of an object. colored layer behind the object when it is active. + * does not mix good with globalCompositeOperation methods. + * @type String */ - objectCaching?: boolean; + selectionBackgroundColor?: string; /** * When defined, an object is rendered via stroke and this property specifies its color @@ -2146,7 +2543,14 @@ interface IObjectOptions { /** * Array specifying dash pattern of an object's stroke (stroke must be defined) */ - strokeDashArray?: any[]; + strokeDashArray?: number[]; + + /** + * Line offset of an object's stroke + * @type Number + * @default + */ + strokeDashOffset?: number; /** * Line endings style of an object's stroke (one of "butt", "round", "square") @@ -2240,20 +2644,7 @@ interface IObjectOptions { */ clipTo?: Function; - /** - * A fabricObject that, without stroke define a clipping area with their shape. filled in black - * the clipPath object gets used when the object has rendered, and the context is placed in the center - * of the object cacheCanvas. - * If you want 0,0 of a clipPath to align with an object center, use clipPath.originX/Y to 'center' - */ - clipPath?: Object; - - /** - * When set to `true`, object's cache will be rerendered next render call. - */ - dirty?: boolean; - - /** + /** * When `true`, object horizontal movement is locked */ lockMovementX?: boolean; @@ -2283,11 +2674,126 @@ interface IObjectOptions { */ lockUniScaling?: boolean; + /** + * When `true`, object horizontal skewing is locked + * @type Boolean + */ + lockSkewingX?: boolean; + + /** + * When `true`, object vertical skewing is locked + * @type Boolean + */ + lockSkewingY?: boolean; + /** * When `true`, object cannot be flipped by scaling into negative values */ lockScalingFlip?: boolean; + /** + * When `true`, object is not exported in OBJECT/JSON + * since 1.6.3 + * @type Boolean + * @default + */ + excludeFromExport?: boolean; + + /** + * When `true`, object is cached on an additional canvas. + */ + objectCaching?: boolean; + + /** + * When `true`, object properties are checked for cache invalidation. In some particular + * situation you may want this to be disabled ( spray brush, very big, groups) + * or if your application does not allow you to modify properties for groups child you want + * to disable it for groups. + * default to false + * since 1.7.0 + * @type Boolean + * @default false + */ + statefullCache?: boolean; + + /** + * When `true`, cache does not get updated during scaling. The picture will get blocky if scaled + * too much and will be redrawn with correct details at the end of scaling. + * this setting is performance and application dependant. + * default to true + * since 1.7.0 + * @type Boolean + */ + noScaleCache?: boolean; + + /** + * When `false`, the stoke width will scale with the object. + * When `true`, the stroke will always match the exact pixel size entered for stroke width. + * default to false + * @since 2.6.0 + * @type Boolean + * @default false + * @type Boolean + */ + strokeUniform?: boolean; + + /** + * When set to `true`, object's cache will be rerendered next render call. + */ + dirty?: boolean; + + /** + * Determines if the fill or the stroke is drawn first (one of "fill" or "stroke") + * @type String + */ + paintFirst?: string; + + /** + * List of properties to consider when checking if state + * of an object is changed (fabric.Object#hasStateChanged) + * as well as for history (undo/redo) purposes + * @type Array + */ + stateProperties?: string[]; + + /** + * List of properties to consider when checking if cache needs refresh + * Those properties are checked by statefullCache ON ( or lazy mode if we want ) or from single + * calls to Object.set(key, value). If the key is in this list, the object is marked as dirty + * and refreshed at the next render + * @type Array + */ + cacheProperties?: string[]; + + /** + * A fabricObject that, without stroke define a clipping area with their shape. filled in black + * the clipPath object gets used when the object has rendered, and the context is placed in the center + * of the object cacheCanvas. + * If you want 0,0 of a clipPath to align with an object center, use clipPath.originX/Y to 'center' + */ + clipPath?: Object; + + /** + * Meaningful ONLY when the object is used as clipPath. + * if true, the clipPath will make the object clip to the outside of the clipPath + * since 2.4.0 + * @type boolean + * @default false + */ + inverted?: boolean; + + /** + * Meaningful ONLY when the object is used as clipPath. + * if true, the clipPath will have its top and left relative to canvas, and will + * not be influenced by the object transform. This will make the clipPath relative + * to the canvas, but clipping just a particular object. + * WARNING this is beta, this feature may change or be renamed. + * since 2.4.0 + * @type boolean + * @default false + */ + absolutePositioned?: boolean; + /** * Not used by fabric, just for convenience */ @@ -2297,86 +2803,56 @@ interface IObjectOptions { * Not used by fabric, just for convenience */ data?: any; - - /** - * 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; + * @memberOf fabric.Object.prototype + */ + oCoords?: {tl: Point, mt: Point, tr: Point, ml: Point, mr: Point, bl: Point, mb: Point, br: Point, mtr: Point}; + /** + * Describe object's corner position in canvas object absolute coordinates + * properties are tl,tr,bl,br and describe the four main corner. + * each property is an object with x, y, instance of Fabric.Point. + * The coordinates depends from this properties: width, height, scaleX, scaleY + * skewX, skewY, angle, strokeWidth, top, left. + * Those coordinates are usefull to understand where an object is. They get updated + * with oCoords but they do not need to be updated when zoom or panning change. + * The coordinates get updated with @method setCoords. + * You can calculate them without updating with @method calcCoords(true); + * @memberOf fabric.Object.prototype + */ + aCoords?: {bl: Point, br: Point, tl: Point, tr: Point}; + /** + * storage for object full transform matrix + */ + matrixCache?: any; + /** + * storage for object transform matrix + */ + ownMatrixCache?: any; } export interface Object extends IObservable, IObjectOptions, IObjectAnimation { } export class Object { - getCurrentWidth(): number; - getCurrentHeight(): number; + constructor(options?: IObjectOptions); + initialize(options?: IObjectOptions): Object; - getAngle(): number; - setAngle(value: number): Object; - - getBorderColor(): string; - setBorderColor(value: string): Object; - - getBorderScaleFactor(): number; - - getCornersize(): number; - setCornersize(value: number): Object; - - getFill(): string; - setFill(value: string): Object; - - getFillRule(): string; - setFillRule(value: string): Object; - - getFlipX(): boolean; - setFlipX(value: boolean): Object; - - getFlipY(): boolean; - setFlipY(value: boolean): Object; - - getHeight(): number; - setHeight(value: number): Object; - - getLeft(): number; - setLeft(value: number): Object; - - getOpacity(): number; - setOpacity(value: number): Object; - - overlayFill: string; - getOverlayFill(): string; - setOverlayFill(value: string): Object; - - getScaleX(): number; - setScaleX(value: number): Object; - - getScaleY(): number; - setScaleY(value: number): Object; - - getSkewX(): number; - setSkewX(value: number): Object; - - getSkewY(): number; - setSkewY(value: number): Object; - - setShadow(options: any): Object; - getShadow(): Object; - - stateProperties: any[]; - getTop(): number; - setTop(value: number): Object; - - getWidth(): number; - setWidth(value: number): Object; - - /* * Sets object's properties from options - * @param {Object} [options] Options object - */ + /* Sets object's properties from options + * @param {Object} [options] Options object + */ setOptions(options: IObjectOptions): void; /** * Transforms context when rendering an object - * @param ctx Context - * @param fromLeft When true, context is transformed to object's top/left corner. This is used when rendering text on Node + * @param {CanvasRenderingContext2D} ctx Context */ - transform(ctx: CanvasRenderingContext2D, fromLeft: boolean): void; + transform(ctx: CanvasRenderingContext2D): void; /** * Returns an object representation of an instance @@ -2396,63 +2872,121 @@ export class Object { toString(): string; /** - * Basic getter - * @param property Property name + * Return the object scale factor counting also the group scaling + * @return {Object} object with scaleX and scaleY properties */ - get(property: K): this[K]; + getObjectScaling(): {scaleX: number, scaleY: number}; /** - * Sets property to a given value. - * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. - * If you need to update those, call `setCoords()`. - * @param key Property name - * @param value Property value (if function, the value is passed into it and its return value is used as a new one) + * Return the object scale factor counting also the group scaling, zoom and retina + * @return {Object} object with scaleX and scaleY properties */ - set(key: K, value: this[K] | ((value: this[K]) => this[K])): this; - /** - * Sets property to a given value. - * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. - * If you need to update those, call `setCoords()`. - * @param options Property object, iterate over the object properties - */ - set(options: Partial): this; + getTotalObjectScaling(): {scaleX: number, scaleY: number}; /** - * Toggles specified property from `true` to `false` or from `false` to `true` - * @param property Property to toggle + * Return the object opacity counting also the group property + * @return {Number} */ - toggle(property: keyof this): this; + getObjectOpacity(): number; /** - * Sets sourcePath of an object - * @param value Value to set sourcePath to + * This callback function is called by the parent group of an object every + * time a non-delegated property changes on the group. It is passed the key + * and value as parameters. Not adding in this function's signature to avoid + * Travis build error about unused variables. */ - setSourcePath(value: string): this; + setOnGroup(): void; /** * Retrieves viewportTransform from Object's canvas if possible */ - getViewportTransform(): boolean; + getViewportTransform(): any[]; /** * Renders an object on a specified context - * @param ctx Context to render on - * @param [noTransform] When true, context is not transformed + * @param {CanvasRenderingContext2D} ctx Context to render on */ - render(ctx: CanvasRenderingContext2D, noTransform?: boolean): void; + render(ctx: CanvasRenderingContext2D): void; + + /** + * When set to `true`, force the object to have its own cache, even if it is inside a group + * it may be needed when your object behave in a particular way on the cache and always needs + * its own isolated canvas to render correctly. + * Created to be overridden + * since 1.7.12 + * @returns false + */ + needsItsOwnCache(): boolean; + + /** + * Decide if the object should cache or not. Create its own cache level + * objectCaching is a global flag, wins over everything + * needsItsOwnCache should be used when the object drawing method requires + * a cache step. None of the fabric classes requires it. + * Generally you do not cache objects in groups because the group outside is cached. + * @return {Boolean} + */ + shouldCache(): boolean; + + /** + * Check if this object or a child object will cast a shadow + * used by Group.shouldCache to know if child has a shadow recursively + * @return {Boolean} + */ + willDrawShadow(): boolean; + + /** + * Execute the drawing operation for an object clipPath + * @param {CanvasRenderingContext2D} ctx Context to render on + */ + drawClipPathOnCache(ctx: CanvasRenderingContext2D): void; + + /** + * Execute the drawing operation for an object on a specified context + * @param {CanvasRenderingContext2D} ctx Context to render on + */ + drawObject(ctx: CanvasRenderingContext2D): void; + + /** + * Paint the cached copy of the object on the target context. + * @param {CanvasRenderingContext2D} ctx Context to render on + */ + drawCacheOnCanvas(ctx: CanvasRenderingContext2D): void; + + /** + * Check if cache is dirty + * @param {Boolean} skipCanvas skip canvas checks because this object is painted + * on parent canvas. + */ + isCacheDirty(skipCanvas?: boolean): boolean; /** * Clones an instance, using a callback method will work for every object. * @param callback Callback is invoked with a clone as a first argument * @param [propertiesToInclude] Any properties that you might want to additionally include in the output */ - clone(callback: (clone: Object) => void, propertiesToInclude?: string[]): void; + clone(callback: Function, propertiesToInclude?: string[]): void; /** * Creates an instance of fabric.Image out of an object * @param callback callback, invoked with an instance as a first argument */ - cloneAsImage(callback: (image: Image) => void): this; + cloneAsImage(callback: Function, options?: IDataURLOptions): Object; + + /** + * Converts an object into a HTMLCanvas element + * @param {Object} options Options object + * @param {Number} [options.multiplier=1] Multiplier to scale by + * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14 + * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14 + * @param {Number} [options.width] Cropping width. Introduced in v1.2.14 + * @param {Number} [options.height] Cropping height. Introduced in v1.2.14 + * @param {Boolean} [options.enableRetinaScaling] Enable retina scaling for clone image. Introduce in 1.6.4 + * @param {Boolean} [options.withoutTransform] Remove current object transform ( no scale , no angle, no flip, no skew ). Introduced in 2.3.4 + * @param {Boolean} [options.withoutShadow] Remove current object shadow. Introduced in 2.4.2 + * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format + */ + toCanvasElement(options?: IDataURLOptions): string; /** * Converts an object into a data-url-like string @@ -2483,59 +3017,73 @@ export class Object { * @param property Property name 'stroke' or 'fill' * @param [options] Options object */ - setGradient(property: "stroke" | "fill", options: IGradientOptions): this; + setGradient(property: "stroke" | "fill", options?: IGradientOptions): Object; + /** * Sets pattern fill of an object * @param options Options object */ - setPatternFill(options: IFillOptions): this; + setPatternFill(options: IFillOptions, callback: Function): Object; /** * Sets shadow of an object * @param [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)") */ - setShadow(options?: string | Shadow): this; + setShadow(options?: string | Shadow): Object; /** * Sets "color" of an instance (alias of `set('fill', …)`) * @param color Color value */ - setColor(color: string): this; + setColor(color: string): Object; /** * Sets "angle" of an instance * @param angle Angle value */ - setAngle(angle: number): this; - - /** - * Sets "angle" of an instance - * @param angle Angle value - */ - rotate(angle: number): this; + rotate(angle: number): Object; /** * Centers object horizontally on canvas to which it was added last. * You might need to call `setCoords` on an object after centering, to update controls area. */ - centerH(): this; + centerH(): Object; + + /** + * Centers object horizontally on current viewport of canvas to which it was added last. + * You might need to call `setCoords` on an object after centering, to update controls area. + * @return {fabric.Object} thisArg + * @chainable + */ + viewportCenterH(): Object; /** * Centers object vertically on canvas to which it was added last. * You might need to call `setCoords` on an object after centering, to update controls area. */ - centerV(): this; + centerV(): Object; + + /** + * Centers object vertically on current viewport of canvas to which it was added last. + * You might need to call `setCoords` on an object after centering, to update controls area. + * @return {fabric.Object} thisArg + * @chainable + */ + viewportCenterV(): Object; /** * Centers object vertically and horizontally on canvas to which is was added last * You might need to call `setCoords` on an object after centering, to update controls area. */ - center(): this; + center(): Object; /** - * Removes object from canvas to which it was added last + * Centers object on current viewport of canvas to which it was added last. + * You might need to call `setCoords` on an object after centering, to update controls area. + * @return {fabric.Object} thisArg + * @chainable */ - remove(): Object; + viewportCenter(): Object; /** * Returns coordinates of a pointer relative to an object @@ -2544,11 +3092,52 @@ export class Object { */ getLocalPointer(e: Event, pointer?: { x: number, y: number }): { x: number, y: number }; + /** + * Basic getter + * @param property Property name + */ + get(property: K): this[K]; + + /** + * Sets property to a given value. + * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. + * If you need to update those, call `setCoords()`. + * @param key Property name + * @param value Property value (if function, the value is passed into it and its return value is used as a new one) + */ + set(key: K, value: this[K] | ((value: this[K]) => this[K])): Object; + + /** + * Sets property to a given value. + * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. + * If you need to update those, call `setCoords()`. + * @param options Property object, iterate over the object properties + */ + set(options: Partial): Object; + + /** + * Toggles specified property from `true` to `false` or from `false` to `true` + * @param property Property to toggle + */ + toggle(property: keyof this): Object; + + /** + * Sets sourcePath of an object + * @param value Value to set sourcePath to + */ + setSourcePath(value: string): Object; + + /** + * Sets "angle" of an instance + * @param angle Angle value + */ + setAngle(angle: number): Object; + /** * Sets object's properties from options * @param [options] Options object */ - setOptions(options: any): void; + setOptions(options?: any): void; /** * Sets sourcePath of an object * @param value Value to set sourcePath to @@ -2558,12 +3147,16 @@ export class Object { // ----------------------------------------------------------------------------------------------------------------------------------- /** * Returns styles-string for svg-export + * @param {Boolean} skipShadow a boolean to skip shadow filter output + * @return {String} */ - getSvgStyles(): string; + getSvgStyles(skipShadow?: boolean): string; /** * Returns transform-string for svg-export + * @param {Boolean} use the full transform or the single object one. + * @return {String} */ - getSvgTransform(): string; + getSvgTransform(full?: boolean, additionalTransform?: string): string; /** * Returns transform-string for svg-export from the transform matrix of single elements */ @@ -2573,28 +3166,32 @@ export class Object { // ----------------------------------------------------------------------------------------------------------------------------------- /** * Returns true if object state (one of its state properties) was changed + * @param {String} [propertySet] optional name for the set of property we want to save + * @return {Boolean} true if instance' state has changed since `{@link fabric.Object#saveState}` was called */ - hasStateChanged(): boolean; + hasStateChanged(propertySet: string): boolean; /** * Saves state of an object * @param [options] Object with additional `stateProperties` array to include when saving state * @return thisArg */ - saveState(options?: { stateProperties: any[] }): this; + saveState(options?: { stateProperties: any[] }): Object; /** * Setups state of an object + * @param {Object} [options] Object with additional `stateProperties` array to include when saving state + * @return {fabric.Object} thisArg */ - setupState(): this; + setupState(options?: any): Object; // functions from object straightening mixin // ----------------------------------------------------------------------------------------------------------------------------------- /** * Straightens an object (rotating it from current angle to one of 0, 90, 180, 270, etc. depending on which is closer) */ - straighten(): this; + straighten(): Object; /** * Same as straighten but with animation */ - fxStraighten(callbacks: Callbacks): this; + fxStraighten(callbacks: Callbacks): Object; // functions from object stacking mixin // ----------------------------------------------------------------------------------------------------------------------------------- @@ -2602,25 +3199,25 @@ export class Object { * Moves an object up in stack of drawn objects * @param [intersecting] If `true`, send object in front of next upper intersecting object */ - bringForward(intersecting?: boolean): this; + bringForward(intersecting?: boolean): Object; /** * Moves an object to the top of the stack of drawn objects */ - bringToFront(): this; + bringToFront(): Object; /** * Moves an object down in stack of drawn objects * @param [intersecting] If `true`, send object behind next lower intersecting object */ - sendBackwards(intersecting?: boolean): this; + sendBackwards(intersecting?: boolean): Object; /** * Moves an object to the bottom of the stack of drawn objects */ - sendToBack(): this; + sendToBack(): Object; /** * Moves an object to specified level in stack of drawn objects * @param index New position of object */ - moveTo(index: number): this; + moveTo(index: number): Object; // functions from object origin mixin // ----------------------------------------------------------------------------------------------------------------------------------- @@ -2646,10 +3243,11 @@ export class Object { /** * Returns the coordinates of the object as if it has a different origin - * @param originX Horizontal origin: 'left', 'center' or 'right' - * @param originY Vertical origin: 'top', 'center' or 'bottom' + * @param {String} originX Horizontal origin: 'left', 'center' or 'right' + * @param {String} originY Vertical origin: 'top', 'center' or 'bottom' + * @return {fabric.Point} */ - getPointByOrigin(): Point; + getPointByOrigin(originX: string, originY: string) : Point; /** * Returns the point in local coordinates @@ -2678,9 +3276,46 @@ export class Object { * Draws borders of an object's bounding box. * Requires public properties: width, height * Requires public options: padding, borderColor - * @param ctx Context to draw on + * @param {CanvasRenderingContext2D} ctx Context to draw on + * @param {Object} styleOverride object to override the object style + * @return {fabric.Object} thisArg + * @chainable */ - drawBorders(context: CanvasRenderingContext2D): this; + drawBorders(ctx: CanvasRenderingContext2D, styleOverride?: any): Object; + + /** + * Draws borders of an object's bounding box when it is inside a group. + * Requires public properties: width, height + * Requires public options: padding, borderColor + * @param {CanvasRenderingContext2D} ctx Context to draw on + * @param {object} options object representing current object parameters + * @param {Object} styleOverride object to override the object style + * @return {fabric.Object} thisArg + * @chainable + */ + drawBordersInGroup(ctx: CanvasRenderingContext2D, options?: any, styleOverride?: any): Object; + + /** + * Draws corners of an object's bounding box. + * Requires public properties: width, height + * Requires public options: cornerSize, padding + * @param {CanvasRenderingContext2D} ctx Context to draw on + * @param {Object} styleOverride object to override the object style + * @return {fabric.Object} thisArg + * @chainable + */ + drawControls(ctx: CanvasRenderingContext2D, styleOverride?: any): Object; + + /** + * Draws a colored layer behind the object, inside its selection borders. + * Requires public options: padding, selectionBackgroundColor + * this function is called when the context is transformed + * has checks to be skipped when the object is on a staticCanvas + * @param {CanvasRenderingContext2D} ctx Context to draw on + * @return {fabric.Object} thisArg + * @chainable + */ + drawSelectionBackground(ctx: CanvasRenderingContext2D): Object; /** * Draws corners of an object's bounding box. @@ -2700,7 +3335,7 @@ export class Object { * @param controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'. * @param visible true to set the specified control visible, false otherwise */ - setControlVisible(controlName: string, visible: boolean): this; + setControlVisible(controlName: string, visible: boolean): Object; /** * Sets the visibility state of object controls. @@ -2721,77 +3356,186 @@ export class Object { // functions from geometry mixin // ------------------------------------------------------------------------------------------------------------------------------- /** - * Sets corner position coordinates based on current angle, width and height - * See https://github.com/kangax/fabric.js/wiki/When-to-call-setCoords + * Sets corner position coordinates based on current angle, width and height. + * See {@link https://github.com/kangax/fabric.js/wiki/When-to-call-setCoords|When-to-call-setCoords} + * @param {Boolean} [ignoreZoom] set oCoords with or without the viewport transform. + * @param {Boolean} [skipAbsolute] skip calculation of aCoords, usefull in setViewportTransform + * @return {fabric.Object} thisArg + * @chainable */ - setCoords(): this; + setCoords(ignoreZoom?: boolean, skipAbsolute?: boolean): Object; /** * Returns coordinates of object's bounding rectangle (left, top, width, height) - * @param absoluteopt use coordinates without viewportTransform - * @param calculateopt use coordinates of current position instead of .oCoords / .aCoords - * @return Object with left, top, width, height properties + * the box is intented as aligned to axis of canvas. + * @param {Boolean} [absolute] use coordinates without viewportTransform + * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords / .aCoords + * @return {Object} Object with left, top, width, height properties */ - getBoundingRect(absoluteopt?: boolean, calculateopt?: boolean): { left: number; top: number; width: number; height: number }; + getBoundingRect(absolute?: boolean, calculate?: boolean): { left: number; top: number; width: number; height: number }; /** * Checks if object is fully contained within area of another object - * @param other Object to test + * @param {Object} other Object to test + * @param {Boolean} [absolute] use coordinates without viewportTransform + * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords + * @return {Boolean} true if object is fully contained within area of another object */ - isContainedWithinObject(other: Object): boolean; + isContainedWithinObject(other: Object, absolute?: boolean, calculate?: boolean): boolean; /** * Checks if object is fully contained within area formed by 2 points * @param pointTL top-left point of area * @param pointBR bottom-right point of area */ - isContainedWithinRect(pointTL: any, pointBR: any): boolean; + isContainedWithinRect(pointTL: any, pointBR: any, absolute?: boolean, calculate?: boolean): boolean; /** * Checks if point is inside the object - * @param point Point to check against + * @param {fabric.Point} point Point to check against + * @param {Object} [lines] object returned from @method _getImageLines + * @param {Boolean} [absolute] use coordinates without viewportTransform + * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords + * @return {Boolean} true if point is inside the object */ - containsPoint(point: Point): boolean; + containsPoint(point: Point, lines?: any, absolute?: boolean, calculate?: boolean): boolean; /** * Scales an object (equally by x and y) * @param value Scale factor * @return thisArg */ - scale(value: number): this; + scale(value: number): Object; /** * Scales an object to a given height, with respect to bounding box (scaling by x/y equally) * @param value New height value */ - scaleToHeight(value: number): this; + scaleToHeight(value: number, absolute?: boolean): Object; /** * Scales an object to a given width, with respect to bounding box (scaling by x/y equally) * @param value New width value */ - scaleToWidth(value: number): this; + scaleToWidth(value: number, absolute?: boolean): Object; /** * Checks if object intersects with another object - * @param other Object to test + * @param {Object} other Object to test + * @param {Boolean} [absolute] use coordinates without viewportTransform + * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords + * @return {Boolean} true if object intersects with another object */ - intersectsWithObject(other: Object): boolean; + intersectsWithObject(other: Object, absolute?: boolean, calculate?: boolean): boolean; /** * Checks if object intersects with an area formed by 2 points - * @param pointTL top-left point of area - * @param pointBR bottom-right point of area + * @param {Object} pointTL top-left point of area + * @param {Object} pointBR bottom-right point of area + * @param {Boolean} [absolute] use coordinates without viewportTransform + * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords + * @return {Boolean} true if object intersects with an area formed by 2 points */ - intersectsWithRect(pointTL: any, pointBR: any): boolean; + intersectsWithRect(pointTL: any, pointBR: any, absolute?: boolean, calculate?: boolean): boolean; + /** + * Animates object's properties + */ + animate(): Object; + /** + * Calculate and returns the .coords of an object. + * @return {Object} Object with tl, tr, br, bl .... + * @chainable + */ + calcCoords(absolute?: boolean): any; + /** + * calculate trasform Matrix that represent current transformation from + * object properties. + * @param {Boolean} [skipGroup] return transformMatrix for object and not go upward with parents + * @return {Array} matrix Transform Matrix for the object + */ + calcTransformMatrix(skipGroup?: boolean): any[]; + /** + * return correct set of coordinates for intersection + */ + getCoords(absolute?: boolean, calculate?: boolean): any; + /** + * Returns height of an object bounding box counting transformations + * before 2.0 it was named getHeight(); + * @return {Number} height value + */ + getScaledHeight(): number; + /** + * Returns width of an object bounding box counting transformations + * before 2.0 it was named getWidth(); + * @return {Number} width value + */ + getScaledWidth(): number; + /** + * Returns id attribute for svg output + * @return {String} + */ + getSvgCommons(): string; + /** + * Returns filter for svg shadow + * @return {String} + */ + getSvgFilter(): string; + /** + * Returns styles-string for svg-export + * @param {Object} style the object from which to retrieve style properties + * @param {Boolean} useWhiteSpace a boolean to include an additional attribute in the style. + * @return {String} + */ + getSvgSpanStyles(style: any, useWhiteSpace?: boolean): string; + /** + * Returns text-decoration property for svg-export + * @param {Object} style the object from which to retrieve style properties + * @return {String} + */ + getSvgTextDecoration(style: any): string; + /** + * Checks if object is contained within the canvas with current viewportTransform + * the check is done stopping at first point that appears on screen + * @param {Boolean} [calculate] use coordinates of current position instead of .aCoords + * @return {Boolean} true if object is fully or partially contained within canvas + */ + isOnScreen(calculate?: boolean): boolean; + /** + * Checks if object is partially contained within the canvas with current viewportTransform + * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords + * @return {Boolean} true if object is partially contained within canvas + */ + isPartiallyOnScreen(calculate?: boolean): boolean; + /** + * This callback function is called every time _discardActiveObject or _setActiveObject + * try to to deselect this object. If the function returns true, the process is cancelled + */ + onDeselect(): void; + /** + * This callback function is called every time _discardActiveObject or _setActiveObject + * try to to select this object. If the function returns true, the process is cancelled + */ + onSelect(): void; + /** + * Returns svg clipPath representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toClipPathSVG(reviver?: Function): string; + /** + * Returns svg representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toSVG(reviver?: Function): string; + /** + * Translates the coordinates from a set of origin to another (based on the object's dimensions) + * @param {fabric.Point} point The point which corresponds to the originX and originY params + * @param {String} fromOriginX Horizontal origin: 'left', 'center' or 'right' + * @param {String} fromOriginY Vertical origin: 'top', 'center' or 'bottom' + * @param {String} toOriginX Horizontal origin: 'left', 'center' or 'right' + * @param {String} toOriginY Vertical origin: 'top', 'center' or 'bottom' + * @return {fabric.Point} + */ + translateToGivenOrigin(pointL: Point, fromOriginX: string, fromOriginY: string, toOriginX: string, toOriginY: string): Point; } interface IPathOptions extends IObjectOptions { /** * Array of path points */ - path?: any[]; - - /** - * Minimum X from points values, necessary to offset points - */ - minX?: number; - - /** - * Minimum Y from points values, necessary to offset points - */ - minY?: number; + path?: Point[]; } export interface Path extends Object, IPathOptions { } export class Path { @@ -2800,178 +3544,53 @@ export class Path { * @param path Path data (sequence of coordinates and corresponding "command" tokens) * @param [options] Options object */ - constructor(path?: string | any[], options?: IPathOptions); + constructor(path?: string | Point[], options?: IPathOptions); pathOffset: Point; - initialize(path?: any[], options?: IPathOptions): Path; - /** - * Returns number representation of an instance complexity - * @return complexity of this instance + * Returns svg clipPath representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance */ - complexity(): number; - - /** - * Renders path on a specified context - * @param ctx context to render path on - * @param [noTransform] When true, context is not transformed - */ - render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; - /** - * Returns dataless object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toDatalessObject(propertiesToInclude?: string[]): any; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns string representation of an instance - * @return string representation of an instance - */ - toString(): string; + toClipPathSVG(reviver?: Function): string; /** * Returns svg representation of an instance * @param [reviver] Method for further parsing of svg representation. * @return svg representation of an instance */ toSVG(reviver?: Function): string; - /** * Creates an instance of fabric.Path from an SVG element * @param element to parse * @param callback Callback to invoke when an fabric.Path instance is created * @param [options] Options object */ - static fromElement(element: SVGElement, callback: (path: Path) => any, options?: IPathOptions): void; + static fromElement(element: SVGElement, callback: Function, options?: IPathOptions): Path; /** * Creates an instance of fabric.Path from an object * @param callback Callback to invoke when an fabric.Path instance is created */ - static fromObject(object: any, callback: (path: Path) => any): void; + static fromObject(object: any, callback: Function): Path; + /** + * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) + */ + static ATTRIBUTE_NAMES: string[]; } - -export class PathGroup extends Object { - /** - * Constructor - * @param [options] Options object - */ - constructor(paths: Path[], options?: IObjectOptions); - - initialize(paths: Path[], options?: IObjectOptions): void; - /** - * Returns number representation of object's complexity - * @return complexity - */ - complexity(): number; - /** - * Returns true if all paths in this group are of same color - * @return true if all paths are of the same color (`fill`) - */ - isSameColor(): boolean; - /** - * Renders this group on a specified context - * @param ctx Context to render this instance on - */ - render(ctx: CanvasRenderingContext2D): void; - /** - * Returns dataless object representation of this path group - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return dataless object representation of an instance - */ - toDatalessObject(propertiesToInclude?: string[]): any; - /** - * Returns object representation of this path group - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns a string representation of this path group - * @return string representation of an object - */ - toString(): string; - /** - * Returns svg representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - /** - * Returns all paths in this path group - * @return array of path objects included in this path group - */ - getObjects(): Path[]; - - static fromObject(object: any): PathGroup; - /** - * Creates fabric.PathGroup instance from an object representation - * @param object Object to create an instance from - * @param callback Callback to invoke when an fabric.PathGroup instance is created - */ - static fromObject(object: any, callback: (group: PathGroup) => any): void; -} - -interface IPolygonOptions extends IObjectOptions { - /** - * Points array - */ - points?: Point[]; - - /** - * Minimum X from points values, necessary to offset points - */ - minX?: number; - - /** - * Minimum Y from points values, necessary to offset points - */ - minY?: number; -} -export interface Polygon extends IPolygonOptions { } -export class Polygon extends Object { +export interface Polygon extends IPolylineOptions { } +export class Polygon extends Polyline { /** * Constructor * @param points Array of points * @param [options] Options object */ - constructor(points: Array<{ x: number; y: number }>, options?: IObjectOptions, skipOffset?: boolean); - - /** - * Returns complexity of an instance - * @return complexity of this instance - */ - complexity(): number; - - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns svg representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - - /** - * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) - */ - static ATTRIBUTE_NAMES: string[]; - + constructor(points: Array<{ x: number; y: number }>, options?: IPolylineOptions); /** * Returns Polygon instance from an SVG element * @param element Element to parse * @param [options] Options object */ - static fromElement(element: SVGElement, options?: IPolygonOptions): Polygon; + static fromElement(element: SVGElement, options?: IPolylineOptions): Polygon; /** * Returns fabric.Polygon instance from an object representation * @param object Object to create an instance from @@ -2984,16 +3603,6 @@ interface IPolylineOptions extends IObjectOptions { * Points array */ points?: Point[]; - - /** - * Minimum X from points values, necessary to offset points - */ - minX?: number; - - /** - * Minimum Y from points values, necessary to offset points - */ - minY?: number; } export interface Polyline extends IPolylineOptions { } export class Polyline extends Object { @@ -3004,30 +3613,10 @@ export class Polyline extends Object { * @param [skipOffset] Whether points offsetting should be skipped */ constructor(points: Array<{ x: number; y: number }>, options?: IPolylineOptions); - initialize(points: Point[], options?: IPolylineOptions): void; - /** - * Returns complexity of an instance - * @return complexity of this instance - */ - complexity(): number; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return Object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns SVG representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - /** * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) */ static ATTRIBUTE_NAMES: string[]; - /** * Returns Polyline instance from an SVG element * @param element Element to parse @@ -3042,8 +3631,6 @@ export class Polyline extends Object { } interface IRectOptions extends IObjectOptions { - x?: number; - y?: number; /** * Horizontal border radius */ @@ -3062,25 +3649,6 @@ export class Rect extends Object { * @param [options] Options object */ constructor(options?: IRectOptions); - initialize(points?: number[], options?: any): Rect; - /** - * Returns complexity of an instance - * @return complexity - */ - complexity(): number; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude: any[]): any; - /** - * Returns svg representation of an instance - * @param [reviver] Method for further parsing of svg representation. - * @return svg representation of an instance - */ - toSVG(reviver?: Function): string; - /** * List of attribute names to account for when parsing SVG element (used by `fabric.Rect.fromElement`) */ @@ -3098,606 +3666,779 @@ export class Rect extends Object { static fromObject(object: any): Rect; } -interface ITextOptions extends IObjectOptions { +interface TextOptions extends IObjectOptions { + type?: string; /** * Font size (in pixels) + * @type Number */ fontSize?: number; /** * Font weight (e.g. bold, normal, 400, 600, 800) + * @type {(Number|String)} */ - fontWeight?: number | string; + fontWeight?: string | number; /** * Font family + * @type String */ fontFamily?: string; /** - * Text decoration Possible values?: "", "underline", "overline" or "line-through". - * Feels like this has been deprecated in favor of underline, overline, linethrough props + * Text decoration underline. + * @type Boolean */ - textDecoration?: string; - /** - * Text decoration underline. - * @type Boolean - * @default - */ - underline?: boolean; - /** - * Text decoration overline. - * @type Boolean - * @default - */ - overline?: boolean; - /** - * Text decoration linethrough. - * @type Boolean - * @default - */ - linethrough?: boolean; + underline?: boolean; /** - * Text alignment. Possible values?: "left", "center", or "right". + * Text decoration overline. + * @type Boolean + */ + overline?: boolean; + /** + * Text decoration linethrough. + * @type Boolean + */ + linethrough?: boolean; + /** + * Text alignment. Possible values: "left", "center", "right", "justify", + * "justify-left", "justify-center" or "justify-right". + * @type String */ textAlign?: string; /** - * Font style . Possible values?: "", "normal", "italic" or "oblique". + * Font style . Possible values: "", "normal", "italic" or "oblique". + * @type String */ - fontStyle?: string; + fontStyle?: '' | 'normal' | 'italic' | 'oblique'; /** * Line height + * @type Number */ lineHeight?: number; - /** - * Character spacing - */ - charSpacing?: number; + /** + * Superscript schema object (minimum overlap) + * @type {Object} + */ + superscript?: {size: number, baseline: number}; + /** + * Subscript schema object (minimum overlap) + * @type {Object} + */ + subscript?: {size: number, baseline: number}; + /** + * Background color of text lines + * @type String + */ + textBackgroundColor?: string; /** * When defined, an object is rendered via stroke and this property specifies its color. - * Backwards incompatibility note?: This property was named "strokeStyle" until v1.1.6 + * Backwards incompatibility note: This property was named "strokeStyle" until v1.1.6 */ stroke?: string; /** * Shadow object representing shadow of this shape. - * Backwards incompatibility note?: This property was named "textShadow" (String) until v1.2.11 + * Backwards incompatibility note: This property was named "textShadow" (String) until v1.2.11 + * @type fabric.Shadow */ shadow?: Shadow | string; /** - * Background color of text lines + * additional space between characters + * expressed in thousands of em unit + * @type Number */ - textBackgroundColor?: string; - + charSpacing?: number; + /** + * Object containing character styles - top-level properties -> line numbers, + * 2nd-level properties - charater numbers + * @type Object + */ + styles?: any; + /** + * Baseline shift, stlyes only, keep at 0 for the main text object + * @type {Number} + */ + deltaY?: number; + text?: string; + /** + * List of properties to consider when checking if cache needs refresh + * @type Array + */ + cacheProperties?: string[]; + /** + * List of properties to consider when checking if + * state of an object is changed ({@link fabric.Object#hasStateChanged}) + * as well as for history (undo/redo) purposes + * @type Array + */ + stateProperties?: string[]; +} +export interface Text extends TextOptions { } +export class Text extends Object { + /** + * Constructor + * @param text Text string + * @param [options] Options object + */ + constructor(text: string, options?: TextOptions); + /** + * Return a context for measurement of text string. + * if created it gets stored for reuse + * @return {fabric.Text} thisArg + */ + getMeasuringContext(): CanvasRenderingContext2D; + /** + * Initialize or update text dimensions. + * Updates this.width and this.height with the proper values. + * Does not return dimensions. + */ + initDimensions(): void; + /** + * Enlarge space boxes and shift the others + */ + enlargeSpaces(): void; + /** + * Detect if the text line is ended with an hard break + * text and itext do not have wrapping, return false + * @return {Boolean} + */ + isEndOfWrapping(lineIndex: number): boolean; + /** + * Returns string representation of an instance + */ + toString(): string; + /** + * Computes height of character at given position + * @param {Number} line the line number + * @param {Number} char the character number + * @return {Number} fontSize of the character + */ + getHeightOfChar(line: number, char: number): number; + /** + * measure a text line measuring all characters. + * @param {Number} lineIndex line number + * @return {Object} object.width total width of characters + * @return {Object} object.numOfSpaces length of chars that match this._reSpacesAndTabs + */ + measureLine(lineIndex: number): { width: number, numOfSpaces: number }; + /** + * Calculate height of line at 'lineIndex' + * @param {Number} lineIndex index of line to calculate + * @return {Number} + */ + getHeightOfLine(lineIndex: number): number; + /** + * Calculate text box height + */ + calcTextHeight(): number; + /** + * Turns the character into a 'superior figure' (i.e. 'superscript') + * @param {Number} start selection start + * @param {Number} end selection end + * @returns {fabric.Text} thisArg + * @chainable + */ + setSuperscript(start: number, end: number): Text; + /** + * Turns the character into an 'inferior figure' (i.e. 'subscript') + * @param {Number} start selection start + * @param {Number} end selection end + * @returns {fabric.Text} thisArg + * @chainable + */ + setSubscript(start: number, end: number): Text; + /** + * Retrieves the value of property at given character position + * @param {Number} lineIndex the line number + * @param {Number} charIndex the charater number + * @param {String} property the property name + * @returns the value of 'property' + */ + getValueOfPropertyAt(lineIndex: number, charIndex: number, property: string): any; + static DEFAULT_SVG_FONT_SIZE: number; + /** + * Returns fabric.Text instance from an SVG element (not yet implemented) + * @static + * @memberOf fabric.Text + * @param {SVGElement} element Element to parse + * @param {Function} callback callback function invoked after parsing + * @param {Object} [options] Options object + */ + static fromElement(element: SVGElement, callback?: Function, options?: TextOptions): Text; + /** + * Returns fabric.Text instance from an object representation + * @static + * @memberOf fabric.Text + * @param {Object} object Object to create an instance from + * @param {Function} [callback] Callback to invoke when an fabric.Text instance is created + */ + static fromObject(object: any, callback?: Function): Text; + /** + * Check if characters in a text have a value for a property + * whose value matches the textbox's value for that property. If so, + * the character-level property is deleted. If the character + * has no other properties, then it is also deleted. Finally, + * if the line containing that character has no other characters + * then it also is deleted. + * + * @param {string} property The property to compare between characters and text. + */ + cleanStyle(property: string): void; + /** + * Returns 2d representation (lineIndex and charIndex) of cursor (or selection start) + * @param {Number} [selectionStart] Optional index. When not given, current selectionStart is used. + * @param {Boolean} [skipWrapping] consider the location for unwrapped lines. usefull to manage styles. + */ + get2DCursorLocation(selectionStart: number, skipWrapping: boolean): {lineIndex: number, charIndex: number}; + /** + * return a new object that contains all the style property for a character + * the object returned is newly created + * @param {Number} lineIndex of the line where the character is + * @param {Number} charIndex position of the character on the line + * @return {Object} style object + */ + getCompleteStyleDeclaration(lineIndex: number, charIndex: number): any; + /** + * Gets style of a current selection/cursor (at the start position) + * if startIndex or endIndex are not provided, slectionStart or selectionEnd will be used. + * @param {Number} [startIndex] Start index to get styles at + * @param {Number} [endIndex] End index to get styles at, if not specified selectionEnd or startIndex + 1 + * @param {Boolean} [complete] get full style or not + * @return {Array} styles an array with one, zero or more Style objects + */ + getSelectionStyles(startIndex?: number, endIndex?: number, complete?: boolean): any[]; + /** + * Returns styles-string for svg-export + * @param {Boolean} skipShadow a boolean to skip shadow filter output + * @return {String} + */ + getSvgStyles(skipShadow?: boolean): string; + /** + * Returns true if object has no styling or no styling in a line + * @param {Number} lineIndex , lineIndex is on wrapped lines. + * @return {Boolean} + */ + isEmptyStyles(lineIndex: number): boolean; + /** + * Remove a style property or properties from all individual character styles + * in a text object. Deletes the character style object if it contains no other style + * props. Deletes a line style object if it contains no other character styles. + * + * @param {String} props The property to remove from character styles. + */ + removeStyle(property: string): void; + /** + * Sets style of a current selection, if no selection exist, do not set anything. + * @param {Object} [styles] Styles object + * @param {Number} [startIndex] Start index to get styles at + * @param {Number} [endIndex] End index to get styles at, if not specified selectionEnd or startIndex + 1 + * @return {fabric.IText} thisArg + * @chainable + */ + setSelectionStyles(styles: any, startIndex?: number, endIndex?: number): Text; + /** + * Returns true if object has a style property or has it ina specified line + * @param {Number} lineIndex + * @return {Boolean} + */ + styleHas(property: string, lineIndex?: number): boolean; +} +interface ITextOptions extends TextOptions { + /** + * Index where text selection starts (or where cursor is when there is no selection) + * @type Number + */ + selectionStart?: number; + /** + * Index where text selection ends + * @type Number + */ + selectionEnd?: number; + /** + * Color of text selection + * @type String + */ + selectionColor?: string; + /** + * Indicates whether text is in editing mode + * @type Boolean + */ + isEditing?: boolean; + /** + * Indicates whether a text can be edited + * @type Boolean + */ + editable?: boolean; + /** + * Border color of text object while it's in editing mode + * @type String + */ + editingBorderColor?: string; + /** + * Width of cursor (in px) + * @type Number + */ + cursorWidth?: number; + /** + * Color of default cursor (when not overwritten by character style) + * @type String + */ + cursorColor?: string; + /** + * Delay between cursor blink (in ms) + * @type Number + */ + cursorDelay?: number; + /** + * Duration of cursor fadein (in ms) + * @type Number + */ + cursorDuration?: number; + /** + * Indicates whether internal text char widths can be cached + * @type Boolean + */ + caching?: boolean; + /** + * Helps determining when the text is in composition, so that the cursor + * rendering is altered. + */ + inCompositionMode?: boolean; path?: string; useNative?: boolean; - text?: string; + /** + * For functionalities on keyDown + ctrl || cmd + */ + ctrlKeysMapDown?: any; + /** + * For functionalities on keyUp + ctrl || cmd + */ + ctrlKeysMapUp?: any; + /** + * For functionalities on keyDown + * Map a special key to a function of the instance/prototype + * If you need different behaviour for ESC or TAB or arrows, you have to change + * this map setting the name of a function that you build on the fabric.Itext or + * your prototype. + * the map change will affect all Instances unless you need for only some text Instances + * in that case you have to clone this object and assign your Instance. + * this.keysMap = fabric.util.object.clone(this.keysMap); + * The function must be in fabric.Itext.prototype.myFunction And will receive event as args[0] + */ + keysMap?: any; } -export interface Text extends ITextOptions { } -export class Text extends Object { +export interface IText extends ITextOptions { } +export class IText extends Text { /** * Constructor * @param text Text string * @param [options] Options object */ constructor(text: string, options?: ITextOptions); - /** - * Returns complexity of an instance - */ - complexity(): number; - /** - * Returns string representation of an instance - */ - toString(): string; - /** - * Renders text instance on a specified context - * @param ctx Context to render on - */ - render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - */ - toObject(propertiesToInclude?: string[]): any; - /** - * Returns SVG representation of an instance - * @param [reviver] Method for further parsing of svg representation. - */ - toSVG(reviver?: Function): string; - /** - * Retrieves object's fontSize - */ - getFontSize(): number; - /** - * Sets object's fontSize - * @param fontSize Font size (in pixels) - */ - setFontSize(fontSize: number): Text; - /** - * Retrieves object's fontWeight - */ - getFontWeight(): number | string; - /** - * Sets object's fontWeight - * @param fontWeight Font weight - */ - setFontWeight(fontWeight: string | number): Text; - /** - * Retrieves object's fontFamily - */ - getFontFamily(): string; - /** - * Sets object's fontFamily - * @param fontFamily Font family - */ - setFontFamily(fontFamily: string): Text; - /** - * Retrieves object's text - */ - getText(): string; - /** - * Sets object's text - * @param text Text - */ - setText(text: string): Text; - /** - * Retrieves object's textDecoration - */ - getTextDecoration(): string; - /** - * Sets object's textDecoration - * @param textDecoration Text decoration - */ - setTextDecoration(textDecoration: string): Text; - /** - * Retrieves object's underline - */ - getUnderline(): boolean; - /** - * Sets object's underline - * @param underline Text underline - */ - setUnderline(underline: boolean): Text; - /** - * Retrieves object's overline - */ - getOverline(): boolean; - /** - * Sets object's overline - * @param overline Text overline - */ - setOverline(overline: boolean): Text; - /** - * Retrieves object's linethrough - */ - getLinethrough(): boolean; - /** - * Sets object's linethrough - * @param linethrough Text linethrough - */ - setLinethrough(linethrough: boolean): Text; - /** - * Retrieves object's fontStyle - */ - getFontStyle(): string; - /** - * Sets object's fontStyle - * @param fontStyle Font style - */ - setFontStyle(fontStyle: string): Text; - /** - * Retrieves object's lineHeight - */ - getLineHeight(): number; - /** - * Sets object's lineHeight - * @param lineHeight Line height - */ - setLineHeight(lineHeight: number): Text; - /** - * Retrieves object's charSpacing - */ - getCharSpacing(): number; - /** - * Sets object's charSpacing - * @param charSpacing Character spacing - */ - setCharSpacing(charSpacing: number): Text; - /** - * Retrieves object's textAlign - */ - getTextAlign(): string; - /** - * Sets object's textAlign - * @param textAlign Text alignment - */ - setTextAlign(textAlign: string): Text; - /** - * Retrieves object's textBackgroundColor - */ - getTextBackgroundColor(): string; - /** - * Sets object's textBackgroundColor - * @param textBackgroundColor Text background color - */ - setTextBackgroundColor(textBackgroundColor: string): Text; - - /** - * List of attribute names to account for when parsing SVG element (used by `fabric.Text.fromElement`) - */ - static ATTRIBUTE_NAMES: string[]; - /** - * Default SVG font size - */ - static DEFAULT_SVG_FONT_SIZE: number; - - /** - * Returns fabric.Text instance from an SVG element (not yet implemented) - * @param element Element to parse - * @param [options] Options object - */ - static fromElement(element: SVGElement, options?: ITextOptions): Text; - /** - * Returns fabric.Text instance from an object representation - * @param object Object to create an instance from - */ - static fromObject(object: any): Text; -} - -interface IITextOptions extends IObjectOptions, ITextOptions { - /** - * Index where text selection starts (or where cursor is when there is no selection) - */ - selectionStart?: number; - - /** - * Index where text selection ends - */ - selectionEnd?: number; - - /** - * Color of text selection - */ - selectionColor?: string; - - /** - * Indicates whether text is in editing mode - */ - isEditing?: boolean; - - /** - * Indicates whether a text can be edited - */ - editable?: boolean; - - /** - * Border color of text object while it's in editing mode - */ - editingBorderColor?: string; - - /** - * Width of cursor (in px) - */ - cursorWidth?: number; - - /** - * Color of default cursor (when not overwritten by character style) - */ - cursorColor?: string; - - /** - * Delay between cursor blink (in ms) - */ - cursorDelay?: number; - - /** - * Duration of cursor fadein (in ms) - */ - cursorDuration?: number; - - /** - * Object containing character styles - * (where top-level properties corresponds to line number and 2nd-level properties -- to char number in a line) - */ - styles?: any; - - /** - * Indicates whether internal text char widths can be cached - */ - caching?: boolean; -} -export interface Textbox extends IText {} -export class Textbox extends IText { - /** - * Constructor - * @param text Text string - * @param [options] Options object - */ - constructor(text: string, options?: IITextOptions); - /** - * Detect if the text line is ended with an hard break - * text and itext do not have wrapping, return false - * @param {Number} lineIndex text to split - * @return {Boolean} - */ - isEndOfWrapping(lineIndex: number): boolean; - /** - * Get minimum width of text box - * @return {Number} - */ - getMinWidth(): number; - /** - * Selects entire text - * @return {fabric.Text} thisArg - * @chainable - */ - selectAll(): Textbox; - /** - * Selects a line based on the index - * @param {Number} selectionStart Index of a character - * @return {fabric.IText} thisArg - * @chainable - */ - selectLine(selectionStart: number): Textbox; - /** - * Enters editing state - * @return {fabric.Textbox} thisArg - * @chainable - */ - enterEditing(): Textbox; - /** - * Exits from editing state - * @return {fabric.Textbox} thisArg - * @chainable - */ - exitEditing(): Textbox; -} -export interface IText extends Text, IITextOptions { } -export class IText extends Object { - /** - * Constructor - * @param text Text string - * @param [options] Options object - */ - constructor(text: string, options?: IITextOptions); - /** - * Returns true if object has no styling or no styling in a line - * @param {Number} lineIndex , lineIndex is on wrapped lines. - */ - isEmptyStyles(lineIndex: number): boolean; - render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; - /** - * Returns object representation of an instance - * @param [propertiesToInclude] Any properties that you might want to additionally include in the output - * @return object representation of an instance - */ - toObject(propertiesToInclude?: string[]): any; - - setText(value: string): Text; /** * Sets selection start (left boundary of a selection) - * @param index Index to set selection start to + * @param {Number} index Index to set selection start to */ setSelectionStart(index: number): void; /** * Sets selection end (right boundary of a selection) - * @param index Index to set selection end to + * @param {Number} index Index to set selection end to */ setSelectionEnd(index: number): void; /** - * Gets style of a current selection/cursor (at the start position) - * @param [startIndex] Start index to get styles at - * @param [endIndex] End index to get styles at - * @return styles Style object at a specified (or current) index + * Prepare and clean the contextTop */ - getSelectionStyles(startIndex: number, endIndex: number, complete?: boolean): any; - /** - * Sets style of a current selection - * @param [styles] Styles object - * @return thisArg - * @chainable - */ - setSelectionStyles(styles: any): Text; - + clearContextTop(skipRestore?: boolean): void; /** * Renders cursor or selection (depending on what exists) */ renderCursorOrSelection(): void; - - /** - * Returns 2d representation (lineIndex and charIndex) of cursor (or selection start) - * @param [selectionStart] Optional index. When not given, current selectionStart is used. - */ - get2DCursorLocation(selectionStart?: number): void; - /** - * Returns complete style of char at the current cursor - * @param lineIndex Line index - * @param charIndex Char index - * @return Character style - */ - getCurrentCharStyle(lineIndex: number, charIndex: number): any; - - /** - * Returns fontSize of char at the current cursor - * @param lineIndex Line index - * @param charIndex Char index - * @return Character font size - */ - getCurrentCharFontSize(lineIndex: number, charIndex: number): number; - - /** - * Returns color (fill) of char at the current cursor - * @param lineIndex Line index - * @param charIndex Char index - * @return Character color (fill) - */ - getCurrentCharColor(lineIndex: number, charIndex: number): string; /** * Renders cursor + * @param {Object} boundaries + * @param {CanvasRenderingContext2D} ctx transformed context to draw on */ - renderCursor(boundaries: any): void; - + renderCursor(boundaries: any, ctx: CanvasRenderingContext2D): void; /** * Renders text selection - * @param chars Array of characters - * @param boundaries Object with left/top/leftOffset/topOffset + * @param {Object} boundaries Object with left/top/leftOffset/topOffset + * @param {CanvasRenderingContext2D} ctx transformed context to draw on */ - renderSelection(chars: string[], boundaries: any): void; - - // functions from itext behavior mixin - // ------------------------------------------------------------------------------------------------------------------------ + renderSelection(boundaries: any, ctx: CanvasRenderingContext2D): void; + /** + * High level function to know the height of the cursor. + * the currentChar is the one that precedes the cursor + * Returns fontSize of char at the current cursor + * @return {Number} Character font size + */ + getCurrentCharFontSize(): number; + /** + * High level function to know the color of the cursor. + * the currentChar is the one that precedes the cursor + * Returns color (fill) of char at the current cursor + * @return {String} Character color (fill) + */ + getCurrentCharColor(): string; + /** + * Returns fabric.IText instance from an object representation + * @static + * @memberOf fabric.IText + * @param {Object} object Object to create an instance from + * @param {function} [callback] invoked with new instance as argument + */ + static fromObject(object: any, callback?: Function): IText; /** * Initializes all the interactive behavior of IText */ initBehavior(): void; - - /** - * Initializes "selected" event handler - */ - initSelectedHandler(): void; - + onDeselect(): void; /** * Initializes "added" event handler */ initAddedHandler(): void; - - initRemovedHandler(): void; - /** * Initializes delayed cursor */ - initDelayedCursor(restart: boolean): void; - + initDelayedCursor(): void; /** * Aborts cursor animation and clears all timeouts */ abortCursorAnimation(): void; - /** * Selects entire text + * @return {fabric.IText} thisArg + * @chainable */ - selectAll(): void; - + selectAll(): IText; /** * Returns selected text + * @return {String} */ getSelectedText(): string; - /** * Find new selection index representing start of current word according to current selection index - * @param startFrom Surrent selection index - * @return New selection index + * @param {Number} startFrom Surrent selection index + * @return {Number} New selection index */ findWordBoundaryLeft(startFrom: number): number; - /** * Find new selection index representing end of current word according to current selection index - * @param startFrom Current selection index - * @return New selection index + * @param {Number} startFrom Current selection index + * @return {Number} New selection index */ findWordBoundaryRight(startFrom: number): number; - /** * Find new selection index representing start of current line according to current selection index - * @param startFrom Current selection index + * @param {Number} startFrom Current selection index + * @return {Number} New selection index */ findLineBoundaryLeft(startFrom: number): number; - /** * Find new selection index representing end of current line according to current selection index - * @param startFrom Current selection index + * @param {Number} startFrom Current selection index + * @return {Number} New selection index */ findLineBoundaryRight(startFrom: number): number; - - /** - * Returns number of newlines in selected text - */ - getNumNewLinesInSelectedText(): number; - /** * Finds index corresponding to beginning or end of a word - * @param selectionStart Index of a character - * @param direction: 1 or -1 + * @param {Number} selectionStart Index of a character + * @param {Number} direction 1 or -1 + * @return {Number} Index of the beginning or end of a word */ searchWordBoundary(selectionStart: number, direction: number): number; - /** * Selects a word based on the index - * @param selectionStart Index of a character + * @param {Number} selectionStart Index of a character */ selectWord(selectionStart: number): void; /** * Selects a line based on the index - * @param selectionStart Index of a character + * @param {Number} selectionStart Index of a character + * @return {fabric.IText} thisArg + * @chainable */ - selectLine(selectionStart: number): void; - + selectLine(selectionStart: number): IText; /** * Enters editing state + * @return {fabric.IText} thisArg + * @chainable */ enterEditing(): IText; - /** * Initializes "mousemove" event handler */ initMouseMoveHandler(): void; /** * Exits from editing state - * @return thisArg + * @return {fabric.IText} thisArg * @chainable */ exitEditing(): IText; - /** - * Inserts a character where cursor is (replacing selection if one exists) - * @param _chars Characters to insert + * remove and reflow a style block from start to end. + * @param {Number} start linear start position for removal (included in removal) + * @param {Number} end linear end position for removal ( excluded from removal ) */ - insertChars(_chars: string, useCopiedStyle?: boolean): void; - /** - * Inserts new style object - * @param lineIndex Index of a line - * @param charIndex Index of a char - * @param isEndOfLine True if it's end of line - */ - insertNewlineStyleObject(lineIndex: number, charIndex: number, isEndOfLine: boolean): void; - - /** - * Inserts style object for a given line/char index - * @param lineIndex Index of a line - * @param charIndex Index of a char - * @param [style] Style object to insert, if given - */ - insertCharStyleObject(lineIndex: number, charIndex: number, isEndOfLine: boolean): void; - - /** - * Inserts style object(s) - * @param _chars Characters at the location where style is inserted - * @param isEndOfLine True if it's end of line - * @param [useCopiedStyle] Style to insert - */ - insertStyleObjects(_chars: string, isEndOfLine: boolean, useCopiedStyle?: boolean): void; - + removeStyleFromTo(start: number, end: number): void; /** * Shifts line styles up or down - * @param lineIndex Index of a line - * @param offset Can be -1 or +1 + * @param {Number} lineIndex Index of a line + * @param {Number} offset Can any number? */ shiftLineStyles(lineIndex: number, offset: number): void; - /** - * Removes style object - * @param isBeginningOfLine True if cursor is at the beginning of line - * @param [index] Optional index. When not given, current selectionStart is used. + * Inserts new style object + * @param {Number} lineIndex Index of a line + * @param {Number} charIndex Index of a char + * @param {Number} qty number of lines to add + * @param {Array} copiedStyle Array of objects styles */ - removeStyleObject(isBeginningOfLine: boolean, index?: number): void; + insertNewlineStyleObject(lineIndex: number, charIndex: number, qty: number, copiedStyle: any[]): void; /** - * Inserts new line + * Inserts style object for a given line/char index + * @param {Number} lineIndex Index of a line + * @param {Number} charIndex Index of a char + * @param {Number} quantity number Style object to insert, if given + * @param {Array} copiedStyle array of style objecs */ - insertNewline(): void; - + insertCharStyleObject(lineIndex: number, charIndex: number, quantity: number, copiedStyle: any[]): void; /** - * Returns fabric.IText instance from an object representation - * @param object Object to create an instance from + * Inserts style object(s) + * @param {Array} insertedText Characters at the location where style is inserted + * @param {Number} start cursor index for inserting style + * @param {Array} [copiedStyle] array of style objects to insert. */ - static fromObject(object: any): IText; + insertNewStyleBlock(insertedText: any[], start: number, copiedStyle?: any[]): void; + /** + * Set the selectionStart and selectionEnd according to the ne postion of cursor + * mimic the key - mouse navigation when shift is pressed. + */ + setSelectionStartEndWithShift(start: number, end: number, newSelection: number): void; + /** + * Copies selected text + */ + copy(): void; + /** + * convert from fabric to textarea values + */ + fromGraphemeToStringSelection(start: number, end: number, _text: string): {selectionStart: string, selectionEnd: string}; + /** + * convert from textarea to grapheme indexes + */ + fromStringToGraphemeSelection(start: number, end: number, text: string): {selectionStart: string, selectionEnd: string}; + /** + * Gets start offset of a selection + * @param {Event} e Event object + * @param {Boolean} isRight + * @return {Number} + */ + getDownCursorOffset(e: Event, isRight?: boolean): number; + /** + * Returns index of a character corresponding to where an object was clicked + * @param {Event} e Event object + * @return {Number} Index of a character + */ + getSelectionStartFromPointer(e: Event): number; + /** + * @param {Event} e Event object + * @param {Boolean} isRight + * @return {Number} + */ + getUpCursorOffset(e: Event, isRight?: boolean): number; + /** + * Initializes double and triple click event handlers + */ + initClicks(): void; + /** + * Initializes event handlers related to cursor or selection + */ + initCursorSelectionHandlers(): void + /** + * Initializes "dbclick" event handler + */ + initDoubleClickSimulation(): void; + /** + * Initializes hidden textarea (needed to bring up keyboard in iOS) + */ + initHiddenTextarea(): void; + /** + * Initializes "mousedown" event handler + */ + initMousedownHandler(): void; + /** + * Initializes "mouseup" event handler + */ + initMouseupHandler(): void; + /** + * insert characters at start position, before start position. + * start equal 1 it means the text get inserted between actual grapheme 0 and 1 + * if style array is provided, it must be as the same length of text in graphemes + * if end is provided and is bigger than start, old text is replaced. + * start/end ar per grapheme position in _text array. + * + * @param {String} text text to insert + * @param {Array} style array of style objects + * @param {Number} start + * @param {Number} end default to start + 1 + */ + insertChars(text: string, style: any[], start: number, end: number): void; + /** + * Moves cursor down + * @param {Event} e Event object + */ + moveCursorDown(e: Event): void; + /** + * Moves cursor left + * @param {Event} e Event object + */ + moveCursorLeft(e: Event): void; + /** + * Moves cursor left without keeping selection + * @param {Event} e + */ + moveCursorLeftWithoutShift(e: Event): void; + /** + * Moves cursor left while keeping selection + * @param {Event} e + */ + moveCursorLeftWithShift(e: Event): void; + /** + * Moves cursor right + * @param {Event} e Event object + */ + moveCursorRight(e: Event): void; + /** + * Moves cursor right without keeping selection + * @param {Event} e Event object + */ + moveCursorRightWithoutShift(e: Event): void; + /** + * Moves cursor right while keeping selection + * @param {Event} e + */ + moveCursorRightWithShift(e: Event): void; + /** + * Moves cursor up + * @param {Event} e Event object + */ + moveCursorUp(e: Event): void; + /** + * Moves cursor up without shift + * @param {Number} offset + */ + moveCursorWithoutShift(offset: number): void; + /** + * Moves cursor with shift + * @param {Number} offset + */ + moveCursorWithShift(offset: number): void; + /** + * Composition end + */ + onCompositionEnd(): void; + /** + * Composition start + */ + onCompositionStart(): void; + /** + * Handles onInput event + * @param {Event} e Event object + */ + onInput(e: Event): void; + /** + * Handles keyup event + * @param {Event} e Event object + */ + onKeyDown(e: Event): void; + /** + * Handles keyup event + * We handle KeyUp because ie11 and edge have difficulties copy/pasting + * if a copy/cut event fired, keyup is dismissed + * @param {Event} e Event object + */ + onKeyUp(e: Event): void; + /** + * Pastes text + */ + paste(): void; + /** + * Removes characters from start/end + * start/end ar per grapheme position in _text array. + * + * @param {Number} start + * @param {Number} end default to start + 1 + */ + removeChars(start: number, end: number): void; + /** + * Changes cursor location in a text depending on passed pointer (x/y) object + * @param {Event} e Event object + */ + setCursorByClick(e: Event): void; +} +interface ITextboxOptions extends ITextOptions { + /** + * Minimum width of textbox, in pixels. + * @type Number + */ + minWidth?: number; + /** + * Minimum calculated width of a textbox, in pixels. + * fixed to 2 so that an empty textbox cannot go to 0 + * and is still selectable without text. + * @type Number + */ + dynamicMinWidth?: number; + /** + * Override standard Object class values + */ + lockScalingFlip?: boolean; + /** + * Override standard Object class values + * Textbox needs this on false + */ + noScaleCache?: boolean; + /** + * Use this boolean property in order to split strings that have no white space concept. + * this is a cheap way to help with chinese/japaense + * @type Boolean + * @since 2.6.0 + */ + splitByGrapheme?: boolean; +} +export interface Textbox extends ITextboxOptions{} +export class Textbox extends IText { + /** + * Constructor + * @param text Text string + * @param [options] Options object + */ + constructor(text: string, options?: ITextboxOptions); + /** + * Returns true if object has a style property or has it ina specified line + * @param {Number} lineIndex + * @return {Boolean} + */ + styleHas(property: string, lineIndex: number): boolean; + /** + * Returns true if object has no styling or no styling in a line + * @param {Number} lineIndex , lineIndex is on wrapped lines. + * @return {Boolean} + */ + isEmptyStyles(lineIndex: number): boolean; + /** + * Detect if the text line is ended with an hard break + * text and itext do not have wrapping, return false + * @param {Number} lineIndex text to split + * @return {Boolean} + */ + isEndOfWrapping(lineIndex: number): boolean; + /** + * Returns fabric.Textbox instance from an object representation + * @static + * @memberOf fabric.Textbox + * @param {Object} object Object to create an instance from + * @param {Function} [callback] Callback to invoke when an fabric.Textbox instance is created + */ + static fromObject(object: any, callback?: Function): Textbox; } - interface ITriangleOptions extends IObjectOptions { } export class Triangle extends Object { /** @@ -3705,19 +4446,12 @@ export class Triangle extends Object { * @param [options] Options object */ constructor(options?: ITriangleOptions); - - /** - * Returns complexity of an instance - * @return complexity of this instance - */ - complexity(): number; /** * Returns SVG representation of an instance * @param [reviver] Method for further parsing of svg representation. * @return svg representation of an instance */ toSVG(reviver?: Function): string; - /** * Returns Triangle instance from an object representation * @param object Object to create an instance from @@ -3774,18 +4508,18 @@ interface IAllFilters { */ fromObject(object: any): IBrightnessFilter }; - ColorMatrix: { - new(options?: { - /** Filter matrix */ - matrix?: number[] - }): IColorMatrix; - /** - * Returns filter instance from an object representation - * @param object Object to create an instance from - */ - fromObject(object: any): IColorMatrix - }; - Convolute: { + ColorMatrix: { + new(options?: { + /** Filter matrix */ + matrix?: number[] + }): IColorMatrix; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IColorMatrix + }; + Convolute: { new(options?: { opaque?: boolean, /** Filter matrix */ @@ -3974,11 +4708,11 @@ interface IBrightnessFilter extends IBaseFilter { applyTo(canvasEl: HTMLCanvasElement): void; } interface IColorMatrix extends IBaseFilter { - /** - * Applies filter to canvas element - * @param canvasEl Canvas element to apply filter to - */ - applyTo(canvasEl: HTMLCanvasElement): void; + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; } interface IConvoluteFilter extends IBaseFilter { /** @@ -4601,7 +5335,7 @@ interface IUtilMisc { * @param elements SVG elements to group * @param [options] Options object */ - groupSVGElements(elements: any[], options?: any, path?: any): PathGroup; + groupSVGElements(elements: any[], options?: any, path?: string): Object | Group; /** * Populates an object with properties of another object @@ -4660,10 +5394,10 @@ interface IUtilMisc { */ qrDecompose(a: number[]): { angle: number, scaleX: number, scaleY: number, skewX: number, skewY: number, translateX: number, translateY: number }; - /** - * Creates a transform matrix with the specified scale and skew - */ - customTransformMatrix(scaleX: number, scaleY: number, skewX: number): number[]; + /** + * Creates a transform matrix with the specified scale and skew + */ + customTransformMatrix(scaleX: number, scaleY: number, skewX: number): number[]; /** * Returns string representation of function body diff --git a/types/fabric/index.d.ts b/types/fabric/index.d.ts index e8d31aef56..3897987589 100644 --- a/types/fabric/index.d.ts +++ b/types/fabric/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for FabricJS 1.5 +// Type definitions for FabricJS 2.6 // Project: http://fabricjs.com/ // Definitions by: Oliver Klemencic // Joseph Livecchi @@ -7,6 +7,8 @@ // Brian Martinson // Rogerio Teixeira // Bradley Hill +// Bryan Krol +// Glenn Gartner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 export import fabric = require("./fabric-impl"); diff --git a/types/fabric/test/index.ts b/types/fabric/test/index.ts index 9a5c0b24d2..16c8f5c747 100644 --- a/types/fabric/test/index.ts +++ b/types/fabric/test/index.ts @@ -12,7 +12,7 @@ function sample1() { }); for (let i = 0; i < 15; i++) { - fabric.Image.fromURL('../assets/ladybug.png', img => { + fabric.Image.fromURL('../assets/ladybug.png', (img: fabric.Image) => { img.set({ left: fabric.util.getRandomInt(0, 600), top: fabric.util.getRandomInt(0, 500), @@ -122,7 +122,7 @@ function sample3() { } }); - const image = fabric.Image.fromURL('../assets/printio.png', img => { + const image = fabric.Image.fromURL('../assets/printio.png', (img: fabric.Image) => { const oImg = img.set({ left: 300, top: 300, angle: -15 }).scale(0.9); canvas.add(oImg).renderAll(); canvas.setActiveObject(oImg); @@ -236,21 +236,21 @@ function sample4() { const topControl = $('top-control'); topControl.onchange = function(this: HTMLInputElement) { - rect.setTop(+this.value).setCoords(); + rect.set('top',+this.value).setCoords(); canvas.renderAll(); }; const leftControl = $('left-control'); leftControl.onchange = function(this: HTMLInputElement) { - rect.setLeft(+this.value).setCoords(); + rect.set('left',+this.value).setCoords(); canvas.renderAll(); }; function updateControls() { - scaleControl.value = rect.getScaleX().toString(); - angleControl.value = rect.getAngle().toString(); - leftControl.value = rect.getLeft().toString(); - topControl.value = rect.getTop().toString(); + scaleControl.value = rect.scaleX.toString(); + angleControl.value = rect.angle.toString(); + leftControl.value = rect.left.toString(); + topControl.value = rect.top.toString(); } canvas.on({ 'object:moving': updateControls, @@ -331,10 +331,10 @@ function sample6() { canvas.centerObject(obj); canvas.add(obj); - obj.clone(clone => canvas.add(clone.set({ left: 100, top: 100, angle: -15 }))); - obj.clone(clone => canvas.add(clone.set({ left: 480, top: 100, angle: 15 }))); - obj.clone(clone => canvas.add(clone.set({ left: 100, top: 400, angle: -15 }))); - obj.clone(clone => canvas.add(clone.set({ left: 480, top: 400, angle: 15 }))); + obj.clone((clone: fabric.Object) => canvas.add(clone.set({ left: 100, top: 100, angle: -15 }))); + obj.clone((clone: fabric.Object) => canvas.add(clone.set({ left: 480, top: 100, angle: 15 }))); + obj.clone((clone: fabric.Object) => canvas.add(clone.set({ left: 100, top: 400, angle: -15 }))); + obj.clone((clone: fabric.Object) => canvas.add(clone.set({ left: 480, top: 400, angle: 15 }))); canvas.on('mouse:move', options => { const p = canvas.getPointer(options.e); @@ -343,7 +343,7 @@ function sample6() { const distX = Math.abs(p.x - obj.left); const distY = Math.abs(p.y - obj.top); const dist = Math.round(Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2))); - obj.setOpacity(1 / (dist / 20)); + obj.set('opacity', (1 / (dist / 20))); }); }); }); @@ -357,7 +357,7 @@ function sample7() { const canvas = new fabric.Canvas('c', { selection: false }); setInterval(() => { - fabric.Image.fromURL('../assets/ladybug.png', obj => { + fabric.Image.fromURL('../assets/ladybug.png', (obj: fabric.Object) => { const img = obj; img.set('left', fabric.util.getRandomInt(200, 600)).set('top', -50); img.movingLeft = !!Math.round(Math.random()); @@ -373,7 +373,7 @@ function sample7() { if (img.left > 900 || img.top > 500) { canvas.remove(img); } else { - img.setAngle(img.getAngle() + 2); + img.setAngle(img.angle + 2); } }); canvas.renderAll(); @@ -475,7 +475,7 @@ function sample8() { break; case 'image1': - fabric.Image.fromURL('../assets/pug.jpg', image => { + fabric.Image.fromURL('../assets/pug.jpg', (image: fabric.Image) => { image.set({ left, top, @@ -489,7 +489,7 @@ function sample8() { break; case 'image2': - fabric.Image.fromURL('../assets/logo.png', image => { + fabric.Image.fromURL('../assets/logo.png', (image: fabric.Image) => { image.set({ left, top, @@ -510,14 +510,7 @@ function sample8() { fabric.loadSVGFromURL(`../assets/${match[0]}.svg`, (objects, options) => { const loadedObject = fabric.util.groupSVGElements(objects, options); - loadedObject.set({ - left, - top, - angle, - padding: 10, - cornerSize: 10 - }); - loadedObject/*.scaleToWidth(300)*/.setCoords(); + loadedObject.setCoords(); // loadedObject.hasRotatingPoint = true; @@ -554,15 +547,8 @@ function sample8() { const removeSelectedEl = document.getElementById('remove-selected'); removeSelectedEl.onclick = () => { const activeObject = canvas.getActiveObject(); - const activeGroup = canvas.getActiveGroup(); if (activeObject) { canvas.remove(activeObject); - } else if (activeGroup) { - const objectsInGroup = activeGroup.getObjects(); - canvas.discardActiveGroup(); - objectsInGroup.forEach(object => { - canvas.remove(object); - }); } }; @@ -601,10 +587,9 @@ function sample8() { slider.onchange = function() { const activeObject = canvas.getActiveObject(); - const activeGroup = canvas.getActiveGroup(); - if (activeObject || activeGroup) { - (activeObject || activeGroup).setOpacity(parseInt(( this).value, 10) / 100); + if (activeObject) { + activeObject.set('opacity', (parseInt(( this).value, 10) / 100)); canvas.renderAll(); } }; @@ -632,10 +617,9 @@ function sample8() { colorpicker.onchange = function() { const activeObject = canvas.getActiveObject(); - const activeGroup = canvas.getActiveGroup(); - if (activeObject || activeGroup) { - (activeObject || activeGroup).setFill(( this).value); + if (activeObject) { + activeObject.set('fill', ( this).value); canvas.renderAll(); } }; @@ -768,16 +752,6 @@ function sample8() { updateComplexity(); }); - drawingColorEl.onchange = () => { - canvas.freeDrawingColor = drawingColorEl.value; - }; - drawingLineWidthEl.onchange = () => { - canvas.freeDrawingLineWidth = parseInt(drawingLineWidthEl.value, 10) || 1; // disallow 0, NaN, etc. - }; - - canvas.freeDrawingColor = drawingColorEl.value; - canvas.freeDrawingLineWidth = parseInt(drawingLineWidthEl.value, 10) || 1; - const text = `Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt @@ -802,7 +776,7 @@ laboris nisi ut aliquip ex ea commodo consequat.`; }; document.onkeydown = e => { - const obj = canvas.getActiveObject() || canvas.getActiveGroup(); + const obj = canvas.getActiveObject(); if (obj && e.keyCode === 8) { // this is horrible. need to fix, so that unified interface can be used if (obj.type === 'group') { @@ -832,8 +806,7 @@ laboris nisi ut aliquip ex ea commodo consequat.`; const obj = canvas.getActiveObject(); if (obj) { obj.setGradient("fill", { - x2: (getRandomInt(0, 1) ? 0 : obj.width), - y2: (getRandomInt(0, 1) ? 0 : obj.height), + coords: {x2: (getRandomInt(0, 1) ? 0 : obj.width), y2: (getRandomInt(0, 1) ? 0 : obj.height)}, colorStops: { 0: '#' + getRandomColor(), 1: '#' + getRandomColor() @@ -871,8 +844,8 @@ laboris nisi ut aliquip ex ea commodo consequat.`; cmdUnderlineBtn.onclick = function() { const activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.textDecoration = (activeObject.textDecoration === 'underline' ? '' : 'underline'); - (this as HTMLElement).className = activeObject.textDecoration ? 'selected' : ''; + activeObject.underline = !activeObject.underline; + (this as HTMLElement).className = activeObject.underline ? 'selected' : ''; canvas.renderAll(); } }; @@ -884,8 +857,8 @@ laboris nisi ut aliquip ex ea commodo consequat.`; cmdLinethroughBtn.onclick = function() { const activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.textDecoration = (activeObject.textDecoration === 'line-through' ? '' : 'line-through'); - (this as HTMLElement).className = activeObject.textDecoration ? 'selected' : ''; + activeObject.linethrough = !activeObject.linethrough; + (this as HTMLElement).className = activeObject.linethrough ? 'selected' : ''; canvas.renderAll(); } }; @@ -897,8 +870,8 @@ laboris nisi ut aliquip ex ea commodo consequat.`; cmdOverlineBtn.onclick = function() { const activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.textDecoration = (activeObject.textDecoration === 'overline' ? '' : 'overline'); - (this as HTMLElement).className = activeObject.textDecoration ? 'selected' : ''; + activeObject.overline = !activeObject.overline; + (this as HTMLElement).className = activeObject.overline ? 'selected' : ''; canvas.renderAll(); } }; diff --git a/types/get-urls/package.json b/types/get-urls/package.json new file mode 100644 index 0000000000..2dbe933ea4 --- /dev/null +++ b/types/get-urls/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "normalize-url": "*" + } +} diff --git a/types/gijgo/gijgo-tests.ts b/types/gijgo/gijgo-tests.ts index 6e624ad4f6..b1622057cf 100644 --- a/types/gijgo/gijgo-tests.ts +++ b/types/gijgo/gijgo-tests.ts @@ -2,7 +2,7 @@ // Grid $(() => { - this.grid = $('#grid').grid({ + (this as any).grid = $('#grid').grid({ primaryKey: 'ID', columns: [ { field: 'ID', width: 50, sortable: true }, @@ -14,9 +14,9 @@ $(() => { // Dialog $(() => { - this.dialog = $('#playerModal').dialog({ + (this as any).dialog = $('#playerModal').dialog({ autoOpen: false, title: 'Player', width: 400 }); -}); \ No newline at end of file +}); diff --git a/types/giphy-api/giphy-api-tests.ts b/types/giphy-api/giphy-api-tests.ts index c5fc86870e..da286ed612 100644 --- a/types/giphy-api/giphy-api-tests.ts +++ b/types/giphy-api/giphy-api-tests.ts @@ -11,26 +11,26 @@ giphyApi({ apiKey: 'API KEY' }); const searchOptions: giphyApi.SearchOptions = { q: 'pokemon', rating: 'g' }; const giphy: giphyApi.Giphy = giphyApi(); giphy.search('pokemon', cb); -giphy.search('pokemon').then(res => {}); +giphy.search('pokemon').then(res => res.data[0]); giphy.search(searchOptions, cb); -giphy.search({ q: 'pokemon', rating: 'g' }).then(res => {}); +giphy.search({ q: 'pokemon', rating: 'g' }).then(res => res.data[0]); giphy.id('feqkVgjJpYtjy', cb); -giphy.id('feqkVgjJpYtjy').then(res => {}); +giphy.id('feqkVgjJpYtjy').then(res => res.data[0]); giphy.id(['feqkVgjJpYtjy'], cb); -giphy.id(['feqkVgjJpYtjy']).then(res => {}); +giphy.id(['feqkVgjJpYtjy']).then(res => res.data[0]); giphy.translate('superman', cb); -giphy.translate('superman').then(res => {}); +giphy.translate('superman').then(res => res.data.id); giphy.translate({ s: 'superman', rating: 'g', fmt: 'html' }, cb); -giphy.translate({ s: 'superman', rating: 'g' }).then(res => {}); +giphy.translate({ s: 'superman', rating: 'g' }).then(res => res.data.id); giphy.random('superman', cb); -giphy.random('superman').then(res => {}); +giphy.random('superman').then(res => res.data.id); giphy.random({ tag: 'superman', rating: 'g' }, cb); -giphy.random({ tag: 'superman', rating: 'g' }).then(res => {}); +giphy.random({ tag: 'superman', rating: 'g' }).then(res => res.data.id); giphy.trending(cb); -giphy.trending().then(res => {}); +giphy.trending().then(res => res.data[0]); giphy.trending({ limit: 2, rating: 'g' }); -giphy.trending({ limit: 2, rating: 'g' }).then(res => {}); +giphy.trending({ limit: 2, rating: 'g' }).then(res => res.data[0]); diff --git a/types/giphy-api/index.d.ts b/types/giphy-api/index.d.ts index d121eff979..1b9b58b324 100644 --- a/types/giphy-api/index.d.ts +++ b/types/giphy-api/index.d.ts @@ -30,7 +30,16 @@ interface BaseImage { height: string; } -type Callback = (err: Error, res: giphyApi.Result) => void; +interface BaseResponse { + pagination: { total_count: number; count: number; offset: number }; + meta: { + status: number; + msg: string; + response_id: string; + }; +} + +type Callback = (err: Error, res: TResponse) => void; declare function giphyApi(apiKeyOrOptions?: string | giphyApi.GiphyOptions): giphyApi.Giphy; @@ -48,131 +57,131 @@ declare namespace giphyApi { } interface Giphy { - search(queryOrOptions: string | SearchOptions, cb: Callback): void; - search(queryOrOptions: string | SearchOptions): Promise; - id(ids: string | string[], cb: Callback): void; - id(ids: string | string[]): Promise; - translate(termOrOptions: string | TranslateOptions, cb: Callback): void; - translate(termOrOptions: string | TranslateOptions): Promise; - random(tagOrOptions: string | RandomOptions, cb: Callback): void; - random(tagOrOptions: string | RandomOptions): Promise; - trending(options: TrendingOptions, cb: Callback): void; - trending(cb: Callback): void; - trending(options?: TrendingOptions): Promise; + search(queryOrOptions: string | SearchOptions, cb: Callback): void; + search(queryOrOptions: string | SearchOptions): Promise; + id(ids: string | string[], cb: Callback): void; + id(ids: string | string[]): Promise; + translate(termOrOptions: string | TranslateOptions, cb: Callback): void; + translate(termOrOptions: string | TranslateOptions): Promise; + random(tagOrOptions: string | RandomOptions, cb: Callback): void; + random(tagOrOptions: string | RandomOptions): Promise; + trending(options: TrendingOptions, cb: Callback): void; + trending(cb: Callback): void; + trending(options?: TrendingOptions): Promise; } - interface Result { - data: [ - { - type: string; - id: string; - slug: string; - url: string; - bitly_url: string; - embed_url: string; - username: string; - source: string; - rating: Rating; - content_url: string; - user?: { - avatar_url: string; - banner_url: string; - profile_url: string; - username: string; - display_name: string; - twitter: string; - }, - source_tld: string; - source_post_url: string; - update_datetime: string; - create_datetime: string; - import_datetime: string; - trending_datetime: string; - title: string; - images: { - fixed_height: BaseImage & { - size: string; - mp4: string; - mp4_size: string; - webp: string; - webp_size: string; - }; - fixed_height_still: BaseImage; - fixed_height_downsampled: BaseImage & { - size: string; - webp: string; - webp_size: string; - }; - fixed_width: BaseImage & { - size: string; - mp4: string; - mp4_size: string; - webp: string; - webp_size: string; - }; - original_still: BaseImage; - fixed_width_still: BaseImage; - fixed_width_downsampled: BaseImage & { - size: string; - webp: string; - webp_size: string; - }; - fixed_height_small: BaseImage & { - size: string; - mp4: string; - mp4_size: string; - webp: string; - webp_size: string; - }; - fixed_height_small_still: BaseImage; - fixed_width_small: BaseImage & { - size: string; - mp4: string; - mp4_size: string; - webp: string; - webp_size: string; - }; - fixed_width_small_still: BaseImage; - downsized: BaseImage & { - size: string; - }; - downsized_still: BaseImage; - downsized_large: BaseImage & { - size: string; - }; - downsized_medium: BaseImage & { - size: string; - }; - downsized_small: BaseImage & { - size: string; - }; - original: BaseImage & { - size: string; - frames: string; - mp4: string; - mp4_size: string; - webp: string; - webp_size: string; - }; - looping: { mp4: string; }; - preview: { - width: string; - height: string; - mp4: string; - mp4_size: string; - }; - preview_gif: BaseImage & { - size: string; - }; - }; - } - ]; - pagination: { total_count: number; count: number; offset: number }; - meta: { - status: number; - msg: string; - response_id: string; + interface Images { + fixed_height: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; }; + fixed_height_still: BaseImage; + fixed_height_downsampled: BaseImage & { + size: string; + webp: string; + webp_size: string; + }; + fixed_width: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + original_still: BaseImage; + fixed_width_still: BaseImage; + fixed_width_downsampled: BaseImage & { + size: string; + webp: string; + webp_size: string; + }; + fixed_height_small: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + fixed_height_small_still: BaseImage; + fixed_width_small: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + fixed_width_small_still: BaseImage; + downsized: BaseImage & { + size: string; + }; + downsized_still: BaseImage; + downsized_large: BaseImage & { + size: string; + }; + downsized_medium: BaseImage & { + size: string; + }; + downsized_small: BaseImage & { + size: string; + }; + original: BaseImage & { + size: string; + frames: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + looping: { mp4: string; }; + preview: { + width: string; + height: string; + mp4: string; + mp4_size: string; + }; + preview_gif: BaseImage & { + size: string; + }; + } + + interface GIFObject { + type: string; + id: string; + slug: string; + url: string; + bitly_url: string; + embed_url: string; + username: string; + source: string; + rating: Rating; + content_url: string; + user?: { + avatar_url: string; + banner_url: string; + profile_url: string; + username: string; + display_name: string; + twitter: string; + }; + source_tld: string; + source_post_url: string; + update_datetime: string; + create_datetime: string; + import_datetime: string; + trending_datetime: string; + title: string; + images: Images; + } + + interface MultiResponse extends BaseResponse { + data: GIFObject[]; + } + + interface SingleResponse extends BaseResponse { + data: GIFObject; } } diff --git a/types/gl-vec3/add.d.ts b/types/gl-vec3/add.d.ts new file mode 100644 index 0000000000..a26dfc655c --- /dev/null +++ b/types/gl-vec3/add.d.ts @@ -0,0 +1,6 @@ +/** + * Adds two number's. + */ +declare function add(out: number[], a: number[], b: number[]): number[]; + +export default add; diff --git a/types/gl-vec3/angle.d.ts b/types/gl-vec3/angle.d.ts new file mode 100644 index 0000000000..366b1cb4b7 --- /dev/null +++ b/types/gl-vec3/angle.d.ts @@ -0,0 +1,6 @@ +/** + * Get the angle between two 3D vectors. + */ +declare function angle(a: number[], b: number[]): number; + +export default angle; diff --git a/types/gl-vec3/clone.d.ts b/types/gl-vec3/clone.d.ts new file mode 100644 index 0000000000..7b56113caa --- /dev/null +++ b/types/gl-vec3/clone.d.ts @@ -0,0 +1,6 @@ +/** + * Creates a new number initialized with values from an existing vector. + */ +declare function clone(a: number[]): number[]; + +export default clone; diff --git a/types/gl-vec3/copy.d.ts b/types/gl-vec3/copy.d.ts new file mode 100644 index 0000000000..821f2493a7 --- /dev/null +++ b/types/gl-vec3/copy.d.ts @@ -0,0 +1,6 @@ +/** + * Copy the values from one number to another. + */ +declare function copy(out: number[], a: number[]): number[]; + +export default copy; diff --git a/types/gl-vec3/create.d.ts b/types/gl-vec3/create.d.ts new file mode 100644 index 0000000000..5577d59d7d --- /dev/null +++ b/types/gl-vec3/create.d.ts @@ -0,0 +1,6 @@ +/** + * Creates a new, empty number. + */ +declare function create(): number[]; + +export default create; diff --git a/types/gl-vec3/dist.d.ts b/types/gl-vec3/dist.d.ts new file mode 100644 index 0000000000..bb4df7b83f --- /dev/null +++ b/types/gl-vec3/dist.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the euclidian distance between two number's. Aliased as dist. + */ +declare function dist(a: number[], b: number[]): number; + +export default dist; diff --git a/types/gl-vec3/div.d.ts b/types/gl-vec3/div.d.ts new file mode 100644 index 0000000000..be3bcf68a0 --- /dev/null +++ b/types/gl-vec3/div.d.ts @@ -0,0 +1,6 @@ +/** + * Divides two number's. Aliased as div. + */ +declare function div(out: number[], a: number[], b: number[]): number[]; + +export default div; diff --git a/types/gl-vec3/dot.d.ts b/types/gl-vec3/dot.d.ts new file mode 100644 index 0000000000..efe2caf624 --- /dev/null +++ b/types/gl-vec3/dot.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the dot product of two number's. + */ +declare function dot(a: number[], b: number[]): number; + +export default dot; diff --git a/types/gl-vec3/equals.d.ts b/types/gl-vec3/equals.d.ts new file mode 100644 index 0000000000..91aeaa3bbd --- /dev/null +++ b/types/gl-vec3/equals.d.ts @@ -0,0 +1,6 @@ +/** + * Returns whether or not the vectors have approximately the same elements in the same position.. + */ +declare function equals(a: number[], b: number[]): boolean; + +export default equals; diff --git a/types/gl-vec3/exactEquals.d.ts b/types/gl-vec3/exactEquals.d.ts new file mode 100644 index 0000000000..c68b328f69 --- /dev/null +++ b/types/gl-vec3/exactEquals.d.ts @@ -0,0 +1,6 @@ +/** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===). + */ +declare function exactEquals(a: number[], b: number[]): boolean; + +export default exactEquals; diff --git a/types/gl-vec3/forEach.d.ts b/types/gl-vec3/forEach.d.ts new file mode 100644 index 0000000000..8805286fb0 --- /dev/null +++ b/types/gl-vec3/forEach.d.ts @@ -0,0 +1,6 @@ +/** + * Perform some operation over an array of numbers. + */ +declare function forEach(a: number[], stride: number, offset: number, count: number, fn: (a: number[], b: number[], arg: object) => number[], arg: object): number[]; + +export default forEach; diff --git a/types/gl-vec3/fromValues.d.ts b/types/gl-vec3/fromValues.d.ts new file mode 100644 index 0000000000..8fd52fbcee --- /dev/null +++ b/types/gl-vec3/fromValues.d.ts @@ -0,0 +1,6 @@ +/** + * Creates a new number initialized with the given values. + */ +declare function fromValues(x: number, y: number, z: number): number[]; + +export default fromValues; diff --git a/types/gl-vec3/gl-vec3-tests.ts b/types/gl-vec3/gl-vec3-tests.ts new file mode 100644 index 0000000000..67be9102a9 --- /dev/null +++ b/types/gl-vec3/gl-vec3-tests.ts @@ -0,0 +1,121 @@ +import * as GlVec3 from "gl-vec3"; +import GLVec3Add from "gl-vec3/add"; +import GLVec3Angle from "gl-vec3/angle"; +import GLVec3Clone from "gl-vec3/clone"; +import GLVec3Copy from "gl-vec3/copy"; +import GLVec3Create from "gl-vec3/create"; +import GLVec3Dist from "gl-vec3/dist"; +import GLVec3Div from "gl-vec3/div"; +import GLVec3Dot from "gl-vec3/dot"; +import GLVec3Equals from "gl-vec3/equals"; +import GLVec3exactEquals from "gl-vec3/exactEquals"; +import GLVec3forEach from "gl-vec3/forEach"; +import GLVec3fromValues from "gl-vec3/fromValues"; +import GLVec3Inverse from "gl-vec3/inverse"; +import GLVec3Len from "gl-vec3/len"; +import GLVec3Lerp from "gl-vec3/lerp"; +import GLVec3Max from "gl-vec3/max"; +import GLVec3Min from "gl-vec3/min"; +import GLVec3Mul from "gl-vec3/mul"; +import GLVec3Negate from "gl-vec3/negate"; +import GLVec3Normalize from "gl-vec3/normalize"; +import GLVec3Random from "gl-vec3/random"; +import GLVec3Scale from "gl-vec3/scale"; +import GLVec3ScaleAndAdd from "gl-vec3/scaleAndAdd"; +import GLVec3Set from "gl-vec3/set"; +import GLVec3SqrDist from "gl-vec3/sqrDist"; +import GLVec3SqrLen from "gl-vec3/sqrLen"; +import GLVec3Sub from "gl-vec3/sub"; +import GLVec3TransformMat3 from "gl-vec3/transformMat3"; +import GLVec3TransformMat4 from "gl-vec3/transformMat4"; +import GLVec3TransformQuat from "gl-vec3/transformQuat"; + +GlVec3.add([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3Add([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.angle([1, 2, 3], [1, 2, 3]); +GLVec3Angle([1, 2, 3], [1, 2, 3]); + +GlVec3.clone([1, 2, 3]); +GLVec3Clone([1, 2, 3]); + +GlVec3.copy([1, 2, 3], [1, 2, 3]); +GLVec3Copy([1, 2, 3], [1, 2, 3]); + +GlVec3.create(); +GLVec3Create(); + +GlVec3.dist([1, 2, 3], [1, 2, 3]); +GLVec3Dist([1, 2, 3], [1, 2, 3]); + +GlVec3.div([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3Div([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.dot([1, 2, 3], [1, 2, 3]); +GLVec3Dot([1, 2, 3], [1, 2, 3]); + +GlVec3.forEach([1, 2, 3], 5, 6, 1, () => [3], {}); +GLVec3forEach([1, 2, 3], 5, 6, 1, () => [3], {}); + +GlVec3.fromValues(1, 2, 3); +GLVec3fromValues(1, 2, 3); + +GlVec3.equals([1, 2, 3], [1, 2, 3]); +GLVec3Equals([1, 2, 3], [1, 2, 3]); + +GlVec3.exactEquals([1, 2, 3], [1, 2, 3]); +GLVec3exactEquals([1, 2, 3], [1, 2, 3]); + +GlVec3.inverse([1, 2, 3], [1, 2, 3]); +GLVec3Inverse([1, 2, 3], [1, 2, 3]); + +GlVec3.len([1, 2, 3]); +GLVec3Len([1, 2, 3]); + +GlVec3.lerp([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); +GLVec3Lerp([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); + +GlVec3.max([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3Max([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.min([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3Min([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.mul([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3Mul([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.negate([1, 2, 3], [1, 2, 3]); +GLVec3Negate([1, 2, 3], [1, 2, 3]); + +GlVec3.normalize([1, 2, 3], [1, 2, 3]); +GLVec3Normalize([1, 2, 3], [1, 2, 3]); + +GlVec3.random([1, 2, 3], 6); +GLVec3Random([1, 2, 3], 6); + +GlVec3.scale([1, 2, 3], [1, 2, 3], 6); +GLVec3Scale([1, 2, 3], [1, 2, 3], 6); + +GlVec3.scaleAndAdd([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); +GLVec3ScaleAndAdd([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); + +GlVec3.set([1, 2, 3], 1, 2, 6); +GLVec3Set([1, 2, 3], 1, 2, 6); + +GlVec3.sqrDist([1, 2, 3], [1, 2, 3]); +GLVec3SqrDist([1, 2, 3], [1, 2, 3]); + +GlVec3.sqrLen([1, 2, 3]); +GLVec3SqrLen([1, 2, 3]); + +GlVec3.sub([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3Sub([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.transformMat3([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3TransformMat3([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.transformMat4([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3TransformMat4([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.transformQuat([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3TransformQuat([1, 2, 3], [1, 2, 3], [1, 2, 3]); diff --git a/types/gl-vec3/index.d.ts b/types/gl-vec3/index.d.ts new file mode 100644 index 0000000000..0d90cfe981 --- /dev/null +++ b/types/gl-vec3/index.d.ts @@ -0,0 +1,190 @@ +// Type definitions for gl-vec3 1.1 +// Project: https://github.com/stackgl/gl-vec3 +// Definitions by: Adam Zerella +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.3 + +/** + * Adds two number's. + */ +export function add(out: number[], a: number[], b: number[]): number[]; + +/** + * Get the angle between two 3D vectors. + */ +export function angle(a: number[], b: number[]): number; + +/** + * Creates a new number initialized with values from an existing vector. + */ +export function clone(a: number[]): number[]; + +/** + * Math.ceil the components of a number. + */ +export function ceil(out: number[], a: number[]): number[]; + +/** + * Copy the values from one number to another. + */ +export function copy(out: number[], a: number[]): number[]; + +/** + * Creates a new, empty number. + */ +export function create(): number[]; + +/** + * Computes the cross product of two number's. + */ +export function cross(out: number[], a: number[], b: number[]): number[]; + +/** + * Calculates the euclidian distance between two number's. Aliased as dist. + */ +export function dist(a: number[], b: number[]): number; + +/** + * Divides two number's. Aliased as div. + */ +export function div(out: number[], a: number[], b: number[]): number[]; + +/** + * Calculates the dot product of two number's. + */ +export function dot(a: number[], b: number[]): number; + +/** + * Returns whether or not the vectors have approximately the same elements in the same position.. + */ +export function equals(a: number[], b: number[]): boolean; + +/** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===). + */ +export function exactEquals(a: number[], b: number[]): boolean; + +/** + * Math.floor the components of a number. + */ +export function floor(out: number[], a: number[]): number[]; + +/** + * Perform some operation over an array of numbers. + */ +export function forEach(a: number[], stride: number, offset: number, count: number, fn: (a: number[], b: number[], arg: object) => number[], arg: object): number[]; + +/** + * Creates a new number initialized with the given values. + */ +export function fromValues(x: number, y: number, z: number): number[]; + +/** + * Returns the inverse of the components of a number. + */ +export function inverse(out: number[], a: number[]): number[]; + +/** + * Calculates the length of a number. Aliased as len. + */ +export function len(a: number[]): number; + +/** + * Performs a linear interpolation between two number]'s. + */ +export function lerp(out: number[], a: number[], b: number[], t: number): number[]; + +/** + * Returns the maximum of two number's. + */ +export function max(out: number[], a: number[], b: number[]): number[]; + +/** + * Returns the minimum of two number's. + */ +export function min(out: number[], a: number[], b: number[]): number[]; + +/** + * Multiplies two number's. Aliased as mul. + */ +export function mul(out: number[], a: number[], b: number[]): number[]; + +/** + * Negates the components of a number. + */ +export function negate(out: number[], a: number[]): number[]; + +/** + * Normalize a number + */ +export function normalize(out: number[], a: number[]): number[]; + +/** + * Generates a random vector with the given scale. + */ +export function random(out: number[], scale: number): number[]; + +/** + * Rotate a 3D vector around the x-axis. + */ +export function rotateX(out: number[], a: number[], b: number[], c: number): number[]; + +/** + * Rotate a 3D vector around the y-axis. + */ +export function rotateY(out: number[], a: number[], b: number[], c: number): number[]; + +/** + * Rotate a 3D vector around the z-axis. + */ +export function rotateZ(out: number[], a: number[], b: number[], c: number): number[]; + +/** + * Math.round the components of a number. + */ +export function round(out: number[], a: number[]): number[]; + +/** + * Scales a number by a scalar number. + */ +export function scale(out: number[], a: number[], b: number): number[]; + +/** + * Adds two numbers after scaling the second operand by a scalar value. + */ +export function scaleAndAdd(out: number[], a: number[], b: number[], scale: number): number[]; + +/** + * Set the components of a number to the given values. + */ +export function set(out: number[], x: number, y: number, z: number): number[]; + +/** + * Calculates the squared euclidian distance between two number's. Aliased as sqrDist. + */ +export function sqrDist(a: number[], b: number[]): number[]; + +/** + * Calculates the squared length of a number. Aliased as sqrLen. + */ +export function sqrLen(a: number[]): number[]; + +/** + * Subtracts vector b from vector a. Aliased as sub. + */ +export function sub(out: number[], a: number[], b: number[]): number[]; + +/** + * Transforms the number with a mat3. + */ +export function transformMat3(out: number[], a: number[], m: number[]): number[]; + +/** + * Transforms the number with a mat4. 4th vector component is implicitly '1'. + */ +export function transformMat4(out: number[], a: number[], m: number[]): number[]; + +/** + * Transforms the number with a quat. + */ +export function transformQuat(out: number[], a: number[], q: number[]): number[]; diff --git a/types/gl-vec3/inverse.d.ts b/types/gl-vec3/inverse.d.ts new file mode 100644 index 0000000000..bbe2345665 --- /dev/null +++ b/types/gl-vec3/inverse.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the inverse of the components of a number. + */ +declare function inverse(out: number[], a: number[]): number[]; + +export default inverse; diff --git a/types/gl-vec3/len.d.ts b/types/gl-vec3/len.d.ts new file mode 100644 index 0000000000..0bd0473614 --- /dev/null +++ b/types/gl-vec3/len.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the length of a number. Aliased as len. + */ +declare function len(a: number[]): number; + +export default len; diff --git a/types/gl-vec3/lerp.d.ts b/types/gl-vec3/lerp.d.ts new file mode 100644 index 0000000000..a595db2bf8 --- /dev/null +++ b/types/gl-vec3/lerp.d.ts @@ -0,0 +1,6 @@ +/** + * Performs a linear interpolation between two number]'s. + */ +declare function lerp(out: number[], a: number[], b: number[], t: number): number[]; + +export default lerp; diff --git a/types/gl-vec3/max.d.ts b/types/gl-vec3/max.d.ts new file mode 100644 index 0000000000..37458f7eb9 --- /dev/null +++ b/types/gl-vec3/max.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the maximum of two number's. + */ +declare function max(out: number[], a: number[], b: number[]): number[]; + +export default max; diff --git a/types/gl-vec3/min.d.ts b/types/gl-vec3/min.d.ts new file mode 100644 index 0000000000..6c8cdc6600 --- /dev/null +++ b/types/gl-vec3/min.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the minimum of two number's. + */ +declare function min(out: number[], a: number[], b: number[]): number[]; + +export default min; diff --git a/types/gl-vec3/mul.d.ts b/types/gl-vec3/mul.d.ts new file mode 100644 index 0000000000..76559d847a --- /dev/null +++ b/types/gl-vec3/mul.d.ts @@ -0,0 +1,6 @@ +/** + * Multiplies two number's. Aliased as mul. + */ +declare function mul(out: number[], a: number[], b: number[]): number[]; + +export default mul; diff --git a/types/gl-vec3/negate.d.ts b/types/gl-vec3/negate.d.ts new file mode 100644 index 0000000000..84b6443e30 --- /dev/null +++ b/types/gl-vec3/negate.d.ts @@ -0,0 +1,6 @@ +/** + * Negates the components of a number. + */ +declare function negate(out: number[], a: number[]): number[]; + +export default negate; diff --git a/types/gl-vec3/normalize.d.ts b/types/gl-vec3/normalize.d.ts new file mode 100644 index 0000000000..f060e59f73 --- /dev/null +++ b/types/gl-vec3/normalize.d.ts @@ -0,0 +1,6 @@ +/** + * Normalize a number + */ +declare function normalize(out: number[], a: number[]): number[]; + +export default normalize; diff --git a/types/gl-vec3/random.d.ts b/types/gl-vec3/random.d.ts new file mode 100644 index 0000000000..94fd5f57e4 --- /dev/null +++ b/types/gl-vec3/random.d.ts @@ -0,0 +1,6 @@ +/** + * Generates a random vector with the given scale. + */ +declare function random(out: number[], scale: number): number[]; + +export default random; diff --git a/types/gl-vec3/scale.d.ts b/types/gl-vec3/scale.d.ts new file mode 100644 index 0000000000..b5f8b63e9f --- /dev/null +++ b/types/gl-vec3/scale.d.ts @@ -0,0 +1,6 @@ +/** + * Scales a number by a scalar number. + */ +declare function scale(out: number[], a: number[], b: number): number[]; + +export default scale; diff --git a/types/gl-vec3/scaleAndAdd.d.ts b/types/gl-vec3/scaleAndAdd.d.ts new file mode 100644 index 0000000000..a6eea747bd --- /dev/null +++ b/types/gl-vec3/scaleAndAdd.d.ts @@ -0,0 +1,6 @@ +/** + * Adds two numbers after scaling the second operand by a scalar value. + */ +declare function scaleAndAdd(out: number[], a: number[], b: number[], scale: number): number[]; + +export default scaleAndAdd; diff --git a/types/gl-vec3/set.d.ts b/types/gl-vec3/set.d.ts new file mode 100644 index 0000000000..02d24eda97 --- /dev/null +++ b/types/gl-vec3/set.d.ts @@ -0,0 +1,6 @@ +/** + * Set the components of a number to the given values. + */ +declare function set(out: number[], x: number, y: number, z: number): number[]; + +export default set; diff --git a/types/gl-vec3/sqrDist.d.ts b/types/gl-vec3/sqrDist.d.ts new file mode 100644 index 0000000000..9488750632 --- /dev/null +++ b/types/gl-vec3/sqrDist.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the squared euclidian distance between two number's. Aliased as sqrDist. + */ +declare function sqrDist(a: number[], b: number[]): number[]; + +export default sqrDist; diff --git a/types/gl-vec3/sqrLen.d.ts b/types/gl-vec3/sqrLen.d.ts new file mode 100644 index 0000000000..99e072fa44 --- /dev/null +++ b/types/gl-vec3/sqrLen.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the squared length of a number. Aliased as sqrLen. + */ +declare function sqrLen(a: number[]): number[]; + +export default sqrLen; diff --git a/types/gl-vec3/sub.d.ts b/types/gl-vec3/sub.d.ts new file mode 100644 index 0000000000..10bcab9eca --- /dev/null +++ b/types/gl-vec3/sub.d.ts @@ -0,0 +1,6 @@ +/** + * Subtracts vector b from vector a. Aliased as sub. + */ +declare function sub(out: number[], a: number[], b: number[]): number[]; + +export default sub; diff --git a/types/gl-vec3/transformMat3.d.ts b/types/gl-vec3/transformMat3.d.ts new file mode 100644 index 0000000000..bab8234194 --- /dev/null +++ b/types/gl-vec3/transformMat3.d.ts @@ -0,0 +1,6 @@ +/** + * Transforms the number with a mat3. + */ +declare function transformMat3(out: number[], a: number[], m: number[]): number[]; + +export default transformMat3; diff --git a/types/gl-vec3/transformMat4.d.ts b/types/gl-vec3/transformMat4.d.ts new file mode 100644 index 0000000000..35c6424380 --- /dev/null +++ b/types/gl-vec3/transformMat4.d.ts @@ -0,0 +1,6 @@ +/** + * Transforms the number with a mat4. 4th vector component is implicitly '1'. + */ +declare function transformMat4(out: number[], a: number[], m: number[]): number[]; + +export default transformMat4; diff --git a/types/gl-vec3/transformQuat.d.ts b/types/gl-vec3/transformQuat.d.ts new file mode 100644 index 0000000000..2cba13bfc8 --- /dev/null +++ b/types/gl-vec3/transformQuat.d.ts @@ -0,0 +1,6 @@ +/** + * Transforms the number with a quat. + */ +declare function transformQuat(out: number[], a: number[], q: number[]): number[]; + +export default transformQuat; diff --git a/types/gl-vec3/tsconfig.json b/types/gl-vec3/tsconfig.json new file mode 100644 index 0000000000..5382911c1a --- /dev/null +++ b/types/gl-vec3/tsconfig.json @@ -0,0 +1,55 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [ + + ], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "angle.d.ts", + "add.d.ts", + "clone.d.ts", + "copy.d.ts", + "create.d.ts", + "dist.d.ts", + "div.d.ts", + "dot.d.ts", + "equals.d.ts", + "exactEquals.d.ts", + "forEach.d.ts", + "fromValues.d.ts", + "inverse.d.ts", + "len.d.ts", + "lerp.d.ts", + "max.d.ts", + "min.d.ts", + "mul.d.ts", + "negate.d.ts", + "normalize.d.ts", + "random.d.ts", + "scale.d.ts", + "scaleAndAdd.d.ts", + "set.d.ts", + "sqrDist.d.ts", + "sqrLen.d.ts", + "sub.d.ts", + "transformMat3.d.ts", + "transformMat4.d.ts", + "transformQuat.d.ts", + "gl-vec3-tests.ts" + ] +} diff --git a/types/gl-vec3/tslint.json b/types/gl-vec3/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/gl-vec3/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/gl-vec4/add.d.ts b/types/gl-vec4/add.d.ts new file mode 100644 index 0000000000..8d7cb4e851 --- /dev/null +++ b/types/gl-vec4/add.d.ts @@ -0,0 +1,6 @@ +/** + * Adds two vec4's. + */ +declare function add(out: number[], a: number[], b: number[]): number[]; + +export default add; diff --git a/types/gl-vec4/clone.d.ts b/types/gl-vec4/clone.d.ts new file mode 100644 index 0000000000..e2b7777cd2 --- /dev/null +++ b/types/gl-vec4/clone.d.ts @@ -0,0 +1,6 @@ +/** + * Creates a new vec4 initialized with values from an existing vector. + */ +declare function clone(a: number[]): number[]; + +export default clone; diff --git a/types/gl-vec4/copy.d.ts b/types/gl-vec4/copy.d.ts new file mode 100644 index 0000000000..76e60c5cf6 --- /dev/null +++ b/types/gl-vec4/copy.d.ts @@ -0,0 +1,6 @@ +/** + * Copy the values from one vec4 to another. + */ +declare function copy(out: number[], a: number[]): number[]; + +export default copy; diff --git a/types/gl-vec4/create.d.ts b/types/gl-vec4/create.d.ts new file mode 100644 index 0000000000..93216fe4b0 --- /dev/null +++ b/types/gl-vec4/create.d.ts @@ -0,0 +1,6 @@ +/** + * Creates a new, empty vec4. + */ +declare function create(): number[]; + +export default create; diff --git a/types/gl-vec4/distance.d.ts b/types/gl-vec4/distance.d.ts new file mode 100644 index 0000000000..201b734b17 --- /dev/null +++ b/types/gl-vec4/distance.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the euclidian distance between two vec4's. + */ +declare function distance(a: number[], b: number[]): number; + +export default distance; diff --git a/types/gl-vec4/divide.d.ts b/types/gl-vec4/divide.d.ts new file mode 100644 index 0000000000..847dd7ce73 --- /dev/null +++ b/types/gl-vec4/divide.d.ts @@ -0,0 +1,6 @@ +/** + * Divides two vec4's. + */ +declare function divide(out: number[], a: number[], b: number[]): number[]; + +export default divide; diff --git a/types/gl-vec4/dot.d.ts b/types/gl-vec4/dot.d.ts new file mode 100644 index 0000000000..218d2bfe91 --- /dev/null +++ b/types/gl-vec4/dot.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the dot product of two vec4's. + */ +declare function dot(a: number[], b: number[]): number; + +export default dot; diff --git a/types/gl-vec4/fromValues.d.ts b/types/gl-vec4/fromValues.d.ts new file mode 100644 index 0000000000..84d60a9c10 --- /dev/null +++ b/types/gl-vec4/fromValues.d.ts @@ -0,0 +1,6 @@ +/** + * Creates a new vec4 initialized with the given values. + */ +declare function fromValues(x: number, y: number, z: number, w: number): number[]; + +export default fromValues; diff --git a/types/gl-vec4/gl-vec4-tests.ts b/types/gl-vec4/gl-vec4-tests.ts new file mode 100644 index 0000000000..302596450a --- /dev/null +++ b/types/gl-vec4/gl-vec4-tests.ts @@ -0,0 +1,102 @@ +import * as glVec from "gl-vec4"; + +import glVecAdd from "gl-vec4/add"; +import glVecClone from "gl-vec4/clone"; +import glVecCopy from "gl-vec4/copy"; +import glVecCreate from "gl-vec4/create"; +import glVecDistance from "gl-vec4/distance"; +import glVecDivide from "gl-vec4/divide"; +import glVecDot from "gl-vec4/dot"; +import glVecFromValues from "gl-vec4/fromValues"; +import glVecInverse from "gl-vec4/inverse"; +import glVecLength from "gl-vec4/length"; +import glVecLerp from "gl-vec4/lerp"; +import glVecMax from "gl-vec4/max"; +import glVecMin from "gl-vec4/min"; +import glVecMultiply from "gl-vec4/multiply"; +import glVecNegate from "gl-vec4/negate"; +import glVecNormalize from "gl-vec4/normalize"; +import glVecRandom from "gl-vec4/random"; +import glVecScale from "gl-vec4/scale"; +import glVecScaleAndAdd from "gl-vec4/scaleAndAdd"; +import glVecSet from "gl-vec4/set"; +import glVecSqrdDistance from "gl-vec4/squaredDistance"; +import glVecSqrdLength from "gl-vec4/squaredLength"; +import glVecSubtract from "gl-vec4/subtract"; +import glVecTransformMat4 from "gl-vec4/transformMat4"; +import glVecTransformQuat from "gl-vec4/transformQuat"; + +glVec.add([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecAdd([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.clone([1, 2, 3]); +glVecClone([1, 2, 3]); + +glVec.copy([1, 2, 3], [1, 2, 3]); +glVecCopy([1, 2, 3], [1, 2, 3]); + +glVec.create(); +glVecCreate(); + +glVec.distance([1, 2, 3], [1, 2, 3]); +glVecDistance([1, 2, 3], [1, 2, 3]); + +glVec.divide([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecDivide([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.dot([1, 2, 3], [1, 2, 3]); +glVecDot([1, 2, 3], [1, 2, 3]); + +glVec.fromValues(1, 2, 4, 5); +glVecFromValues(1, 2, 4, 5); + +glVec.inverse([1, 2, 3], [1, 2, 3]); +glVecInverse([1, 2, 3], [1, 2, 3]); + +glVec.length([1, 2, 3]); +glVecLength([1, 2, 3]); + +glVec.lerp([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); +glVecLerp([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); + +glVec.max([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecMax([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.min([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecMin([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.multiply([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecMultiply([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.negate([1, 2, 3], [1, 2, 3]); +glVecNegate([1, 2, 3], [1, 2, 3]); + +glVec.normalize([1, 2, 3], [1, 2, 3]); +glVecNormalize([1, 2, 3], [1, 2, 3]); + +glVec.random([1, 2, 3], 6); +glVecRandom([1, 2, 3], 6); + +glVec.scale([1, 2, 3], [1, 2, 3], 6); +glVecScale([1, 2, 3], [1, 2, 3], 6); + +glVec.scaleAndAdd([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); +glVecScaleAndAdd([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); + +glVec.set([1, 2, 3], [1, 2, 3], [1, 2, 3], 6, 6); +glVecSet([1, 2, 3], [1, 2, 3], [1, 2, 3], 6, 6); + +glVec.squaredDistance([1, 2, 3], [1, 2, 3]); +glVecSqrdDistance([1, 2, 3], [1, 2, 3]); + +glVec.squaredLength([1, 2, 3]); +glVecSqrdLength([1, 2, 3]); + +glVec.subtract([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecSubtract([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.transformMat4([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecTransformMat4([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.transformQuat([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecTransformQuat([1, 2, 3], [1, 2, 3], [1, 2, 3]); diff --git a/types/gl-vec4/index.d.ts b/types/gl-vec4/index.d.ts new file mode 100644 index 0000000000..3d5e54e562 --- /dev/null +++ b/types/gl-vec4/index.d.ts @@ -0,0 +1,129 @@ +// Type definitions for gl-vec4 1.0 +// Project: https://github.com/stackgl/gl-vec4 +// Definitions by: Adam Zerella +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Adds two vec4's. + */ +export function add(out: number[], a: number[], b: number[]): number[]; + +/** + * Creates a new vec4 initialized with values from an existing vector. + */ +export function clone(a: number[]): number[]; + +/** + * Copy the values from one vec4 to another. + */ +export function copy(out: number[], a: number[]): number[]; + +/** + * Creates a new, empty vec4. + */ +export function create(): number[]; + +/** + * Calculates the euclidian distance between two vec4's. + */ +export function distance(a: number[], b: number[]): number; + +/** + * Divides two vec4's. + */ +export function divide(out: number[], a: number[], b: number[]): number[]; + +/** + * Calculates the dot product of two vec4's. + */ +export function dot(a: number[], b: number[]): number; + +/** + * Creates a new vec4 initialized with the given values. + */ +export function fromValues(x: number, y: number, z: number, w: number): number[]; + +/** + * Returns the inverse of the components of a vec4. + */ +export function inverse(out: number[], a: number[]): number[]; + +/** + * Calculates the length of a vec4. + */ +export function length(a: number[]): number; + +/** + * Performs a linear interpolation between two vec4's. + */ +export function lerp(out: number[], a: number[], b: number[], t: number): number[]; + +/** + * Returns the maximum of two vec4's. + */ +export function max(out: number[], a: number[], b: number[]): number[]; + +/** + * Returns the minimum of two vec4's. + */ +export function min(out: number[], a: number[], b: number[]): number[]; + +/** + * Multiplies two vec4's. + */ +export function multiply(out: number[], a: number[], b: number[]): number[]; + +/** + * Negates the components of a vec4. + */ +export function negate(out: number[], a: number[]): number[]; + +/** + * Normalize a vec4. + */ +export function normalize(out: number[], a: number[]): number[]; + +/** + * Generates a random vector with the given scale. + */ +export function random(out: number[], scale: number): number[]; + +/** + * Scales a vec4 by a scalar number. + */ +export function scale(out: number[], a: number[], b: number): number[]; + +/** + * Adds two vec4's after scaling the second operand by a scalar value. + */ +export function scaleAndAdd(out: number[], a: number[], b: number[], scale: number): number[]; + +/** + * Set the components of a vec4 to the given values. + */ +export function set(out: number[], x: number[], y: number[], z: number, w: number): number[]; + +/** + * Calculates the squared euclidian distance between two vec4's. + */ +export function squaredDistance(a: number[], b: number[]): number; + +/** + * Calculates the squared length of a vec4. + */ +export function squaredLength(a: number[]): number; + +/** + * Subtracts vector b from vector a. + */ +export function subtract(out: number[], a: number[], b: number[]): number[]; + +/** + * Transforms the vec4 with a mat4.. + */ +export function transformMat4(out: number[], a: number[], m: number[]): number[]; + +/** + * Transforms the vec4 with a quat. + */ +export function transformQuat(out: number[], a: number[], q: number[]): number[]; diff --git a/types/gl-vec4/inverse.d.ts b/types/gl-vec4/inverse.d.ts new file mode 100644 index 0000000000..4df5cb7491 --- /dev/null +++ b/types/gl-vec4/inverse.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the inverse of the components of a vec4. + */ +declare function inverse(out: number[], a: number[]): number[]; + +export default inverse; diff --git a/types/gl-vec4/length.d.ts b/types/gl-vec4/length.d.ts new file mode 100644 index 0000000000..229b629c89 --- /dev/null +++ b/types/gl-vec4/length.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the length of a vec4. + */ +declare function length(a: number[]): number; + +export default length; diff --git a/types/gl-vec4/lerp.d.ts b/types/gl-vec4/lerp.d.ts new file mode 100644 index 0000000000..c56471ecf1 --- /dev/null +++ b/types/gl-vec4/lerp.d.ts @@ -0,0 +1,6 @@ +/** + * Performs a linear interpolation between two vec4's. + */ +declare function lerp(out: number[], a: number[], b: number[], t: number): number[]; + +export default lerp; diff --git a/types/gl-vec4/max.d.ts b/types/gl-vec4/max.d.ts new file mode 100644 index 0000000000..ca179a75ab --- /dev/null +++ b/types/gl-vec4/max.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the maximum of two vec4's. + */ +declare function max(out: number[], a: number[], b: number[]): number[]; + +export default max; diff --git a/types/gl-vec4/min.d.ts b/types/gl-vec4/min.d.ts new file mode 100644 index 0000000000..48544195a5 --- /dev/null +++ b/types/gl-vec4/min.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the minimum of two vec4's. + */ +declare function min(out: number[], a: number[], b: number[]): number[]; + +export default min; diff --git a/types/gl-vec4/multiply.d.ts b/types/gl-vec4/multiply.d.ts new file mode 100644 index 0000000000..9708f570ea --- /dev/null +++ b/types/gl-vec4/multiply.d.ts @@ -0,0 +1,6 @@ +/** + * Multiplies two vec4's. + */ +declare function multiply(out: number[], a: number[], b: number[]): number[]; + +export default multiply; diff --git a/types/gl-vec4/negate.d.ts b/types/gl-vec4/negate.d.ts new file mode 100644 index 0000000000..b62a5bab84 --- /dev/null +++ b/types/gl-vec4/negate.d.ts @@ -0,0 +1,6 @@ +/** + * Negates the components of a vec4. + */ +declare function negate(out: number[], a: number[]): number[]; + +export default negate; diff --git a/types/gl-vec4/normalize.d.ts b/types/gl-vec4/normalize.d.ts new file mode 100644 index 0000000000..2d09e91543 --- /dev/null +++ b/types/gl-vec4/normalize.d.ts @@ -0,0 +1,6 @@ +/** + * Normalize a vec4. + */ +declare function normalize(out: number[], a: number[]): number[]; + +export default normalize; diff --git a/types/gl-vec4/random.d.ts b/types/gl-vec4/random.d.ts new file mode 100644 index 0000000000..94fd5f57e4 --- /dev/null +++ b/types/gl-vec4/random.d.ts @@ -0,0 +1,6 @@ +/** + * Generates a random vector with the given scale. + */ +declare function random(out: number[], scale: number): number[]; + +export default random; diff --git a/types/gl-vec4/scale.d.ts b/types/gl-vec4/scale.d.ts new file mode 100644 index 0000000000..cb6d5747a8 --- /dev/null +++ b/types/gl-vec4/scale.d.ts @@ -0,0 +1,6 @@ +/** + * Scales a vec4 by a scalar number. + */ +declare function scale(out: number[], a: number[], b: number): number[]; + +export default scale; diff --git a/types/gl-vec4/scaleAndAdd.d.ts b/types/gl-vec4/scaleAndAdd.d.ts new file mode 100644 index 0000000000..3912aadceb --- /dev/null +++ b/types/gl-vec4/scaleAndAdd.d.ts @@ -0,0 +1,6 @@ +/** + * Adds two vec4's after scaling the second operand by a scalar value. + */ +declare function scaleAndAdd(out: number[], a: number[], b: number[], scale: number): number[]; + +export default scaleAndAdd; diff --git a/types/gl-vec4/set.d.ts b/types/gl-vec4/set.d.ts new file mode 100644 index 0000000000..36040f5638 --- /dev/null +++ b/types/gl-vec4/set.d.ts @@ -0,0 +1,6 @@ +/** + * Set the components of a vec4 to the given values. + */ +declare function set(out: number[], x: number[], y: number[], z: number, w: number): number[]; + +export default set; diff --git a/types/gl-vec4/squaredDistance.d.ts b/types/gl-vec4/squaredDistance.d.ts new file mode 100644 index 0000000000..539f702ffb --- /dev/null +++ b/types/gl-vec4/squaredDistance.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the squared euclidian distance between two vec4's. + */ +declare function squaredDistance(a: number[], b: number[]): number; + +export default squaredDistance; diff --git a/types/gl-vec4/squaredLength.d.ts b/types/gl-vec4/squaredLength.d.ts new file mode 100644 index 0000000000..226d528c81 --- /dev/null +++ b/types/gl-vec4/squaredLength.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the squared length of a vec4. + */ +declare function squaredLength(a: number[]): number; + +export default squaredLength; diff --git a/types/gl-vec4/subtract.d.ts b/types/gl-vec4/subtract.d.ts new file mode 100644 index 0000000000..1ba0aba3bc --- /dev/null +++ b/types/gl-vec4/subtract.d.ts @@ -0,0 +1,6 @@ +/** + * Subtracts vector b from vector a. + */ +declare function subtract(out: number[], a: number[], b: number[]): number[]; + +export default subtract; diff --git a/types/gl-vec4/transformMat4.d.ts b/types/gl-vec4/transformMat4.d.ts new file mode 100644 index 0000000000..762b5c4bc8 --- /dev/null +++ b/types/gl-vec4/transformMat4.d.ts @@ -0,0 +1,6 @@ +/** + * Transforms the vec4 with a mat4.. + */ +declare function transformMat4(out: number[], a: number[], m: number[]): number[]; + +export default transformMat4; diff --git a/types/gl-vec4/transformQuat.d.ts b/types/gl-vec4/transformQuat.d.ts new file mode 100644 index 0000000000..8f6dadd4c1 --- /dev/null +++ b/types/gl-vec4/transformQuat.d.ts @@ -0,0 +1,6 @@ +/** + * Transforms the vec4 with a quat. + */ +declare function transformQuat(out: number[], a: number[], q: number[]): number[]; + +export default transformQuat; diff --git a/types/gl-vec4/tsconfig.json b/types/gl-vec4/tsconfig.json new file mode 100644 index 0000000000..341f7c3271 --- /dev/null +++ b/types/gl-vec4/tsconfig.json @@ -0,0 +1,50 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [ + + ], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "add.d.ts", + "clone.d.ts", + "copy.d.ts", + "create.d.ts", + "distance.d.ts", + "divide.d.ts", + "dot.d.ts", + "fromValues.d.ts", + "inverse.d.ts", + "length.d.ts", + "lerp.d.ts", + "max.d.ts", + "min.d.ts", + "multiply.d.ts", + "negate.d.ts", + "normalize.d.ts", + "random.d.ts", + "scale.d.ts", + "scaleAndAdd.d.ts", + "set.d.ts", + "squaredDistance.d.ts", + "squaredLength.d.ts", + "subtract.d.ts", + "transformMat4.d.ts", + "transformQuat.d.ts", + "gl-vec4-tests.ts" + ] +} diff --git a/types/gl-vec4/tslint.json b/types/gl-vec4/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/gl-vec4/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/google-apps-script/google-apps-script.base.d.ts b/types/google-apps-script/google-apps-script.base.d.ts index 9f7153a6bb..5c2a8d9155 100644 --- a/types/google-apps-script/google-apps-script.base.d.ts +++ b/types/google-apps-script/google-apps-script.base.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2019-01-23 +// Type definitions for Google Apps Script 2019-02-27 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -284,7 +284,9 @@ declare namespace GoogleAppsScript { * // A simple INFO log message, using sprintf() formatting. * console.info('Timing the %s function (%d arguments)', 'myFunction', 1); * - * // Log a JSON object at a DEBUG level. Writes the stringified object to the log. + * // Log a JSON object at a DEBUG level. If the object contains a property called "message", + * // that is used as the summary in the log viewer, otherwise a stringified version of + * // the object is used as the summary. * var parameters = { * isValid: true, * content: 'some string', diff --git a/types/google-apps-script/google-apps-script.data-studio.d.ts b/types/google-apps-script/google-apps-script.data-studio.d.ts index 332dff6dbc..c86bd39447 100644 --- a/types/google-apps-script/google-apps-script.data-studio.d.ts +++ b/types/google-apps-script/google-apps-script.data-studio.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2019-01-23 +// Type definitions for Google Apps Script 2019-02-27 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -127,6 +127,7 @@ declare namespace GoogleAppsScript { getFormula(): string; getGroup(): string; getId(): string; + getIsReaggregatable(): boolean; getName(): string; getType(): FieldType; isDefault(): boolean; @@ -139,6 +140,7 @@ declare namespace GoogleAppsScript { setGroup(group: string): Field; setId(id: string): Field; setIsHidden(isHidden: boolean): Field; + setIsReaggregatable(isReaggregatable: boolean): Field; setName(name: string): Field; setType(type: FieldType): Field; } diff --git a/types/google-apps-script/google-apps-script.spreadsheet.d.ts b/types/google-apps-script/google-apps-script.spreadsheet.d.ts index d8dc3bc4d0..ba28d9719c 100644 --- a/types/google-apps-script/google-apps-script.spreadsheet.d.ts +++ b/types/google-apps-script/google-apps-script.spreadsheet.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2019-01-23 +// Type definitions for Google Apps Script 2019-02-27 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -49,6 +49,35 @@ declare namespace GoogleAppsScript { */ export enum BandingTheme { LIGHT_GREY, CYAN, GREEN, YELLOW, ORANGE, BLUE, TEAL, GREY, BROWN, LIGHT_GREEN, INDIGO, PINK } + /** + * Access the existing BigQuery data source specification. To create a new data source + * specification, use SpreadsheetApp.newDataSourceSpec(). + */ + export interface BigQueryDataSourceSpec { + copy(): DataSourceSpecBuilder; + getParameters(): DataSourceParameter[]; + getProjectId(): string; + getRawQuery(): string; + getType(): DataSourceType; + } + + /** + * The builder for BigQueryDataSourceSpecBuilder. + */ + export interface BigQueryDataSourceSpecBuilder { + build(): DataSourceSpec; + copy(): DataSourceSpecBuilder; + getParameters(): DataSourceParameter[]; + getProjectId(): string; + getRawQuery(): string; + getType(): DataSourceType; + removeAllParameters(): BigQueryDataSourceSpecBuilder; + removeParameter(parameterName: string): BigQueryDataSourceSpecBuilder; + setParameterFromCell(parameterName: string, sourceCell: string): BigQueryDataSourceSpecBuilder; + setProjectId(projectId: string): BigQueryDataSourceSpecBuilder; + setRawQuery(rawQuery: string): BigQueryDataSourceSpecBuilder; + } + /** * Access boolean conditions in ConditionalFormatRules. Each * conditional format rule may contain a single boolean condition. The boolean condition itself @@ -167,6 +196,154 @@ declare namespace GoogleAppsScript { */ export enum CopyPasteType { PASTE_NORMAL, PASTE_NO_BORDERS, PASTE_FORMAT, PASTE_FORMULA, PASTE_DATA_VALIDATION, PASTE_VALUES, PASTE_CONDITIONAL_FORMATTING, PASTE_COLUMN_WIDTHS } + /** + * An enumeration of data execution error codes. + */ + export enum DataExecutionErrorCode { DATA_EXECUTION_ERROR_CODE_UNSUPPORTED, NONE, TIME_OUT, TOO_MANY_ROWS, TOO_MANY_CELLS, ENGINE, PARAMETER_INVALID, UNSUPPORTED_DATA_TYPE, DUPLICATE_COLUMN_NAMES, INTERRUPTED, OTHER, TOO_MANY_CHARS_PER_CELL } + + /** + * An enumeration of data execution states. + */ + export enum DataExecutionState { DATA_EXECUTION_STATE_UNSUPPORTED, RUNNING, SUCCESS, ERROR, NOT_STARTED } + + /** + * The data execution status. + */ + export interface DataExecutionStatus { + getErrorCode(): DataExecutionErrorCode; + getErrorMessage(): string; + getExecutionState(): DataExecutionState; + getLastRefreshedTime(): Date; + isTruncated(): boolean; + } + + /** + * Access and modify existing data source. To create a data source table with new data source, see + * DataSourceTable. + */ + export interface DataSource { + getSpec(): DataSourceSpec; + updateSpec(spec: DataSourceSpec): DataSource; + } + + /** + * Access existing data source parameters. + */ + export interface DataSourceParameter { + getName(): string; + getSourceCell(): string; + getType(): DataSourceParameterType; + } + + /** + * An enumeration of data source parameter types. + */ + export enum DataSourceParameterType { DATA_SOURCE_PARAMETER_TYPE_UNSUPPORTED, CELL } + + /** + * Access the general settings of an existing data source spec. To access data source spec for + * certain type, use as...() method. To create a new data source spec, use SpreadsheetApp.newDataSourceSpec(). + * + * This example shows how to get information from a BigQuery data source spec. + * + * var dataSourceTable = + * SpreadsheetApp.getActive().getSheetByName("Data Sheet 1").getDataSourceTables()[0]; + * var spec = dataSourceTable.getDataSource().getSpec(); + * if (spec.getType() == SpreadsheetApp.DataSourceType.BIGQUERY) { + * var bqSpec = spec.asBigQuery(); + * Logger.log("Project ID: %s\n", bqSpec.getProjectId()); + * Logger.log("Raw query string: %s\n", bqSpec.getRawQuery()); + * } + */ + export interface DataSourceSpec { + asBigQuery(): BigQueryDataSourceSpec; + copy(): DataSourceSpecBuilder; + getParameters(): DataSourceParameter[]; + getType(): DataSourceType; + } + + /** + * The builder for DataSourceSpec. To create a specification for certain type, use as...() method. To create a new builder, use SpreadsheetApp.newDataSourceSpec(). To use the specification, see DataSourceTable. + * + * This examples show how to build a BigQuery data source specification. + * + * var spec = SpreadsheetApp.newDataSourceSpec() + * .asBigQuery() + * .setProjectId('big_query_project') + * .setRawQuery('select @FIELD from table limit @LIMIT') + * .setParameterFromCell('FIELD', 'Sheet1!A1') + * .setParameterFromCell('LIMIT', 'namedRangeCell') + * .build(); + */ + export interface DataSourceSpecBuilder { + asBigQuery(): BigQueryDataSourceSpecBuilder; + build(): DataSourceSpec; + copy(): DataSourceSpecBuilder; + getParameters(): DataSourceParameter[]; + getType(): DataSourceType; + removeAllParameters(): DataSourceSpecBuilder; + removeParameter(parameterName: string): DataSourceSpecBuilder; + setParameterFromCell(parameterName: string, sourceCell: string): DataSourceSpecBuilder; + } + + /** + * Access and modify existing data source table. To create a new data source table on a new sheet, + * use Spreadsheet.insertSheetWithDataSourceTable(spec). + * + * This example shows how to create a new data source table. + * + * SpreadsheetApp.enableBigQueryExecution(); + * var spreadsheet = SpreadsheetApp.getActive(); + * var spec = SpreadsheetApp.newDataSourceSpec() + * .asBigQuery() + * .setProjectId('big_query_project') + * .setRawQuery('select @FIELD from table limit @LIMIT') + * .setParameterFromCell('FIELD', 'Sheet1!A1') + * .setParameterFromCell('LIMIT', 'namedRangeCell') + * .build(); + * // Starts data execution asynchronously. + * var dataSheet = spreadsheet.insertSheetWithDataSourceTable(spec); + * var dataSourceTable = dataSheet.getDataSourceTables()[0]; + * // waitForCompletion() blocks script execution until data execution completes. + * dataSourceTable.waitForCompletion(60); + * // Check status after execution. + * Logger.log("Data execution state: %s.", dataSourceTable.getStatus().getExecutionState()); + * + * This example shows how to edit a data source. + * + * SpreadsheetApp.enableBigQueryExecution(); + * var dataSheet = SpreadsheetApp.getActive().getSheetByName("Data Sheet 1"); + * var dataSourceTable = dataSheet.getDataSourceTables()[0]; + * var dataSource = dataSourceTable.getDataSource(); + * var newSpec = dataSource.getSpec() + * .copy() + * .asBigQuery() + * .setRawQuery('select name from table limit 2') + * .removeAllParameters() + * .build(); + * // Updates data source specification and starts data execution asynchronously. + * dataSource.updateSpec(newSpec); + * // Check status during execution. + * Logger.log("Data execution state: %s.", dataSourceTable.getStatus().getExecutionState()); + * // waitForCompletion() blocks script execution until data execution completes. + * dataSourceTable.waitForCompletion(60); + * // Check status after execution. + * Logger.log("Data execution state: %s.", dataSourceTable.getStatus().getExecutionState()); + */ + export interface DataSourceTable { + forceRefreshData(): DataSourceTable; + getDataSource(): DataSource; + getRange(): Range; + getStatus(): DataExecutionStatus; + refreshData(): DataSourceTable; + waitForCompletion(timeoutInSeconds: Integer): DataExecutionStatus; + } + + /** + * An enumeration of data source types. + */ + export enum DataSourceType { DATA_SOURCE_TYPE_UNSUPPORTED, BIGQUERY } + /** * Access data validation rules. To create a new rule, use SpreadsheetApp.newDataValidation() and DataValidationBuilder. You can use * Range.setDataValidation(rule) to set the validation rule for a range. @@ -1215,6 +1392,7 @@ declare namespace GoogleAppsScript { getBandings(): Banding[]; getCell(row: Integer, column: Integer): Range; getColumn(): Integer; + getDataSourceTables(): DataSourceTable[]; getDataSourceUrl(): string; getDataTable(): Charts.DataTable; getDataTable(firstRowIsHeader: boolean): Charts.DataTable; @@ -1493,6 +1671,7 @@ declare namespace GoogleAppsScript { getConditionalFormatRules(): ConditionalFormatRule[]; getCurrentCell(): Range; getDataRange(): Range; + getDataSourceTables(): DataSourceTable[]; getDeveloperMetadata(): DeveloperMetadata[]; getFilter(): Filter; getFormUrl(): string; @@ -1627,6 +1806,7 @@ declare namespace GoogleAppsScript { getColumnWidth(columnPosition: Integer): Integer; getCurrentCell(): Range; getDataRange(): Range; + getDataSourceTables(): DataSourceTable[]; getDeveloperMetadata(): DeveloperMetadata[]; getEditors(): Base.User[]; getFormUrl(): string; @@ -1677,6 +1857,7 @@ declare namespace GoogleAppsScript { insertSheet(sheetName: string, sheetIndex: Integer): Sheet; insertSheet(sheetName: string, sheetIndex: Integer, options: Object): Sheet; insertSheet(sheetName: string, options: Object): Sheet; + insertSheetWithDataSourceTable(spec: DataSourceSpec): Sheet; isColumnHiddenByUser(columnPosition: Integer): boolean; isRowHiddenByFilter(rowPosition: Integer): boolean; isRowHiddenByUser(rowPosition: Integer): boolean; @@ -1728,6 +1909,10 @@ declare namespace GoogleAppsScript { BooleanCriteria: typeof BooleanCriteria; BorderStyle: typeof BorderStyle; CopyPasteType: typeof CopyPasteType; + DataExecutionErrorCode: typeof DataExecutionErrorCode; + DataExecutionState: typeof DataExecutionState; + DataSourceParameterType: typeof DataSourceParameterType; + DataSourceType: typeof DataSourceType; DataValidationCriteria: typeof DataValidationCriteria; DeveloperMetadataLocationType: typeof DeveloperMetadataLocationType; DeveloperMetadataVisibility: typeof DeveloperMetadataVisibility; @@ -1744,6 +1929,8 @@ declare namespace GoogleAppsScript { WrapStrategy: typeof WrapStrategy; create(name: string): Spreadsheet; create(name: string, rows: Integer, columns: Integer): Spreadsheet; + enableAllDataSourcesExecution(): void; + enableBigQueryExecution(): void; flush(): void; getActive(): Spreadsheet; getActiveRange(): Range; @@ -1754,6 +1941,7 @@ declare namespace GoogleAppsScript { getSelection(): Selection; getUi(): Base.Ui; newConditionalFormatRule(): ConditionalFormatRuleBuilder; + newDataSourceSpec(): DataSourceSpecBuilder; newDataValidation(): DataValidationBuilder; newFilterCriteria(): FilterCriteriaBuilder; newRichTextValue(): RichTextValueBuilder; 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/history/v3/index.d.ts b/types/history/v3/index.d.ts index 7a6c8116bd..040f5bb0c5 100644 --- a/types/history/v3/index.d.ts +++ b/types/history/v3/index.d.ts @@ -38,6 +38,7 @@ export interface Location { pathname: Pathname; search: Search; query: Query; + hash: Hash; state: LocationState; action: Action; key: LocationKey; @@ -47,6 +48,7 @@ export interface LocationDescriptorObject { pathname?: Pathname; search?: Search; query?: Query; + hash?: Hash; state?: LocationState; } diff --git a/types/howler/index.d.ts b/types/howler/index.d.ts index 0fd16e5f0d..5ee9c40627 100644 --- a/types/howler/index.d.ts +++ b/types/howler/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for howler.js v2.0.5 // Project: https://github.com/goldfire/howler.js -// Definitions by: Pedro Casaubon , Todd Dukart , Alexander Leon , Nicholas Higgins +// Definitions by: Pedro Casaubon , Alexander Leon , Nicholas Higgins // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface HowlerGlobal { diff --git a/types/httperr/httperr-tests.ts b/types/httperr/httperr-tests.ts index ee1f6d8567..db58b1a487 100644 --- a/types/httperr/httperr-tests.ts +++ b/types/httperr/httperr-tests.ts @@ -52,7 +52,7 @@ console.log(err instanceof Error); // true // ---------------------------------------- // Advanced usage: creating custom Error subclasses -var Custom404Error = httperr.createHttpError(404, 'Not Found', config => { +var Custom404Error = httperr.createHttpError(404, 'Not Found', function (config) { this.message = 'The resource was not found'; this['some custom property'] = config.parameters['some custom parameter']; }); diff --git a/types/icepick/icepick-tests.ts b/types/icepick/icepick-tests.ts index 5458509d42..f1d536e78f 100644 --- a/types/icepick/icepick-tests.ts +++ b/types/icepick/icepick-tests.ts @@ -1,5 +1,4 @@ import i = require("icepick"); -import * as _ from 'underscore'; "use strict"; // so attempted modifications of frozen objects will throw errors @@ -146,15 +145,13 @@ class Foo {} { i.map(function(v) { return v * 2 }, [1, 2, 3]); // [2, 4, 6] - var removeEvens = _.partial(i.filter, function(v: number) { return v % 2; }); - - removeEvens([1, 2, 3]); // [1, 3] + i.filter(function(v: number) { return v % 2 === 0; }, [1, 2, 3]); // [1, 3] } { var arr = i.freeze([{ a: 1 }, { b: 2 }]); //ECMAScript 2015 - //arr.find(function(item) { return item.b != null; }); // {b: 2} + //arr.find(function(item) { return item.b != null; }); // {b: 2} } // chain(coll) - not defined 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/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/ink-table/index.d.ts b/types/ink-table/index.d.ts new file mode 100644 index 0000000000..a225084f59 --- /dev/null +++ b/types/ink-table/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for ink-table 1.0 +// Project: https://github.com/maticzav/ink-table#readme +// Definitions by: Łukasz Ostrowski +// Definitions: https://github.com/DefinitelyTyped/ +// TypeScript Version: 2.8 + +import { InkComponent, InkNode, StatelessComponent } from 'ink'; + +export interface TableProps { + cell?: InkComponent; + data?: ReadonlyArray; + header?: InkComponent; + padding?: number; + skeleton?: InkComponent; +} + +export const Cell: StatelessComponent<{ children: InkNode }>; +export const Header: StatelessComponent<{ children: InkNode }>; +export const Skeleton: StatelessComponent<{ children: InkNode }>; + +declare const Table: StatelessComponent; + +export default Table; diff --git a/types/ink-table/ink-table-tests.tsx b/types/ink-table/ink-table-tests.tsx new file mode 100644 index 0000000000..53f3eb0c3b --- /dev/null +++ b/types/ink-table/ink-table-tests.tsx @@ -0,0 +1,45 @@ +/** @jsx h */ +import { h } from 'ink'; +import Table from 'ink-table'; + +const data = [ + { + name: 'Sosa Saunders', + gender: 'male', + age: 17, + email: 'sosa.saunders@mail.com', + phone: '+1 (809) 435-2786' + }, + { + name: 'Angelina Kirk', + gender: 'female', + age: 3, + email: 'angelina@kirk.io', + phone: '+1 (870) 567-3516' + }, + { + name: 'Bradford Rosales', + gender: 'male', + age: 20, + email: 'bradfordrosales@fast.com', + phone: '+1 (918) 573-3240' + }, + { + name: 'Gwen Schroeder', + gender: 'female', + age: 17, + email: 'gwen@corp.xyz', + phone: '+1 (987) 417-2062' + }, + { + name: 'Ellison Mann', + gender: 'male', + age: 5, + email: 'ellisonmann@katakana.com', + phone: '+1 (889) 411-2186' + } +]; + +const Basic = () => ( + +); diff --git a/types/ink-table/tsconfig.json b/types/ink-table/tsconfig.json new file mode 100644 index 0000000000..0bc43e3305 --- /dev/null +++ b/types/ink-table/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "jsx": "react", + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ink-table-tests.tsx" + ] +} diff --git a/types/p-pipe/tslint.json b/types/ink-table/tslint.json similarity index 100% rename from types/p-pipe/tslint.json rename to types/ink-table/tslint.json 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/ioredis/index.d.ts b/types/ioredis/index.d.ts index cbe5b0f8e2..99c99dcf04 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -30,7 +30,7 @@ interface RedisStatic { (port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; (options?: IORedis.RedisOptions): IORedis.Redis; - Cluster: IORedis.Cluster; + Cluster: IORedis.ClusterStatic; Command: IORedis.Command; } @@ -873,11 +873,16 @@ declare namespace IORedis { type ClusterNode = string | number | NodeConfiguration; + type NodeRole = 'master' | 'slave' | 'all'; + interface Cluster extends NodeJS.EventEmitter, Commander { - new(nodes: ClusterNode[], options?: ClusterOptions): Redis; connect(callback: () => void): Promise; disconnect(): void; - nodes(role: string): Redis[]; + nodes(role?: NodeRole): Redis[]; + } + + interface ClusterStatic extends NodeJS.EventEmitter, Commander { + new (nodes: ClusterNode[], options?: ClusterOptions): Cluster; } interface RedisOptions { diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index fdb1fafcc1..f3cafe1f18 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -207,3 +207,22 @@ new Redis.Cluster([], { new Redis.Cluster([], { clusterRetryStrategy: (times: number, reason?: Error) => 1 }); + +// Cluster types +const clusterOptions: Redis.ClusterOptions = {}; +const cluster = new Redis.Cluster( + [ + { + host: 'localhost', + port: 6379 + } + ], + clusterOptions +); +cluster.on('end', () => console.log('on end')); +cluster.nodes().map(node => { + node.pipeline() + .flushdb() + .exec() + .then(result => console.log(result)); +}); 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/wait-for-localhost/tslint.json b/types/is-natural-number/tslint.json similarity index 100% rename from types/wait-for-localhost/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-ajax/jasmine-ajax-tests.ts b/types/jasmine-ajax/jasmine-ajax-tests.ts index da68ad92a0..cf1db49f28 100644 --- a/types/jasmine-ajax/jasmine-ajax-tests.ts +++ b/types/jasmine-ajax/jasmine-ajax-tests.ts @@ -772,7 +772,7 @@ describe("Jasmine Mock Ajax (for toplevel)", () => { error = jasmine.createSpy("onFailure"); complete = jasmine.createSpy("onComplete"); - onreadystatechange = () => { + onreadystatechange = function() { if (this.readyState === (this.DONE || 4)) { // IE 8 doesn't support DONE if (this.status === 200) { success(this.responseText, this.textStatus, this); 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/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/jsdom/index.d.ts b/types/jsdom/index.d.ts index a4267d560e..b591ee3abb 100644 --- a/types/jsdom/index.d.ts +++ b/types/jsdom/index.d.ts @@ -41,7 +41,7 @@ export class JSDOM { * Behind the scenes, a jsdom Window is indeed a VM context. * To get access to this ability, use the runVMScript() method. */ - runVMScript(script: Script): void; + runVMScript(script: Script): any; reconfigure(settings: ReconfigureSettings): void; } 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/kafka-node/index.d.ts b/types/kafka-node/index.d.ts index 2f44a7e767..b90acfa762 100644 --- a/types/kafka-node/index.d.ts +++ b/types/kafka-node/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for kafka-node 2.0 // Project: https://github.com/SOHU-Co/kafka-node/ -// Definitions by: Daniel Imrie-Situnayake , Bill , Michael Haan , Amiram Korach +// Definitions by: Daniel Imrie-Situnayake +// Bill +// Michael Haan +// Amiram Korach +// Insanehong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -61,7 +65,7 @@ export class HighLevelConsumer { client: Client; on(eventName: "message", cb: (message: Message) => any): void; on(eventName: "error" | "offsetOutOfRange", cb: (error: any) => any): void; - on(eventName: "rebalancing" | "rebalanced", cb: () => any): void; + on(eventName: "rebalancing" | "rebalanced" | "connect", cb: () => any): void; addTopics(topics: string[] | Topic[], cb?: (error: any, added: string[] | Topic[]) => any): void; removeTopics(topics: string | string[], cb: (error: any, removed: number) => any): void; commit(cb: (error: any, data: any) => any): void; diff --git a/types/kafka-node/kafka-node-tests.ts b/types/kafka-node/kafka-node-tests.ts index 1e433172ae..0a8713aa27 100644 --- a/types/kafka-node/kafka-node-tests.ts +++ b/types/kafka-node/kafka-node-tests.ts @@ -244,6 +244,8 @@ consumerGroup.on('error', (err) => { }); consumerGroup.on('message', (msg) => { }); +consumerGroup.on('connect', () => { +}); consumerGroup.close(true, () => { }); diff --git a/types/kafkajs/index.d.ts b/types/kafkajs/index.d.ts new file mode 100644 index 0000000000..a28377e369 --- /dev/null +++ b/types/kafkajs/index.d.ts @@ -0,0 +1,538 @@ +// Type definitions for kafkajs 1.4 +// Project: https://github.com/tulios/kafkajs +// Definitions by: Michal Kaminski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +/// + +import * as tls from "tls"; + +export class Kafka { + constructor(options: KafkaOptions); + + producer(options?: ProducerOptions): Producer; + consumer(options?: ConsumerOptions): Consumer; + admin(options?: AdminOptions): Admin; +} + +export const PartitionAssigners: { + roundRobin: PartitionAssigner; +}; + +export namespace AssignerProtocol { + interface MemberMetadataOptions { + version: number; + topics: string[]; + userData?: Buffer; + } + + interface MemberMetadata { + encode(options: MemberMetadataOptions): Buffer; + decode(buffer: Buffer): MemberMetadataOptions; + } + + interface MemberAssignmentOptions { + version: number; + assignment: { [key: string]: number[] }; + userData?: Buffer; + } + + interface MemberAssignment { + encode(options: MemberAssignmentOptions): Buffer; + decode(buffer: Buffer): MemberAssignmentOptions; + } + + interface AssignerProtocolStatic { + MemberMetadata: MemberMetadata; + MemberAssignment: MemberAssignment; + } +} + +export const AssignerProtocol: AssignerProtocol.AssignerProtocolStatic; + +export enum CompressionTypes { + None = 0, + GZIP = 1, + Snappy = 2, + LZ4 = 3, + ZSTD = 4 +} + +export const CompressionCodecs: { [key in CompressionTypes]: () => any }; + +export enum ResourceTypes { + UNKNOWN = 0, + ANY = 1, + TOPIC = 2, + GROUP = 3, + CLUSTER = 4, + TRANSACTIONAL_ID = 5, + DELEGATION_TOKEN = 6 +} + +export interface KafkaOptions { + clientId?: string; + brokers: string[]; + ssl?: tls.ConnectionOptions; + sasl?: SASLOptions; + connectionTimeout?: number; + requestTimeout?: number; + retry?: RetryOptions; + logLevel?: logLevel; +} + +export interface SASLOptions { + mechanism: "plain" | "scram-sha-256" | "scram-sha-512"; + username: string; + password: string; +} + +export interface RetryOptions { + maxRetryTime?: number; + initialRetryTime?: number; + factor?: number; + multiplier?: number; + retries?: number; + maxInFlightRequests?: number | null; +} + +export enum logLevel { + NOTHING = 0, + ERROR = 1, + WARN = 2, + INFO = 4, + DEBUG = 5 +} + +export interface Producer { + connect(): Promise; + disconnect(): Promise; + + send(payload: MessagePayload): Promise; + sendBatch(payload: MessageBatchPayload): Promise; + + transaction(): Promise; + + events: ProducerEvents; + on( + event: ProducerEvents[keyof ProducerEvents], + cb: (e: InstrumentationEvent) => void + ): () => Producer; +} + +export interface ProducerOptions { + createPartitioner?: () => (options: { + topic: string; + partitionMetadata: PartitionMetadata[]; + message: ProducerMessage; + }) => number; + retry?: RetryOptions; + metadataMaxAge?: number; + allowAutoTopicCreation?: boolean; + transactionTimeout?: number; + idempotent?: boolean; +} + +export interface PartitionerPartitionMetadata { + partitionId: number; + leader: number; +} + +export interface PartitionMetadata { + partitionId: number; + leader: number; + partitionErrorCode?: number; + replicas?: number[]; + isr?: number[]; +} + +export interface MessagePayloadBase { + acks?: AcksBehaviour; + timeout?: number; + compression?: CompressionTypes; +} + +export interface MessagePayload extends MessagePayloadBase { + topic: string; + messages: ProducerMessage[]; + transactionTimeout?: number; + idempotent?: boolean; +} + +export interface MessageBatchPayload extends MessagePayloadBase { + topicMessages: ProducerTopicMessage[]; +} + +export interface ProducerMessage { + partition?: number; + key?: string; + value: string | Buffer | ArrayBuffer; + headers?: { [key: string]: string }; +} + +export interface ProducerTopicMessage { + topic: string; + messages: ProducerMessage[]; +} + +export enum AcksBehaviour { + All = -1, + No = 0, + Leader = 1 +} + +export interface Transaction { + send(payload: MessagePayload): Promise; + sendBatch(payload: MessageBatchPayload): Promise; + + sendOffsets(offsets: TransactionSendOffsets): Promise; + + commit(): Promise; + abort(): Promise; +} + +export interface TransactionSendOffsets { + consumerGroupId: string; + topics: TransactionSendOffsetsTopic[]; +} + +export interface TransactionSendOffsetsTopic { + topic: string; + partitions: TransactionSendOffsetsTopicPartitions[]; +} + +export interface TransactionSendOffsetsTopicPartitions { + partition: number; + offset: string; +} + +export interface Consumer { + connect(): Promise; + disconnect(): Promise; + + subscribe(options: ConsumerSubscribeOptions): Promise; + + run(options: ConsumerRunOptions): Promise; + + pause(topics: Array<{ topic: string }>): void; + resume(topics: Array<{ topic: string }>): void; + seek(options: ConsumerSeekOptions): void; + + describeGroup(): Promise; + + events: ConsumerEvents; + on( + event: ConsumerEvents[keyof ConsumerEvents], + cb: (e: InstrumentationEvent) => void + ): () => Consumer; +} + +export interface ConsumerOptions { + groupId: string; + partitionAssigners?: PartitionAssigner[]; + sessionTimeout?: number; + heartbeatInterval?: number; + metadataMaxAge?: number; + allowAutoTopicCreation?: boolean; + maxBytesPerPartition?: number; + minBytes?: number; + maxBytes?: number; + maxWaitTimeInMs?: number; + retry?: RetryOptions; + readUncommitted?: boolean; +} + +export interface PartitionAssigner { + ({ cluster }: { cluster: any /* TODO */ }): { + name: string; + version: number; + assign: (options: { + members: Array<{ memberId: string }>; + topics: any[]; + userData?: Buffer; + }) => Promise< + Array<{ + memberId: number; + memberAssignment: Buffer; + }> + >; + protocol?: (options: { + topics: any /* TODO */; + }) => { name: string; metadata: Buffer }; + }; +} + +export interface ConsumerRunOptions { + eachMessage?: (payload: ConsumerEachMessagePayload) => Promise; + eachBatch?: (payload: ConsumerEachBatchPayload) => Promise; + eachBatchAutoResolve?: boolean; + autoCommitInterval?: number; + autoCommitThreshold?: number; + autoCommit?: boolean; +} + +export interface ConsumerSubscribeOptions { + topic: string; + fromBeginning?: boolean; +} + +export interface ConsumerMessage { + timestamp: number; + key: string; + value: Buffer; + headers: { [key: string]: string }; + offset: number; +} + +export interface ConsumerBatch { + topic: string; + partition: number; + highWatermark: number; + messages: ConsumerMessage[]; +} + +export interface ConsumerEachMessagePayload { + topic: string; + partition: number; + message: ConsumerMessage; +} + +export interface ConsumerEachBatchPayload { + batch: ConsumerBatch; + resolveOffset: (offset: number) => Promise; + heartbeat: () => Promise; + isRunning: () => boolean; + commitOffsetsIfNecessary: ( + offsets?: OffsetsByTopicPartition + ) => Promise; + uncommittedOffsets: () => OffsetsByTopicPartition; +} + +export interface OffsetsByTopicPartition { + topics: TopicOffsets[]; +} + +export interface TopicOffsets { + partitions: PartitionOffset[]; +} + +export interface PartitionOffset { + partition: string; + offset: string; +} + +export interface ConsumerSeekOptions { + topic: string; + partition: number; + offset: number; +} + +export interface GroupMemberMetadata { + memberId: string; + clientId: string; + clientHost: string; + memberMetadata: Buffer; + memberAssignment: Buffer; +} + +export interface GroupMetadata { + errorCode: number; + groupId: string; + protocolType: string; + protocol: string; + members: GroupMemberMetadata[]; + state: string; +} + +export interface Admin { + connect(): Promise; + disconnect(): Promise; + + createTopics(options: AdminCreateTopicsOptions): Promise; + deleteTopics(options: AdminDeleteTopicsOptions): Promise; + getTopicMetadata(options: { + topics?: string[]; + }): Promise<{ topics: TopicMetadata[] }>; + + fetchOffsets( + options: AdminFetchOffsetsOptions + ): Promise; + resetOffsets(options: AdminResetOffsetsOptions): Promise; + setOffsets(options: AdminSetOffsetsOptions): Promise; + + describeConfigs( + options: AdminDescribeConfigsOptions + ): Promise; + alterConfigs(options: AdminAlterConfigsOptions): Promise; + + events: AdminEvents; + on( + event: AdminEvents[keyof AdminEvents], + cb: (e: InstrumentationEvent) => void + ): () => Admin; +} + +export interface AdminOptions { + retry?: RetryOptions; +} + +export interface AdminCreateTopicsOptions { + validateOnly?: boolean; + waitForLeaders?: boolean; + timeout?: number; + topics: AdminTopic[]; +} + +export interface AdminTopic { + topic: string; + numPartitions?: number; + replicationFactor?: number; + replicaAssignment?: AdminTopicReplicaAssignment[]; + configEntries?: AdminTopicConfigEntry[]; +} + +export interface AdminTopicReplicaAssignment { + partition: number; + replicas: number[]; +} + +export interface AdminTopicConfigEntry { + name: string; + value: string; +} + +export interface AdminDeleteTopicsOptions { + timeout?: number; + topics: string[]; +} + +export interface AdminFetchOffsetsOptions { + groupId: string; + topic: string; +} + +export interface AdminResetOffsetsOptions { + groupId: string; + topic: string; + earliest?: boolean; +} + +export interface TopicMetadata { + name: string; + partitions: PartitionMetadata[]; +} + +export interface AdminDescribeConfigsOptions { + resources: ResourceConfigQuery[]; +} + +export interface ResourceConfigQuery { + type: ResourceTypes; + name: string; + configNames?: string[]; +} + +export interface AdminConfigDescription { + resources: AdminConfigDescriptionResource[]; + throttleTime: number; +} + +export interface AdminConfigDescriptionResource { + configEntries: AdminConfigDescriptionResourceConfigEntry[]; + errorCode: number; + errorMessage: string; + resourceName: string; + resourceType: ResourceTypes; +} + +export interface AdminConfigDescriptionResourceConfigEntry { + configName: string; + configValue: string; + isDefault: boolean; + isSensitive: boolean; + readOnly: boolean; +} + +export interface AdminAlterConfigsOptions { + validateOnly: boolean; + resources: ResourceConfigQuery[]; +} + +export interface ResourceConfigQuery { + type: ResourceTypes; + name: string; + configEntries: ResourceConfigEntry[]; +} + +export interface ResourceConfigEntry { + name: string; + value: string; +} + +export interface AdminAlterConfigReturn { + resources: AdminAlterConfigResource[]; + throttleTime: number; +} + +export interface AdminAlterConfigResource { + errorCode: number; + errorMessage: string; + resourceName: string; + resourceType: ResourceTypes; +} + +export interface AdminTopicOffset { + partition: number; + offset: string; +} + +export interface AdminSetOffsetsSeekEntry { + partition: number; + offset: string; +} + +export interface AdminSetOffsetsOptions { + groupId: string; + topic: string; + partitions: AdminSetOffsetsSeekEntry[]; +} + +export interface InstrumentationEvent { + id: number; + type: string; + timestamp: number; + payload: { [key: string]: any }; +} + +export interface ConsumerEvents { + HEARTBEAT: "consumer.heartbeat"; + COMMIT_OFFSETS: "consumer.commit_offsets"; + GROUP_JOIN: "consumer.group_join"; + FETCH: "consumer.fetch"; + START_BATCH_PROCESS: "consumer.start_batch_process"; + END_BATCH_PROCESS: "consumner.end_batch_process"; + CONNECT: "consumer.connect"; + DISCONNECT: "consumer.disconnect"; + STOP: "consumer.stop"; + CRASH: "consumer.crash"; + REQUEST: "consumer.request"; + REQUEST_TIMEOUT: "consumer.request_timeout"; + REQUEST_QUEUE_SIZE: "consumer.request_queue_size"; +} + +export interface ProducerEvents { + CONNECT: "producer.connect"; + DISCONNECT: "producer.disconnect"; + REQUEST: "producer.request"; + REQUEST_TIMEOUT: "producer.request_timeout"; + REQUEST_QUEUE_SIZE: "producer.request_queue_size"; +} + +export interface AdminEvents { + CONNECT: "admin.connect"; + DISCONNECT: "admin.disconnect"; + REQUEST: "admin.request"; + REQUEST_TIMEOUT: "admin.request_timeout"; + REQUEST_QUEUE_SIZE: "admin.request_queue_size"; +} diff --git a/types/kafkajs/kafkajs-tests.ts b/types/kafkajs/kafkajs-tests.ts new file mode 100644 index 0000000000..3ae0f37c2c --- /dev/null +++ b/types/kafkajs/kafkajs-tests.ts @@ -0,0 +1,145 @@ +import * as fs from "fs"; + +import { + Kafka, + AssignerProtocol, + PartitionAssigners, + logLevel, + CompressionTypes, + CompressionCodecs, + ResourceTypes, + PartitionAssigner +} from "kafkajs"; + +const { MemberMetadata, MemberAssignment } = AssignerProtocol; +const { roundRobin } = PartitionAssigners; + +// COMMON +const host = "localhost"; +const topic = "topic-test"; + +const kafka = new Kafka({ + logLevel: logLevel.INFO, + brokers: [`${host}:9094`, `${host}:9097`, `${host}:9100`], + clientId: "example-consumer", + ssl: { + servername: "localhost", + rejectUnauthorized: false, + ca: [fs.readFileSync("./testHelpers/certs/cert-signed", "utf-8")] + }, + sasl: { + mechanism: "plain", + username: "test", + password: "testtest" + } +}); + +// CONSUMER +const consumer = kafka.consumer({ groupId: "test-group" }); + +const runConsumer = async () => { + await consumer.connect(); + await consumer.subscribe({ topic }); + await consumer.run({ + // eachBatch: async ({ batch }) => { + // console.log(batch) + // }, + eachMessage: async ({ topic, partition, message }) => { + const prefix = `${topic}[${partition} | ${message.offset}] / ${ + message.timestamp + }`; + console.log(`- ${prefix} ${message.key}#${message.value}`); + } + }); + await consumer.disconnect(); +}; + +runConsumer().catch(e => console.error(`[example/consumer] ${e.message}`, e)); + +// PRODUCER +const producer = kafka.producer({ allowAutoTopicCreation: true }); + +const getRandomNumber = () => Math.round(Math.random() * 1000); +const createMessage = (num: number) => ({ + key: `key-${num}`, + value: `value-${num}-${new Date().toISOString()}` +}); + +const sendMessage = () => { + return producer + .send({ + topic, + compression: CompressionTypes.GZIP, + messages: Array(getRandomNumber()) + .fill(0) + .map(_ => createMessage(getRandomNumber())) + }) + .then(console.log) + .catch(e => console.error(`[example/producer] ${e.message}`, e)); +}; + +const runProducer = async () => { + await producer.connect(); + setInterval(sendMessage, 3000); + await producer.disconnect(); +}; + +runProducer().catch(e => console.error(`[example/producer] ${e.message}`, e)); + +// ADMIN +const admin = kafka.admin({ retry: { retries: 10 } }); + +const runAdmin = async () => { + await admin.connect(); + const { topics } = await admin.getTopicMetadata({}); + await admin.createTopics({ topics: [{ topic, numPartitions: 10, replicationFactor: 1}], timeout: 30000, waitForLeaders: true }); + await admin.disconnect(); +}; + +runAdmin().catch(e => console.error(`[example/admin] ${e.message}`, e)); + +// OTHERS +async () => { + await producer.send({ + topic: "topic-name", + compression: CompressionTypes.GZIP, + messages: [{ key: "key1", value: "hello world!" }] + }); +}; + +// import SnappyCodec from "kafkajs-snappy"; +const SnappyCodec: any = undefined; +CompressionCodecs[CompressionTypes.Snappy] = SnappyCodec; + +const myCustomAssignmentArray = [0]; +const assignment: { [key: number]: { [key: string]: number[] } } = { + 0: { a: [0] } +}; +const MyPartitionAssigner: PartitionAssigner = ({ cluster: any }) => ({ + name: "MyPartitionAssigner", + version: 1, + async assign({ members, topics }) { + // perform assignment + return myCustomAssignmentArray.map(memberId => ({ + memberId, + memberAssignment: MemberAssignment.encode({ + version: this.version, + assignment: assignment[memberId] + }) + })); + }, + protocol({ topics }) { + return { + name: this.name, + metadata: MemberMetadata.encode({ + version: this.version, + topics + }) + }; + } +}); + +kafka.consumer({ + groupId: "my-group", + partitionAssigners: [MyPartitionAssigner, roundRobin] +}); diff --git a/types/p-map/tsconfig.json b/types/kafkajs/tsconfig.json similarity index 76% rename from types/p-map/tsconfig.json rename to types/kafkajs/tsconfig.json index ed62309b29..1cab3080d1 100644 --- a/types/p-map/tsconfig.json +++ b/types/kafkajs/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" + "kafkajs-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/kafkajs/tslint.json b/types/kafkajs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/kafkajs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/klaw/v1/klaw-tests.ts b/types/klaw/v1/klaw-tests.ts index 7bfd79ee50..eb9a101017 100644 --- a/types/klaw/v1/klaw-tests.ts +++ b/types/klaw/v1/klaw-tests.ts @@ -16,7 +16,7 @@ klaw('/some/dir') // README.md: Streams 2 & 3 (pull) with error handling klaw('/some/dir') - .on('readable', () => { + .on('readable', function() { while (true) { const item = this.read(); if (!item) break; diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 8b173c0887..1ff232e4a7 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -173,7 +173,7 @@ knex.select('title', 'author', 'year').from('books'); knex.select({ name: 'title', writer: 'author' }).from(knex.raw('books')); knex.select().table('books'); -knex.avg('sum_column1').from(() => { +knex.avg('sum_column1').from(function() { this.sum('column1 as sum_column1').from('t1').groupBy('column1').as('t1'); }).as('ignored_alias'); @@ -190,7 +190,7 @@ knex('users').where({ knex('users').where('id', 1); -knex('users').where(() => { +knex('users').where(function() { this.where('id', 1).orWhere('id', '>', 10); }).orWhere({name: 'Tester'}); @@ -218,7 +218,7 @@ knex.select('name').from('users') knex('users') .where('name', '=', 'John') - .orWhere(() => { + .orWhere(function() { this.where('votes', '>', 100).andWhere('title', '<>', 'Admin'); }); @@ -230,13 +230,13 @@ knex('users').whereNull('updated_at'); knex('users').whereNotNull('created_at'); -knex('users').whereExists(() => { +knex('users').whereExists(function() { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); knex('users').whereExists(knex.select('*').from('accounts').whereRaw('users.account_id = accounts.id')); -knex('users').whereNotExists(() => { +knex('users').whereNotExists(function() { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); @@ -321,15 +321,15 @@ knex('users') .join(knex('contacts').select('user_id', 'phone').as('contacts'), { 'users.id': 'contacts.user_id' }) .select('users.id', 'contacts.phone'); -knex.select('*').from('users').join(knex('accounts').select('id', 'owner_id').as('accounts'), () => { +knex.select('*').from('users').join(knex('accounts').select('id', 'owner_id').as('accounts'), function() { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); -knex.select('*').from('users').join('accounts', () => { +knex.select('*').from('users').join('accounts', function() { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); -knex.select('*').from('users').join('accounts', (join: Knex.JoinClause) => { +knex.select('*').from('users').join('accounts', function(join: Knex.JoinClause) { if (this !== join) { throw new Error("join() callback call semantics wrong"); } @@ -337,120 +337,120 @@ knex.select('*').from('users').join('accounts', (join: Knex.JoinClause) => { join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); -knex.select('*').from('user').join('contacts', () => { +knex.select('*').from('user').join('contacts', function() { this.on('users.id', '=', knex.raw(7)); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').onIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').andOnIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').orOnIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').onNotIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').andOnNotIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').orOnNotIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').onNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').andOnNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').orOnNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').onNotNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').andOnNotNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').orOnNotNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', () => { - this.on('users.id', '=', 'contacts.id').onExists(() => { +knex.select('*').from('users').join('contacts', function() { + this.on('users.id', '=', 'contacts.id').onExists(function() { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', () => { - this.on('users.id', '=', 'contacts.id').andOnExists(() => { +knex.select('*').from('users').join('contacts', function() { + this.on('users.id', '=', 'contacts.id').andOnExists(function() { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', () => { - this.on('users.id', '=', 'contacts.id').orOnExists(() => { +knex.select('*').from('users').join('contacts', function() { + this.on('users.id', '=', 'contacts.id').orOnExists(function() { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', () => { - this.on('users.id', '=', 'contacts.id').onNotExists(() => { +knex.select('*').from('users').join('contacts', function() { + this.on('users.id', '=', 'contacts.id').onNotExists(function() { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', () => { - this.on('users.id', '=', 'contacts.id').andOnNotExists(() => { +knex.select('*').from('users').join('contacts', function() { + this.on('users.id', '=', 'contacts.id').andOnNotExists(function() { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', () => { - this.on('users.id', '=', 'contacts.id').orOnNotExists(() => { +knex.select('*').from('users').join('contacts', function() { + this.on('users.id', '=', 'contacts.id').orOnNotExists(function() { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').onBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').andOnBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').orOnBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').onNotBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').andOnNotBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', () => { +knex.select('*').from('users').join('contacts', function() { this.on('users.id', '=', 'contacts.id').orOnNotBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', () => { - this.on('users.id', '=', 'contacts.id').onNotExists(() => { +knex.select('*').from('users').join('contacts', function() { + this.on('users.id', '=', 'contacts.id').onNotExists(function() { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); @@ -475,7 +475,7 @@ knex.from('users').innerJoin('accounts', 'users.id', 'accounts.user_id'); knex.table('users').innerJoin('accounts', 'users.id', '=', 'accounts.user_id'); -knex('users').innerJoin('accounts', () => { +knex('users').innerJoin('accounts', function() { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -485,7 +485,7 @@ knex('users').innerJoin('accounts', (join: Knex.JoinClause) => { knex.select('*').from('users').leftJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').leftJoin('accounts', () => { +knex.select('*').from('users').leftJoin('accounts', function() { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -502,13 +502,13 @@ knex.select('*').from('users').leftJoin('accounts', (join) => { knex.select('*').from('users').leftOuterJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').leftOuterJoin('accounts', () => { +knex.select('*').from('users').leftOuterJoin('accounts', function() { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); knex.select('*').from('users').rightJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').rightJoin('accounts', () => { +knex.select('*').from('users').rightJoin('accounts', function() { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -518,13 +518,13 @@ knex.select('*').from('users').rightJoin('accounts', (join: Knex.JoinClause) => knex.select('*').from('users').rightOuterJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').rightOuterJoin('accounts', () => { +knex.select('*').from('users').rightOuterJoin('accounts', function() { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); knex.select('*').from('users').outerJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').outerJoin('accounts', () => { +knex.select('*').from('users').outerJoin('accounts', function() { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -534,7 +534,7 @@ knex.select('*').from('users').outerJoin('accounts', (join: Knex.JoinClause) => knex.select('*').from('users').fullOuterJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').fullOuterJoin('accounts', () => { +knex.select('*').from('users').fullOuterJoin('accounts', function() { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -549,39 +549,39 @@ knex.select('*').from('accounts').joinRaw('natural full join table1').where('id' knex.select('*').from('accounts').join(knex.raw('natural full join table1')).where('id', 1); knex.select('*').from('accounts') - .join(() => { + .join(function() { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .leftJoin(() => { + .leftJoin(function() { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .leftOuterJoin(() => { + .leftOuterJoin(function() { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .rightJoin(() => { + .rightJoin(function() { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .rightOuterJoin(() => { + .rightOuterJoin(function() { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .innerJoin(() => { + .innerJoin(function() { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .crossJoin(() => { + .crossJoin(function() { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .fullOuterJoin(() => { + .fullOuterJoin(function() { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .outerJoin(() => { + .outerJoin(function() { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); @@ -1044,66 +1044,66 @@ knex.select('*').from('users').where(knex.raw('id = ?', [1])).toSQL(); // knex('users') .select('*') - .join('contacts', (builder) => { - this.on((builder: any) => { + .join('contacts', function(builder) { + this.on(function(builder: any) { let self: Knex.JoinClause = this; self = builder; - }).andOn((builder: any) => { + }).andOn(function(builder: any) { let self: Knex.JoinClause = this; self = builder; - }).orOn((builder: any) => { + }).orOn(function(builder: any) { let self: Knex.JoinClause = this; self = builder; - }).onExists((builder: any) => { + }).onExists(function(builder: any) { let self: Knex.QueryBuilder = this; self = builder; - }).orOnExists((builder: any) => { + }).orOnExists(function(builder: any) { let self: Knex.QueryBuilder = this; self = builder; - }).andOnExists((builder: any) => { + }).andOnExists(function(builder: any) { let self: Knex.QueryBuilder = this; self = builder; - }).onNotExists((builder: any) => { + }).onNotExists(function(builder: any) { let self: Knex.QueryBuilder = this; self = builder; - }).andOnNotExists((builder: any) => { + }).andOnNotExists(function(builder: any) { let self: Knex.QueryBuilder = this; self = builder; - }).orOnNotExists((builder: any) => { + }).orOnNotExists(function(builder: any) { let self: Knex.QueryBuilder = this; self = builder; }); - }).where((builder) => { + }).where(function(builder) { let self: Knex.QueryBuilder = this; self = builder; - }).orWhere((builder) => { + }).orWhere(function(builder) { let self: Knex.QueryBuilder = this; self = builder; - }).andWhere((builder) => { + }).andWhere(function(builder) { let self: Knex.QueryBuilder = this; self = builder; - }).whereIn('column', (builder) => { + }).whereIn('column', function(builder) { let self: Knex.QueryBuilder = this; self = builder; - }).orWhereIn('column', (builder) => { + }).orWhereIn('column', function(builder) { let self: Knex.QueryBuilder = this; self = builder; - }).whereNotIn('column', (builder) => { + }).whereNotIn('column', function(builder) { let self: Knex.QueryBuilder = this; self = builder; - }).orWhereNotIn('column', (builder) => { + }).orWhereNotIn('column', function(builder) { let self: Knex.QueryBuilder = this; self = builder; - }).whereWrapped((builder) => { + }).whereWrapped(function(builder) { let self: Knex.QueryBuilder = this; self = builder; - }).union((builder) => { + }).union(function(builder) { let self: Knex.QueryBuilder = this; self = builder; - }).unionAll((builder) => { + }).unionAll(function(builder) { let self: Knex.QueryBuilder = this; self = builder; - }).modify((builder, aBool) => { + }).modify(function(builder, aBool) { let self: Knex.QueryBuilder = this; self = builder; }, true); @@ -1111,6 +1111,7 @@ knex('users') // // Migrations // +const name = "test"; const config = { directory: "./migrations", extension: "js", @@ -1196,12 +1197,12 @@ knex('characters') knex('characters') .select() - .whereIn('name', () => { + .whereIn('name', function() { this.select('name').from('characters'); }); knex('characters') .select() - .whereIn(['name', 'class'], () => { + .whereIn(['name', 'class'], function() { this.select('name', 'class').from('characters'); }); 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-mount/koa-mount-tests.ts b/types/koa-mount/koa-mount-tests.ts index 139e08a3d8..00ff57986d 100644 --- a/types/koa-mount/koa-mount-tests.ts +++ b/types/koa-mount/koa-mount-tests.ts @@ -3,13 +3,13 @@ import mount = require("koa-mount"); const a = new Koa(); -a.use((next) => { +a.use(function(next) { this.body = "Hello"; }); const b = new Koa(); -b.use((next) => { +b.use(function(next) { this.body = "World"; }); 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/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/lru-cache/v4/tsconfig.json b/types/lru-cache/v4/tsconfig.json new file mode 100644 index 0000000000..153f9c56aa --- /dev/null +++ b/types/lru-cache/v4/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "lru-cache": ["lru-cache/v4"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.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/mailparser/index.d.ts b/types/mailparser/index.d.ts index 181bb452a0..0b6e040af5 100644 --- a/types/mailparser/index.d.ts +++ b/types/mailparser/index.d.ts @@ -1,7 +1,7 @@ -// Type definitions for mailparser v2.0.0 -// Project: https://www.npmjs.com/package/mailparser +// Type definitions for mailparser 2.4 +// Project: https://github.com/nodemailer/mailparser // Definitions by: Peter Snider -// Andrey Volynkin +// Andrey Volynkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -289,6 +289,13 @@ export class MailParser extends StreamModule.Transform { */ export type Source = Buffer | Stream | string; +/** + * Options object for simpleParser. + */ +export interface SimpleParserOptions extends StreamModule.TransformOptions { + keepCidLinks?: boolean; +} + /** * Parse email message to structure object. * @@ -301,5 +308,16 @@ export function simpleParser(source: Source, callback: (err: any, mail: ParsedMa * Parse email message to structure object. * * @param source A message source. + * @param options Transform options passed to MailParser's constructor + * @param callback Function to get a structured email object. */ -export function simpleParser(source: Source): Promise; +export function simpleParser(source: Source, options: SimpleParserOptions, callback: (err: any, mail: ParsedMail) => void): void; + + +/** + * Parse email message to structure object. + * + * @param source A message source. + * @param options Transform options passed to MailParser's constructor + */ +export function simpleParser(source: Source, options?: SimpleParserOptions): Promise; diff --git a/types/mailparser/mailparser-tests.ts b/types/mailparser/mailparser-tests.ts index 19c92814aa..cda949a213 100644 --- a/types/mailparser/mailparser-tests.ts +++ b/types/mailparser/mailparser-tests.ts @@ -36,10 +36,16 @@ var sourceStream = fs.createReadStream('foo.eml'); simpleParser(sourceString, (err, mail) => err ? err : mail.html); simpleParser(sourceBuffer, (err, mail) => err ? err : mail.html); simpleParser(sourceStream, (err, mail) => err ? err : mail.html); +simpleParser(sourceString, { keepCidLinks: true }, (err, mail) => err ? err : mail.html); +simpleParser(sourceBuffer, { keepCidLinks: true }, (err, mail) => err ? err : mail.html); +simpleParser(sourceStream, { keepCidLinks: true }, (err, mail) => err ? err : mail.html); simpleParser(sourceString).then(mail => mail.html).catch(err => err); simpleParser(sourceBuffer).then(mail => mail.html).catch(err => err); simpleParser(sourceStream).then(mail => mail.html).catch(err => err); +simpleParser(sourceString, { keepCidLinks: true }).then(mail => mail.html).catch(err => err); +simpleParser(sourceBuffer, { keepCidLinks: true }).then(mail => mail.html).catch(err => err); +simpleParser(sourceStream, { keepCidLinks: true }).then(mail => mail.html).catch(err => err); simpleParser(sourceString, (err, mail) => { console.log(mail.headers.get('subject')); diff --git a/types/mailparser/tslint.json b/types/mailparser/tslint.json index a41bf5d19a..4cfa77fc40 100644 --- a/types/mailparser/tslint.json +++ b/types/mailparser/tslint.json @@ -7,7 +7,7 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, + "dt-header": true, "eofline": false, "export-just-namespace": false, "import-spacing": false, diff --git a/types/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/massive/index.d.ts b/types/massive/index.d.ts index 72ef7c117b..4e6a7abc26 100644 --- a/types/massive/index.d.ts +++ b/types/massive/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for massive 5.4 -// Project: https://github.com/dmfay/massive-js.git, https://dmfay.github.io/massive-js +// Project: https://massivejs.org, https://github.com/dmfay/massive-js.git, https://dmfay.github.io/massive-js // Definitions by: Pascal Birchler // Clarence Ho // Felix Faust 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/mongodb/index.d.ts b/types/mongodb/index.d.ts index 51393a8d25..3657a3a651 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -1,5 +1,6 @@ -// Type definitions for MongoDB v3.1 -// Project: https://github.com/mongodb/node-mongodb-native/tree/3.0.0 +// Type definitions for MongoDB 3.1 +// Project: https://github.com/mongodb/node-mongodb-native +// https://github.com/mongodb/node-mongodb-native/tree/3.1 // Definitions by: Federico Caselli // Alan Marcell // Jason Dreyzehner @@ -20,17 +21,18 @@ // Hector Ribes // Florian Richter // Erik Christensen +// Nick Zahn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Documentation : http://mongodb.github.io/node-mongodb-native/3.1/api/ +// Documentation: https://mongodb.github.io/node-mongodb-native/3.1/api/ /// -/// import { ObjectID, Timestamp } from 'bson'; import { EventEmitter } from 'events'; import { Readable, Writable } from "stream"; +import { checkServerIdentity } from "tls"; export function connect(uri: string, options?: MongoClientOptions): Promise; export function connect(uri: string, callback: MongoCallback): void; @@ -53,7 +55,7 @@ export class MongoClient extends EventEmitter { close(force?: boolean): Promise; close(force: boolean, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#db */ - db(dbName?: string, options?: MongoClientCommonOption): Db + db(dbName?: string, options?: MongoClientCommonOption): Db; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#isConnected */ isConnected(options?: MongoClientCommonOption): boolean; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#logout */ @@ -63,7 +65,7 @@ export class MongoClient extends EventEmitter { /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#startSession */ startSession(options?: SessionOptions): ClientSession; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#watch */ - watch(pipeline?: Object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream; + watch(pipeline?: object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#withSession */ withSession(operation: (session: ClientSession) => Promise): Promise; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#withSession */ @@ -78,37 +80,36 @@ export interface ClientSession extends EventEmitter { id: any; /** * Aborts the currently active transaction in this session. - * @param {MongoCallback} [cb] Optional callback for completion of this operation + * @param cb Optional callback for completion of this operation */ abortTransaction(cb?: MongoCallback): Promise; /** * Advances the operationTime for a ClientSession. - * @param {mongodb.Timestamp} operationTime */ advanceOperationTime(operamtionTime: Timestamp): void; /** * Commits the currently active transaction in this session. - * @param {MongoCallback} [cb] Optional callback for completion of this operation + * @param cb Optional callback for completion of this operation */ commitTransaction(cb?: MongoCallback): Promise; /** * Ends this session on the server - * @param {MongoCallback} [cb] Optional callback for completion of this operation + * @param cb Optional callback for completion of this operation */ endSession(cb?: MongoCallback): void; /** * Ends this session on the server - * @param {*} [options] Optional settings. Currently reserved for future use - * @param {MongoCallback} [cb] Optional callback for completion of this operation + * @param options Optional settings. Currently reserved for future use + * @param cb Optional callback for completion of this operation */ - endSession(options: any, cb?: MongoCallback): void + endSession(options: any, cb?: MongoCallback): void; /** * Used to determine if this session equals another * - * @param {ClientSession} session A class representing a client session on the server - * @returns {boolean} if the sessions are equal + * @param session A class representing a client session on the server + * @returns Whether the sessions are equal */ equals(session: ClientSession): boolean; @@ -116,14 +117,12 @@ export interface ClientSession extends EventEmitter { incrementTransactionNumber(): void; /** - * @returns {boolean} this session is currently in a transaction or not + * @returns Whether this session is currently in a transaction or not */ inTransaction(): boolean; /** * Starts a new transaction with the given options. - * @param {TransactionOptions} options - * @memberof ClientSession */ startTransaction(options?: TransactionOptions): void; @@ -150,19 +149,17 @@ interface WriteConcern { /** * requests acknowledgement that the write operation has * propagated to a specified number of mongod hosts - * @type {(number | 'majority' | string)} default 1 + * @default 1 */ w?: number | 'majority' | string; /** * requests acknowledgement from MongoDB that the write operation has * been written to the journal - * @type {boolean} default false + * @default false */ j?: boolean; /** * a time limit, in milliseconds, for the write concern - * @type {number} - * @memberof WriteConcern */ wtimeout?: number; } @@ -174,7 +171,7 @@ interface WriteConcern { export interface SessionOptions { /** * Whether causal consistency should be enabled on this session - * @type {boolean} default true + * @default true */ causalConsistency?: boolean; /** @@ -207,7 +204,7 @@ export interface MongoCallback { /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoError.html */ export class MongoError extends Error { constructor(message: string); - static create(options: Object): MongoError; + static create(options: object): MongoError; code?: number; /** * While not documented, the 'errmsg' prop is AFAIK the only way to find out @@ -248,13 +245,13 @@ export interface MongoClientOptions extends /** * Custom logger object */ - logger?: Object | log; + logger?: object | log; /** * Validate MongoClient passed in options for correctness. * Default: false */ - validateOptions?: Object; + validateOptions?: object; /** * The name of the application that created this MongoClient instance. @@ -314,7 +311,7 @@ export interface SSLOptions { /** * Default: true; Server identity checking during SSL */ - checkServerIdentity?: boolean | Function; + checkServerIdentity?: boolean | typeof checkServerIdentity; /** * Array of valid certificates either as Buffers or Strings */ @@ -358,7 +355,7 @@ export interface HighAvailabilityOptions { // See http://mongodb.github.io/node-mongodb-native/3.1/api/ReadPreference.html export class ReadPreference { - constructor(mode: string, tags: Object); + constructor(mode: string, tags: object); mode: string; tags: any; options: { @@ -417,18 +414,18 @@ export interface DbCreateOptions extends CommonOptions { /** * Default: true; Promotes BSON values to native types where possible, set to false to only receive wrapper types. */ - promoteValues?: Object; + promoteValues?: boolean; /** * Custom primary key factory to generate _id values (see Custom primary keys). */ - pkFactory?: Object; + pkFactory?: object; /** * ES6 compatible promise constructor */ - promiseLibrary?: Object; + promiseLibrary?: object; /** * https://docs.mongodb.com/manual/reference/read-concern/#read-concern - **/ + */ readConcern?: ReadConcern; /** * Sets a cap on how many operations the driver will buffer up before giving up on getting a @@ -485,7 +482,7 @@ export interface ServerOptions extends SSLOptions { /** * Default: true; */ - monitoring?: boolean + monitoring?: boolean; /** * Socket Options @@ -558,20 +555,20 @@ export class Db extends EventEmitter { collection(name: string, callback: MongoCallback>): Collection; collection(name: string, options: DbCollectionOptions, callback: MongoCallback>): Collection; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collections */ - collections(): Promise[]>; - collections(callback: MongoCallback[]>): void; + collections(): Promise>>; + collections(callback: MongoCallback>>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#command */ - command(command: Object, callback: MongoCallback): void; - command(command: Object, options?: { readPreference: ReadPreference | string }): Promise; - command(command: Object, options: { readPreference: ReadPreference | string }, callback: MongoCallback): void; + command(command: object, callback: MongoCallback): void; + command(command: object, options?: { readPreference: ReadPreference | string, session?: ClientSession }): Promise; + command(command: object, options: { readPreference: ReadPreference | string, session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection */ createCollection(name: string, callback: MongoCallback>): void; createCollection(name: string, options?: CollectionCreateOptions): Promise>; createCollection(name: string, options: CollectionCreateOptions, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createIndex */ - createIndex(name: string, fieldOrSpec: string | Object, callback: MongoCallback): void; - createIndex(name: string, fieldOrSpec: string | Object, options?: IndexOptions): Promise; - createIndex(name: string, fieldOrSpec: string | Object, options: IndexOptions, callback: MongoCallback): void; + createIndex(name: string, fieldOrSpec: string | object, callback: MongoCallback): void; + createIndex(name: string, fieldOrSpec: string | object, options?: IndexOptions): Promise; + createIndex(name: string, fieldOrSpec: string | object, options: IndexOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#dropCollection */ dropCollection(name: string): Promise; dropCollection(name: string, callback: MongoCallback): void; @@ -579,15 +576,15 @@ export class Db extends EventEmitter { dropDatabase(): Promise; dropDatabase(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#executeDbAdminCommand */ - executeDbAdminCommand(command: Object, callback: MongoCallback): void; - executeDbAdminCommand(command: Object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number }): Promise; - executeDbAdminCommand(command: Object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number }, callback: MongoCallback): void; + executeDbAdminCommand(command: object, callback: MongoCallback): void; + executeDbAdminCommand(command: object, options?: { readPreference?: ReadPreference | string, session?: ClientSession }): Promise; + executeDbAdminCommand(command: object, options: { readPreference?: ReadPreference | string, session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#indexInformation */ indexInformation(name: string, callback: MongoCallback): void; indexInformation(name: string, options?: { full?: boolean, readPreference?: ReadPreference | string }): Promise; indexInformation(name: string, options: { full?: boolean, readPreference?: ReadPreference | string }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#listCollections */ - listCollections(filter?: Object, options?: { nameOnly?: boolean, batchSize?: number, readPreference?: ReadPreference | string, session?: ClientSession }): CommandCursor; + listCollections(filter?: object, options?: { nameOnly?: boolean, batchSize?: number, readPreference?: ReadPreference | string, session?: ClientSession }): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#profilingInfo */ /** @deprecated Query the system.profile collection directly. */ profilingInfo(callback: MongoCallback): void; @@ -626,7 +623,7 @@ export interface CommonOptions extends WriteConcern { export class Server extends EventEmitter { constructor(host: string, port: number, options?: ServerOptions); - connections(): Array; + connections(): any[]; } /** @@ -634,9 +631,9 @@ export class Server extends EventEmitter { * @see http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html */ export class ReplSet extends EventEmitter { - constructor(servers: Array, options?: ReplSetOptions); + constructor(servers: Server[], options?: ReplSetOptions); - connections(): Array; + connections(): any[]; } /** @@ -644,9 +641,9 @@ export class ReplSet extends EventEmitter { * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Mongos.html */ export class Mongos extends EventEmitter { - constructor(servers: Array, options?: MongosOptions); + constructor(servers: Server[], options?: MongosOptions); - connections(): Array; + connections(): any[]; } /** @@ -654,14 +651,14 @@ export class Mongos extends EventEmitter { * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#addUser */ export interface DbAddUserOptions extends CommonOptions { - customData?: Object; - roles?: Object[]; + customData?: object; + roles?: object[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection */ export interface CollectionCreateOptions extends CommonOptions { raw?: boolean; - pkFactory?: Object; + pkFactory?: object; readPreference?: ReadPreference | string; serializeFunctions?: boolean; strict?: boolean; @@ -683,7 +680,7 @@ export interface CollectionCreateOptions extends CommonOptions { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collection */ export interface DbCollectionOptions extends CommonOptions { raw?: boolean; - pkFactory?: Object; + pkFactory?: object; readPreference?: ReadPreference | string; serializeFunctions?: boolean; strict?: boolean; @@ -736,7 +733,7 @@ export interface IndexOptions extends CommonOptions { */ partialFilterExpression?: any; collation?: CollationDocument; - default_language?: string + default_language?: string; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html */ @@ -749,9 +746,9 @@ export interface Admin { buildInfo(): Promise; buildInfo(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#command */ - command(command: Object, callback: MongoCallback): void; - command(command: Object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number }): Promise; - command(command: Object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number }, callback: MongoCallback): void; + command(command: object, callback: MongoCallback): void; + command(command: object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number }): Promise; + command(command: object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#listDatabases */ listDatabases(): Promise; listDatabases(callback: MongoCallback): void; @@ -773,20 +770,20 @@ export interface Admin { serverStatus(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#validateCollection */ validateCollection(collectionNme: string, callback: MongoCallback): void; - validateCollection(collectionNme: string, options?: Object): Promise; - validateCollection(collectionNme: string, options: Object, callback: MongoCallback): void; + validateCollection(collectionNme: string, options?: object): Promise; + validateCollection(collectionNme: string, options: object, callback: MongoCallback): void; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#addUser */ export interface AddUserOptions extends CommonOptions { fsync: boolean; - customData?: Object; - roles?: Object[] + customData?: object; + roles?: object[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#removeUser */ export interface FSyncOptions extends CommonOptions { - fsync?: boolean + fsync?: boolean; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html */ @@ -813,12 +810,12 @@ export interface Collection { hint: any; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#aggregate */ aggregate(callback: MongoCallback>): AggregationCursor; - aggregate(pipeline: Object[], callback: MongoCallback>): AggregationCursor; - aggregate(pipeline?: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback>): AggregationCursor; + aggregate(pipeline: object[], callback: MongoCallback>): AggregationCursor; + aggregate(pipeline?: object[], options?: CollectionAggregationOptions, callback?: MongoCallback>): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#bulkWrite */ - bulkWrite(operations: Object[], callback: MongoCallback): void; - bulkWrite(operations: Object[], options?: CollectionBulkWriteOptions): Promise; - bulkWrite(operations: Object[], options: CollectionBulkWriteOptions, callback: MongoCallback): void; + bulkWrite(operations: object[], callback: MongoCallback): void; + bulkWrite(operations: object[], options?: CollectionBulkWriteOptions): Promise; + bulkWrite(operations: object[], options: CollectionBulkWriteOptions, callback: MongoCallback): void; /** * http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#count * @deprecated Use countDocuments or estimatedDocumentCount @@ -882,9 +879,9 @@ export interface Collection { findOneAndDelete(filter: FilterQuery, options?: FindOneAndDeleteOption): Promise>; findOneAndDelete(filter: FilterQuery, options: FindOneAndDeleteOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndReplace */ - findOneAndReplace(filter: FilterQuery, replacement: Object, callback: MongoCallback>): void; - findOneAndReplace(filter: FilterQuery, replacement: Object, options?: FindOneAndReplaceOption): Promise>; - findOneAndReplace(filter: FilterQuery, replacement: Object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; + findOneAndReplace(filter: FilterQuery, replacement: object, callback: MongoCallback>): void; + findOneAndReplace(filter: FilterQuery, replacement: object, options?: FindOneAndReplaceOption): Promise>; + findOneAndReplace(filter: FilterQuery, replacement: object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate */ findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback>): void; findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, options?: FindOneAndUpdateOption): Promise>; @@ -893,14 +890,33 @@ export interface Collection { geoHaystackSearch(x: number, y: number, callback: MongoCallback): void; geoHaystackSearch(x: number, y: number, options?: GeoHaystackSearchOptions): Promise; geoHaystackSearch(x: number, y: number, options: GeoHaystackSearchOptions, callback: MongoCallback): void; - /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoNear */ - geoNear(x: number, y: number, callback: MongoCallback): void; - geoNear(x: number, y: number, options?: GeoNearOptions): Promise; - geoNear(x: number, y: number, options: GeoNearOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#group */ - group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, callback: MongoCallback): void; - group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options?: { readPreference?: ReadPreference | string }): Promise; - group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options: { readPreference?: ReadPreference | string }, callback: MongoCallback): void; + /** @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. */ + group(keys: object | any[] | Function | Code, condition: object, initial: object, reduce: Function | Code, finalize: Function | Code, command: boolean, callback: MongoCallback): void; + /** @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. */ + group( + keys: object | any[] | Function | Code, + condition: object, + initial: object, + reduce: Function | Code, + finalize: Function | Code, + command: boolean, + options?: { readPreference?: ReadPreference | string, session?: ClientSession } + ): Promise; + /** @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. */ + group( + keys: object | any[] | Function | Code, + condition: object, + initial: object, + reduce: Function | Code, + finalize: Function | Code, + command: boolean, + options: { + readPreference?: ReadPreference | string, + session?: ClientSession + }, + callback: MongoCallback + ): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#indexes */ indexes(options?: { session: ClientSession }): Promise; indexes(callback: MongoCallback): void; @@ -939,28 +955,28 @@ export interface Collection { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#listIndexes */ listIndexes(options?: { batchSize?: number, readPreference?: ReadPreference | string, session?: ClientSession }): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#mapReduce */ - mapReduce(map: Function | string, reduce: Function | string, callback: MongoCallback): void; - mapReduce(map: Function | string, reduce: Function | string, options?: MapReduceOptions): Promise; - mapReduce(map: Function | string, reduce: Function | string, options: MapReduceOptions, callback: MongoCallback): void; + mapReduce(map: CollectionMapFunction | string, reduce: CollectionReduceFunction | string, callback: MongoCallback): void; + mapReduce(map: CollectionMapFunction | string, reduce: CollectionReduceFunction | string, options?: MapReduceOptions): Promise; + mapReduce(map: CollectionMapFunction | string, reduce: CollectionReduceFunction | string, options: MapReduceOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#options */ options(options?: { session: ClientSession }): Promise; options(callback: MongoCallback): void; options(options: { session: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#parallelCollectionScan */ - parallelCollectionScan(callback: MongoCallback[]>): void; - parallelCollectionScan(options?: ParallelCollectionScanOptions): Promise[]>; - parallelCollectionScan(options: ParallelCollectionScanOptions, callback: MongoCallback[]>): void; + parallelCollectionScan(callback: MongoCallback>>): void; + parallelCollectionScan(options?: ParallelCollectionScanOptions): Promise>>; + parallelCollectionScan(options: ParallelCollectionScanOptions, callback: MongoCallback>>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#reIndex */ reIndex(options?: { session: ClientSession }): Promise; reIndex(callback: MongoCallback): void; reIndex(options: { session: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove */ /** @deprecated Use use deleteOne, deleteMany or bulkWrite */ - remove(selector: Object, callback: MongoCallback): void; + remove(selector: object, callback: MongoCallback): void; /** @deprecated Use use deleteOne, deleteMany or bulkWrite */ - remove(selector: Object, options?: CommonOptions & { single?: boolean }): Promise; + remove(selector: object, options?: CommonOptions & { single?: boolean }): Promise; /** @deprecated Use use deleteOne, deleteMany or bulkWrite */ - remove(selector: Object, options?: CommonOptions & { single?: boolean }, callback?: MongoCallback): void; + remove(selector: object, options?: CommonOptions & { single?: boolean }, callback?: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#rename */ rename(newName: string, callback: MongoCallback>): void; rename(newName: string, options?: { dropTarget?: boolean, session?: ClientSession }): Promise>; @@ -996,21 +1012,21 @@ export interface Collection { updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, options?: UpdateOneOptions): Promise; updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, options: UpdateOneOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#watch */ - watch(pipeline?: Object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream; + watch(pipeline?: object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream; } export type Condition = { $eq?: T[P]; $gt?: T[P]; $gte?: T[P]; - $in?: T[P][]; + $in?: Array; $lt?: T[P]; $lte?: T[P]; $ne?: T[P]; - $nin?: T[P][]; - $and?: (FilterQuery | T[P])[]; - $or?: (FilterQuery | T[P])[]; - $not?: (FilterQuery | T[P])[] | T[P]; + $nin?: Array; + $and?: Array | T[P]>; + $or?: Array | T[P]>; + $not?: Array | T[P]> | T[P]; $expr?: any; $jsonSchema?: any; $mod?: [number, number]; @@ -1022,17 +1038,17 @@ export type Condition = { $caseSensitive?: boolean; $diacraticSensitive?: boolean; }; - $where?: Object; - $geoIntersects?: Object; - $geoWithin?: Object; - $near?: Object; - $nearSphere?: Object; - $elemMatch?: Object; + $where?: object; + $geoIntersects?: object; + $geoWithin?: object; + $near?: object; + $nearSphere?: object; + $elemMatch?: object; $size?: number; - $bitsAllClear?: Object; - $bitsAllSet?: Object; - $bitsAnyClear?: Object; - $bitsAnySet?: Object; + $bitsAllClear?: object; + $bitsAllSet?: object; + $bitsAnyClear?: object; + $bitsAnySet?: object; [key: string]: any; }; @@ -1047,12 +1063,12 @@ export type UpdateQuery = { $unset?: { [P in keyof T]?: '' } | { [key: string]: '' }; $rename?: { [key: string]: keyof T } | { [key: string]: string }; $currentDate?: { [P in keyof T]?: (true | { $type: 'date' | 'timestamp' }) } | { [key: string]: (true | { $type: 'date' | 'timestamp' }) }; - $addToSet?: Partial | { [key: string]: any }; + $addToSet?: { [P in keyof T]?: any } | { [key: string]: any }; $pop?: { [P in keyof T]?: -1 | 1 } | { [key: string]: -1 | 1 }; - $pull?: Partial | { [key: string]: Condition }; + $pull?: { [P in keyof T]?: any } | { [key: string]: any }; $push?: Partial | { [key: string]: any }; - $pushAll?: Partial | { [key: string]: Array }; - $each?: Partial | { [key: string]: Array }; + $pushAll?: Partial | { [key: string]: any[] }; + $each?: Partial | { [key: string]: any[] }; $bit?: { [P in keyof T]?: any } | { [key: string]: any }; }; @@ -1298,7 +1314,7 @@ export interface CollectionAggregationOptions { promoteValues?: boolean; promoteBuffers?: boolean; collation?: CollationDocument; - comment?: string + comment?: string; session?: ClientSession; } @@ -1383,7 +1399,7 @@ export interface DeleteWriteOpResultObject { ok?: number; //The total count of documents deleted. n?: number; - } + }; //The connection object used for the operation. connection?: any; //The number of documents deleted. @@ -1402,8 +1418,8 @@ export interface FindAndModifyWriteOpResultObject { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndReplace */ export interface FindOneAndReplaceOption extends CommonOptions { - projection?: Object; - sort?: Object; + projection?: object; + sort?: object; maxTimeMS?: number; upsert?: boolean; returnOriginal?: boolean; @@ -1412,7 +1428,7 @@ export interface FindOneAndReplaceOption extends CommonOptions { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate */ export interface FindOneAndUpdateOption extends FindOneAndReplaceOption { - arrayFilters?: Object[]; + arrayFilters?: object[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndDelete */ @@ -1428,27 +1444,14 @@ export interface FindOneAndDeleteOption { export interface GeoHaystackSearchOptions { readPreference?: ReadPreference | string; maxDistance?: number; - search?: Object; + search?: object; limit?: number; session?: ClientSession; } -/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoNear */ -export interface GeoNearOptions { - readPreference?: ReadPreference | string; - num?: number; - minDistance?: number; - maxDistance?: number; - distanceMultiplier?: number; - query?: Object; - spherical?: boolean; - uniqueDocs?: boolean; - includeLocs?: boolean; -} - /** http://mongodb.github.io/node-mongodb-native/3.1/api/Code.html */ export class Code { - constructor(code: string | Function, scope?: Object) + constructor(code: string | Function, scope?: object) code: string | Function; scope: any; } @@ -1461,9 +1464,9 @@ export interface OrderedBulkOperation { execute(options?: FSyncOptions): Promise; execute(options: FSyncOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/OrderedBulkOperation.html#find */ - find(selector: Object): FindOperatorsOrdered; + find(selector: object): FindOperatorsOrdered; /** http://mongodb.github.io/node-mongodb-native/3.1/api/OrderedBulkOperation.html#insert */ - insert(doc: Object): OrderedBulkOperation; + insert(doc: object): OrderedBulkOperation; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/BulkWriteResult.html */ @@ -1475,15 +1478,15 @@ export interface BulkWriteResult { nModified: number; nRemoved: number; - getInsertedIds(): Array; - getLastOp(): Object; - getRawResponse(): Object; - getUpsertedIdAt(index: number): Object; - getUpsertedIds(): Array; + getInsertedIds(): object[]; + getLastOp(): object; + getRawResponse(): object; + getUpsertedIdAt(index: number): object; + getUpsertedIds(): object[]; getWriteConcernError(): WriteConcernError; getWriteErrorAt(index: number): WriteError; getWriteErrorCount(): number; - getWriteErrors(): Array; + getWriteErrors(): object[]; hasWriteErrors(): boolean; } @@ -1509,9 +1512,9 @@ export interface WriteConcernError { export interface FindOperatorsOrdered { delete(): OrderedBulkOperation; deleteOne(): OrderedBulkOperation; - replaceOne(doc: Object): OrderedBulkOperation; - update(doc: Object): OrderedBulkOperation; - updateOne(doc: Object): OrderedBulkOperation; + replaceOne(doc: object): OrderedBulkOperation; + update(doc: object): OrderedBulkOperation; + updateOne(doc: object): OrderedBulkOperation; upsert(): FindOperatorsOrdered; } @@ -1524,9 +1527,9 @@ export interface UnorderedBulkOperation { execute(options?: FSyncOptions): Promise; execute(options: FSyncOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/UnorderedBulkOperation.html#find */ - find(selector: Object): FindOperatorsUnordered; + find(selector: object): FindOperatorsUnordered; /** http://mongodb.github.io/node-mongodb-native/3.1/api/UnorderedBulkOperation.html#insert */ - insert(doc: Object): UnorderedBulkOperation; + insert(doc: object): UnorderedBulkOperation; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/FindOperatorsUnordered.html */ @@ -1534,23 +1537,23 @@ export interface FindOperatorsUnordered { length: number; remove(): UnorderedBulkOperation; removeOne(): UnorderedBulkOperation; - replaceOne(doc: Object): UnorderedBulkOperation; - update(doc: Object): UnorderedBulkOperation; - updateOne(doc: Object): UnorderedBulkOperation; + replaceOne(doc: object): UnorderedBulkOperation; + update(doc: object): UnorderedBulkOperation; + updateOne(doc: object): UnorderedBulkOperation; upsert(): FindOperatorsUnordered; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOne */ export interface FindOneOptions { limit?: number; - sort?: Array | Object; - projection?: Object; + sort?: any[] | object; + projection?: object; /** * @deprecated Use options.projection instead */ - fields?: Object; + fields?: object; skip?: number; - hint?: Object; + hint?: object; explain?: boolean; snapshot?: boolean; timeout?: boolean; @@ -1576,10 +1579,10 @@ export interface FindOneOptions { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertWriteOpResult */ export interface InsertWriteOpResult { insertedCount: number; - ops: Array; + ops: any[]; insertedIds: { [key: number]: ObjectID }; connection: any; - result: { ok: number, n: number } + result: { ok: number, n: number }; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne */ @@ -1591,16 +1594,16 @@ export interface CollectionInsertOneOptions extends CommonOptions { //Force server to assign _id values instead of driver. forceServerObjectId?: boolean; //Allow driver to bypass schema validation in MongoDB 3.2 or higher. - bypassDocumentValidation?: boolean + bypassDocumentValidation?: boolean; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpResult */ export interface InsertOneWriteOpResult { insertedCount: number; - ops: Array; + ops: any[]; insertedId: ObjectID; connection: any; - result: { ok: number, n: number } + result: { ok: number, n: number }; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#parallelCollectionScan */ @@ -1620,13 +1623,13 @@ export interface ReplaceOneOptions extends CommonOptions { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateOne */ export interface UpdateOneOptions extends ReplaceOneOptions { - arrayFilters?: Object[]; + arrayFilters?: object[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateMany */ export interface UpdateManyOptions extends CommonOptions { upsert?: boolean; - arrayFilters?: Object[]; + arrayFilters?: object[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~updateWriteOpResult */ @@ -1641,34 +1644,38 @@ export interface UpdateWriteOpResult { /** https://github.com/mongodb/node-mongodb-native/blob/2.2/lib/collection.js#L957 */ export interface ReplaceWriteOpResult extends UpdateWriteOpResult { - ops: Array + ops: any[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#mapReduce */ export interface MapReduceOptions { readPreference?: ReadPreference | string; - out?: Object; - query?: Object; - sort?: Object; + out?: object; + query?: object; + sort?: object; limit?: number; keeptemp?: boolean; finalize?: Function | string; - scope?: Object; + scope?: object; jsMode?: boolean; verbose?: boolean; bypassDocumentValidation?: boolean; session?: ClientSession; } +export type CollectionMapFunction = () => void; + +export type CollectionReduceFunction = (key: string, values: any) => any; + /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~WriteOpResult */ export interface WriteOpResult { - ops: Array; + ops: any[]; connection: any; result: any; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#~resultCallback */ -export type CursorResult = any | void | boolean; +export type CursorResult = object | null | boolean; type Default = any; @@ -1703,7 +1710,7 @@ export class Cursor extends Readable { explain(): Promise; explain(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#filter */ - filter(filter: Object): Cursor; + filter(filter: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#forEach */ forEach(iterator: IteratorCallback, callback: EndCallback): void; forEach(iterator: IteratorCallback): Promise; @@ -1711,7 +1718,7 @@ export class Cursor extends Readable { hasNext(): Promise; hasNext(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#hint */ - hint(hint: Object): Cursor; + hint(hint: string | object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#isClosed */ isClosed(): boolean; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#limit */ @@ -1723,7 +1730,7 @@ export class Cursor extends Readable { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#maxAwaitTimeMS */ maxAwaitTimeMS(value: number): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#maxScan */ - maxScan(maxScan: Object): Cursor; + maxScan(maxScan: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#maxTimeMS */ maxTimeMS(value: number): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#min */ @@ -1732,27 +1739,27 @@ export class Cursor extends Readable { next(): Promise; next(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#project */ - project(value: Object): Cursor; + project(value: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#read */ read(size: number): string | Buffer | void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#next */ - returnKey(returnKey: Object): Cursor; + returnKey(returnKey: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#rewind */ rewind(): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#setCursorOption */ - setCursorOption(field: string, value: Object): Cursor; + setCursorOption(field: string, value: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#setReadPreference */ setReadPreference(readPreference: string | ReadPreference): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#showRecordId */ - showRecordId(showRecordId: Object): Cursor; + showRecordId(showRecordId: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#skip */ skip(value: number): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#snapshot */ - snapshot(snapshot: Object): Cursor; + snapshot(snapshot: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#sort */ - sort(keyOrList: string | Object[] | Object, direction?: number): Cursor; + sort(keyOrList: string | object[] | object, direction?: number): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#stream */ - stream(options?: { transform?: Function }): Cursor; + stream(options?: { transform?: (document: T) => any }): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#toArray */ toArray(): Promise; toArray(callback: MongoCallback): void; @@ -1780,7 +1787,7 @@ export interface EndCallback { } /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#~resultCallback */ -export type AggregationCursorResult = any | void; +export type AggregationCursorResult = object | null; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html */ export class AggregationCursor extends Readable { /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#batchSize */ @@ -1796,9 +1803,9 @@ export class AggregationCursor extends Readable { explain(): Promise; explain(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#geoNear */ - geoNear(document: Object): AggregationCursor; + geoNear(document: object): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#group */ - group(document: Object): AggregationCursor; + group(document: object): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#hasNext */ hasNext(): Promise; hasNext(callback: MongoCallback): void; @@ -1807,7 +1814,7 @@ export class AggregationCursor extends Readable { /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#limit */ limit(value: number): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#match */ - match(document: Object): AggregationCursor; + match(document: object): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#maxTimeMS */ maxTimeMS(value: number): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#next */ @@ -1816,17 +1823,17 @@ export class AggregationCursor extends Readable { /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#out */ out(destination: string): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#project */ - project(document: Object): AggregationCursor; + project(document: object): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#read */ read(size: number): string | Buffer | void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#redact */ - redact(document: Object): AggregationCursor; + redact(document: object): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#rewind */ rewind(): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#setEncoding */ skip(value: number): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#sort */ - sort(document: Object): AggregationCursor; + sort(document: object): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#toArray */ toArray(): Promise; toArray(callback: MongoCallback): void; @@ -1837,7 +1844,7 @@ export class AggregationCursor extends Readable { } /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#~resultCallback */ -export type CommandCursorResult = any | void; +export type CommandCursorResult = object | null; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html */ export class CommandCursor extends Readable { /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#hasNext */ @@ -1881,7 +1888,7 @@ export class GridFSBucket { /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#drop */ drop(callback?: GridFSBucketErrorCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#find */ - find(filter?: Object, options?: GridFSBucketFindOptions): Cursor; + find(filter?: object, options?: GridFSBucketFindOptions): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#openDownloadStream */ openDownloadStream(id: ObjectID, options?: { start: number, end: number }): GridFSBucketReadStream; /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#openDownloadStreamByName */ @@ -1898,8 +1905,8 @@ export class GridFSBucket { export interface GridFSBucketOptions { bucketName?: string; chunkSizeBytes?: number; - writeConcern?: Object; - ReadPreference?: Object; + writeConcern?: object; + ReadPreference?: object; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#~errorCallback */ @@ -1914,29 +1921,29 @@ export interface GridFSBucketFindOptions { maxTimeMS?: number; noCursorTimeout?: boolean; skip?: number; - sort?: Object; + sort?: object; } /** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#openUploadStream */ export interface GridFSBucketOpenUploadStreamOptions { - chunkSizeBytes?: number, - metadata?: Object, - contentType?: string, - aliases?: Array + chunkSizeBytes?: number; + metadata?: object; + contentType?: string; + aliases?: string[]; } /** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketReadStream.html */ export class GridFSBucketReadStream extends Readable { id: ObjectID; - constructor(chunks: Collection, files: Collection, readPreference: Object, filter: Object, options?: GridFSBucketReadStreamOptions); + constructor(chunks: Collection, files: Collection, readPreference: object, filter: object, options?: GridFSBucketReadStreamOptions); } /** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketReadStream.html */ export interface GridFSBucketReadStreamOptions { - sort?: number, - skip?: number, - start?: number, - end?: number + sort?: number; + skip?: number; + start?: number; + end?: number; } /** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketWriteStream.html */ @@ -1949,33 +1956,33 @@ export class GridFSBucketWriteStream extends Writable { export interface GridFSBucketWriteStreamOptions { /** * Custom file id for the GridFS file. - **/ - id?: GridFSBucketWriteStreamId, + */ + id?: GridFSBucketWriteStreamId; /** * The chunk size to use, in bytes */ - chunkSizeBytes?: number, + chunkSizeBytes?: number; /** * The write concern */ - w?: number, + w?: number; /** * The write concern timeout */ - wtimeout?: number, + wtimeout?: number; /** * The journal write concern */ - j?: number + j?: number; /** * Default false; If true, disables adding an md5 field to file data */ - disableMD5?: boolean + disableMD5?: boolean; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html */ export class ChangeStream extends Readable { - constructor(changeDomain: Db | Collection, pipeline: Object[], options?: ChangeStreamOptions); + constructor(changeDomain: Db | Collection, pipeline: object[], options?: ChangeStreamOptions); /** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html#close */ close(): Promise; @@ -1993,94 +2000,94 @@ export class ChangeStream extends Readable { next(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html#stream */ - stream(options?: { transform: Function }): Cursor; + stream(options?: { transform?: Function }): Cursor; } export interface ChangeStreamOptions { fullDocument?: string; maxAwaitTimeMS?: number; - resumeAfter?: Object; + resumeAfter?: object; batchSize?: number; collation?: CollationDocument; readPreference?: ReadPreference; } -type GridFSBucketWriteStreamId = string | number | Object | ObjectID; +type GridFSBucketWriteStreamId = string | number | object | ObjectID; export interface LoggerOptions { /** * Custom logger function */ - loggerLevel?: string + loggerLevel?: string; /** * Override default global log level. */ - logger?: log + logger?: log; } -export type log = (message?: string, state?: LoggerState) => void +export type log = (message?: string, state?: LoggerState) => void; export interface LoggerState { - type: string - message: string - className: string - pid: number - date: number + type: string; + message: string; + className: string; + pid: number; + date: number; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Logger.html */ export class Logger { - constructor(className: string, options?: LoggerOptions) + constructor(className: string, options?: LoggerOptions); /** * Log a message at the debug level */ - debug(message: string, state: LoggerState): void + debug(message: string, state: LoggerState): void; /** * Log a message at the warn level */ - warn(message: string, state: LoggerState): void + warn(message: string, state: LoggerState): void; /** * Log a message at the info level */ - info(message: string, state: LoggerState): void + info(message: string, state: LoggerState): void; /** * Log a message at the error level */ - error(message: string, state: LoggerState): void + error(message: string, state: LoggerState): void; /** * Is the logger set at info level */ - isInfo(): boolean + isInfo(): boolean; /** * Is the logger set at error level */ - isError(): boolean + isError(): boolean; /** * Is the logger set at error level */ - isWarn(): boolean + isWarn(): boolean; /** * Is the logger set at debug level */ - isDebug(): boolean + isDebug(): boolean; /** * Resets the logger to default settings, error and no filtered classes */ - static reset(): void + static reset(): void; /** * Get the current logger function */ - static currentLogger(): log + static currentLogger(): log; //Set the current logger function - static setCurrentLogger(log: log): void + static setCurrentLogger(log: log): void; /** * Set what classes to log. */ - static filter(type: string, values: string[]): void + static filter(type: string, values: string[]): void; /** * Set the current log level */ - static setLevel(level: string): void + static setLevel(level: string): void; } /** https://docs.mongodb.com/manual/reference/collation/#collation-document-fields */ diff --git a/types/mongodb/mongodb-tests.ts b/types/mongodb/mongodb-tests.ts index ea755a8eb1..d8eb287964 100644 --- a/types/mongodb/mongodb-tests.ts +++ b/types/mongodb/mongodb-tests.ts @@ -1,19 +1,19 @@ // Test source : https://github.com/mongodb/node-mongodb-native -import mongodb = require('mongodb'); -var MongoClient = mongodb.MongoClient; + +import { format } from 'util'; +import * as mongodb from 'mongodb'; const connectionString = 'mongodb://127.0.0.1:27017/test'; -var format = require('util').format; -let options: mongodb.MongoClientOptions = { +const options: mongodb.MongoClientOptions = { authSource: ' ', loggerLevel: 'debug', w: 1, wtimeout: 300, j: true, bufferMaxEntries: 1000, - readPreference: 'ReadPreference | string', - promoteValues: {}, + readPreference: true ? mongodb.ReadPreference.NEAREST : 'string', + promoteValues: true, pkFactory: {}, poolSize: 1, @@ -24,7 +24,7 @@ let options: mongodb.MongoClientOptions = { reconnectInterval: 123456, ssl: true, sslValidate: false, - checkServerIdentity: function () { }, + checkServerIdentity: true ? true : (host, cert) => { return undefined; }, sslCA: ['str'], sslCRL: ['str'], sslCert: new Buffer(999), @@ -34,58 +34,63 @@ let options: mongodb.MongoClientOptions = { useNewUrlParser: false, authMechanism: 'SCRAM-SHA-1', forceServerObjectId: false -} -MongoClient.connect(connectionString, options, function (err: mongodb.MongoError, client: mongodb.MongoClient) { +}; + +mongodb.MongoClient.connect(connectionString, options, (err: mongodb.MongoError, client: mongodb.MongoClient) => { if (err) throw err; const db = client.db('test'); - var collection = db.collection('test_insert'); - collection.insertOne({ a: 2 }, function (err: mongodb.MongoError, docs: any) { + const collection = db.collection('test_insert'); + collection.insertOne({ a: 2 }, (err: mongodb.MongoError, result) => { + result.insertedCount; // $ExpectType number + result.insertedId; // $ExpectType ObjectId + result.result.n; // $ExpectType number + result.result.ok; // $ExpectType number // Intentionally omitted type annotation from 'count'. // This way it requires a more accurate typedef which allows inferring that it's a number. - collection.countDocuments(function (err: mongodb.MongoError, count) { + collection.countDocuments((err: mongodb.MongoError, count) => { console.log(format("count = %s", count)); }); - collection.countDocuments().then(function (count: number) { + collection.countDocuments().then((count: number) => { console.log(format("count = %s", count)); }); - collection.countDocuments({ foo: 1 }, function (err: mongodb.MongoError, count: number) { + collection.countDocuments({ foo: 1 }, (err: mongodb.MongoError, count: number) => { console.log(format("count = %s", count)); }); - collection.countDocuments({ foo: 1 }).then(function (count: number) { + collection.countDocuments({ foo: 1 }).then((count: number) => { console.log(format("count = %s", count)); }); - collection.countDocuments({ foo: 1 }, { limit: 10 }, function (err: mongodb.MongoError, count: number) { + collection.countDocuments({ foo: 1 }, { limit: 10 }, (err: mongodb.MongoError, count: number) => { console.log(format("count = %s", count)); }); - collection.countDocuments({ foo: 1 }, { limit: 10 }).then(function (count: number) { + collection.countDocuments({ foo: 1 }, { limit: 10 }).then((count: number) => { console.log(format("count = %s", count)); }); // Locate all the entries using find - collection.find({}).toArray(function (err: mongodb.MongoError, results: any) { + collection.find({}).toArray((err: mongodb.MongoError, results: any) => { console.dir(results); // Let's close the db client.close(); }); // Get some statistics - collection.stats(function (err: mongodb.MongoError, stats: any) { + collection.stats((err: mongodb.MongoError, stats: any) => { console.log(stats.count + " documents"); }); // - collection.stats().then(function (stats) { + collection.stats().then((stats) => { console.log(stats.wiredTiger.cache['bytes currently in the cache']); - }) + }); - collection.createIndex({}, { partialFilterExpression: { rating: { $exists: 1 } } }) + collection.createIndex({}, { partialFilterExpression: { rating: { $exists: 1 } } }); }); { @@ -95,10 +100,11 @@ MongoClient.connect(connectionString, options, function (err: mongodb.MongoError cursor = cursor.addQueryModifier('', true); cursor = cursor.batchSize(1); cursor = cursor.comment(''); - cursor = cursor.filter(1); - cursor = cursor.hint({}); + cursor = cursor.filter({a: 1}); + cursor = cursor.hint({ age: 1 }); + cursor = cursor.hint('age_1'); cursor = cursor.limit(1); - cursor = cursor.map(function (result) { }); + cursor = cursor.map((result) => {}); cursor = cursor.max(1); cursor = cursor.min(1); cursor = cursor.maxAwaitTimeMS(1); @@ -116,54 +122,64 @@ MongoClient.connect(connectionString, options, function (err: mongodb.MongoError } // Collection .findM() & .agggregate() generic tests { - let bag: { cost: number, color: string }; - type bag = typeof bag; - let cursor: mongodb.Cursor = collection.find({ color: 'black' }) - cursor.toArray(function (err, r) { r[0].cost }); - cursor.forEach(function (bag) { bag.color }, () => { }); - collection.findOne({ color: 'white' }).then(b => { let _b: bag = b; }) - collection.findOne({ color: 'white' }).then(b => { b.cost; }) + interface Bag { + cost: number; + color: string; + } + const cursor: mongodb.Cursor = collection.find({ color: 'black' }); + cursor.toArray((err, r) => { r[0].cost; }); + cursor.forEach((bag) => { bag.color; }, () => {}); + collection.findOne({ color: 'white' }).then(b => { const _b: Bag = b; }); + collection.findOne({ color: 'white' }).then(b => { b.cost; }); } { - let payment: { total: number }; - type payment = typeof payment; - let cursor: mongodb.AggregationCursor = collection.aggregate([{}]) + interface Payment { + total: number; + } + const cursor: mongodb.AggregationCursor = collection.aggregate([{}]); - collection.aggregate([{ $match: { bar: 1 } }, { $limit: 10 }]) - collection.aggregate([{ $match: { bar: 1 } }]).limit(10) - collection.aggregate([]).match({ bar: 1 }).limit(10) - collection.aggregate().match({ bar: 1 }).limit(10) + collection.aggregate([{ $match: { bar: 1 } }, { $limit: 10 }]); + collection.aggregate([{ $match: { bar: 1 } }]).limit(10); + collection.aggregate([]).match({ bar: 1 }).limit(10); + collection.aggregate().match({ bar: 1 }).limit(10); - collection.aggregate( + collection.aggregate( [{ $match: { bar: 1 } }], - function (err: mongodb.MongoError, cursor: mongodb.AggregationCursor) { - cursor.limit(10) + (err: mongodb.MongoError, cursor: mongodb.AggregationCursor) => { + cursor.limit(10); } - ) + ); - collection.aggregate( + collection.aggregate( [], - function (err: mongodb.MongoError, cursor: mongodb.AggregationCursor) { - cursor.match({ bar: 1 }).limit(10) + (err: mongodb.MongoError, cursor: mongodb.AggregationCursor) => { + cursor.match({ bar: 1 }).limit(10); } - ) + ); - collection.aggregate( - function (err: mongodb.MongoError, cursor: mongodb.AggregationCursor) { - cursor.match({ bar: 1 }).limit(10) + collection.aggregate( + (err: mongodb.MongoError, cursor: mongodb.AggregationCursor) => { + cursor.match({ bar: 1 }).limit(10); } - ) + ); } // test for new typings { - type TestCollection = { + interface TestCollection { stringField: string; numberField?: number; - }; - let testCollection = db.collection('testCollection'); - testCollection.insertOne({stringField:'hola'}) - testCollection.insertMany([{stringField:'hola'},{stringField:'hola', numberField: 1}]) + fruitTags: string[]; + } + const testCollection = db.collection('testCollection'); + testCollection.insertOne({ + stringField: 'hola', + fruitTags: ['Strawberry'], + }); + testCollection.insertMany([ + { stringField: 'hola', fruitTags: ['Apple', 'Lemon'] }, + { stringField: 'hola', numberField: 1, fruitTags: [] }, + ]); testCollection.find({ numberField: { $and: [{ $gt: 0, $lt: 100 }] @@ -171,16 +187,28 @@ MongoClient.connect(connectionString, options, function (err: mongodb.MongoError }); const res: mongodb.Cursor = testCollection.find({ _id: 123 }); + + testCollection.updateOne( + { stringField: 'hola' }, + { + $addToSet: { + fruitTags: 'Orange', + }, + $pull: { + fruitTags: 'Lemon', + } + } + ); } -}) +}); -let testFunc = async () => { - let testClient: mongodb.MongoClient; - testClient = await mongodb.connect(connectionString); -}; +async function testFunc(): Promise { + const testClient: mongodb.MongoClient = await mongodb.connect(connectionString); + return testClient; +} -mongodb.connect(connectionString, (err: mongodb.MongoError, client: mongodb.MongoClient) => { }); -mongodb.connect(connectionString, options, (err: mongodb.MongoError, client: mongodb.MongoClient) => { }); +mongodb.connect(connectionString, (err: mongodb.MongoError, client: mongodb.MongoClient) => {}); +mongodb.connect(connectionString, options, (err: mongodb.MongoError, client: mongodb.MongoClient) => {}); // https://docs.mongodb.com/manual/core/transactions/ @@ -193,10 +221,10 @@ async function commitWithRetry(session: mongodb.ClientSession) { error.errorLabels && error.errorLabels.indexOf('UnknownTransactionCommitResult') < 0 ) { - console.log('UnknownTransactionCommitResult, retrying commit operation ...'); + console.log('UnknownTransactionCommitResult, retrying commit operation...'); await commitWithRetry(session); } else { - console.log('Error during commit ...'); + console.log('Error during commit...'); throw error; } } @@ -205,7 +233,8 @@ async function commitWithRetry(session: mongodb.ClientSession) { async function runTransactionWithRetry( txnFunc: (client: mongodb.MongoClient, session: mongodb.ClientSession) => Promise, client: mongodb.MongoClient, - session: mongodb.ClientSession) { + session: mongodb.ClientSession +) { try { await txnFunc(client, session); } catch (error) { @@ -256,31 +285,31 @@ async function transfer(client: mongodb.MongoClient, from: any, to: any, amount: const session = client.startSession(); session.startTransaction(); try { - const opts = { session, returnOriginal: false }; - const A = await db.collection('Account'). + const opts = { session, returnOriginal: false }; + const A = await db.collection('Account'). findOneAndUpdate({ name: from }, { $inc: { balance: -amount } }, opts). then(res => res.value); - if (A.balance < 0) { - // If A would have negative balance, fail and abort the transaction - // `session.abortTransaction()` will undo the above `findOneAndUpdate()` - throw new Error('Insufficient funds: ' + (A.balance + amount)); - } + if (A.balance < 0) { + // If A would have negative balance, fail and abort the transaction + // `session.abortTransaction()` will undo the above `findOneAndUpdate()` + throw new Error('Insufficient funds: ' + (A.balance + amount)); + } - const B = await db.collection('Account'). - findOneAndUpdate({ name: to }, { $inc: { balance: amount } }, opts). - then(res => res.value); + const B = await db.collection('Account') + .findOneAndUpdate({ name: to }, { $inc: { balance: amount } }, opts) + .then(res => res.value); - await session.commitTransaction(); - session.endSession(); - return { from: A, to: B }; + await session.commitTransaction(); + session.endSession(); + return { from: A, to: B }; } catch (error) { - // If an error occurred, abort the whole transaction and - // undo any changes that might have happened - await session.abortTransaction(); - session.endSession(); - throw error; // Rethrow so calling function sees error + // If an error occurred, abort the whole transaction and + // undo any changes that might have happened + await session.abortTransaction(); + session.endSession(); + throw error; // Rethrow so calling function sees error } - } +} mongodb.connect(connectionString).then((client) => { client.startSession(); @@ -288,5 +317,3 @@ mongodb.connect(connectionString).then((client) => { runTransactionWithRetry(updateEmployeeInfo, client, session) ); }); - - diff --git a/types/mongodb/tslint.json b/types/mongodb/tslint.json index e3610fefae..f46f693285 100644 --- a/types/mongodb/tslint.json +++ b/types/mongodb/tslint.json @@ -2,79 +2,50 @@ "extends": "dtslint/dt.json", "rules": { "adjacent-overload-signatures": false, - "array-type": false, "arrow-return-shorthand": false, - "ban-types": false, + "ban-types": { + "options": [ + ["Object", "Avoid using the `Object` type. Did you mean `object`?"], + ["Boolean", "Avoid using the `Boolean` type. Did you mean `boolean`?"], + ["Number", "Avoid using the `Number` type. Did you mean `number`?"], + ["String", "Avoid using the `String` type. Did you mean `string`?"], + ["Symbol", "Avoid using the `Symbol` type. Did you mean `symbol`?"] + ] + }, "callable-types": false, "comment-format": false, - "dt-header": false, - "eofline": false, "export-just-namespace": false, "import-spacing": false, "interface-name": false, "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, "member-access": false, "new-parens": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, "no-consecutive-blank-lines": false, - "no-construct": false, "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, "no-namespace": false, "no-object-literal-type-assertion": false, "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, "no-trailing-whitespace": false, "object-literal-key-quotes": false, "object-literal-shorthand": false, "one-line": false, "one-variable-per-declaration": false, - "only-arrow-functions": false, "prefer-conditional-expression": false, - "prefer-const": false, "prefer-declare-function": false, "prefer-for-of": false, "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, "space-before-function-paren": false, "space-within-parens": false, "strict-export-declare-modifiers": false, - "trim-file": false, "triple-equals": false, - "typedef-whitespace": false, "unified-signatures": false, - "use-default-type-parameter": false, - "void-return": false, - "whitespace": false + "use-default-type-parameter": false } } 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 fde5e91372..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 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/nock/nock-tests.ts b/types/nock/nock-tests.ts index 06f8458bcb..76f1e0762c 100644 --- a/types/nock/nock-tests.ts +++ b/types/nock/nock-tests.ts @@ -311,7 +311,7 @@ var scope = nock('http://www.google.com') /// Access original request and headers var scope = nock('http://www.google.com') .get('/cat-poems') - .reply((uri, requestBody) => { + .reply(function (uri, requestBody) { console.log('path:', this.req.path); console.log('headers:', this.req.headers); // ... 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/buffer.d.ts b/types/node/buffer.d.ts index 1d618f2c4b..0fe668b17d 100644 --- a/types/node/buffer.d.ts +++ b/types/node/buffer.d.ts @@ -2,6 +2,10 @@ declare module "buffer" { export const INSPECT_MAX_BYTES: number; const BuffType: typeof Buffer; + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + + export function transcode(source: Buffer | Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { /** @deprecated since v6.0.0, use Buffer.allocUnsafeSlow() */ new(size: number): Buffer; diff --git a/types/node/child_process.d.ts b/types/node/child_process.d.ts index 8e10d4e0c7..4e9c882e1b 100644 --- a/types/node/child_process.d.ts +++ b/types/node/child_process.d.ts @@ -1,20 +1,27 @@ declare module "child_process" { import * as events from "events"; - import * as stream from "stream"; import * as net from "net"; + import { Writable, Readable, Stream, Pipe } from "stream"; interface ChildProcess extends events.EventEmitter { - stdin: stream.Writable; - stdout: stream.Readable; - stderr: stream.Readable; - stdio: [stream.Writable, stream.Readable, stream.Readable]; - killed: boolean; - pid: number; + stdin: Writable | null; + stdout: Readable | null; + stderr: Readable | null; + readonly channel?: Pipe | null; + readonly stdio: [ + Writable | null, // stdin + Readable | null, // stdout + Readable | null, // stderr + Readable | Writable | null | undefined, // extra + Readable | Writable | null | undefined // extra + ]; + readonly killed: boolean; + readonly pid: number; + readonly connected: boolean; kill(signal?: string): void; send(message: any, callback?: (error: Error) => void): boolean; send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error) => void): boolean; send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error) => void): boolean; - connected: boolean; disconnect(): void; unref(): void; ref(): void; @@ -75,17 +82,20 @@ declare module "child_process" { keepOpen?: boolean; } - type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | stream.Stream | number | null | undefined)>; + type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | Stream | number | null | undefined)>; - interface CommonOptions { - /** - * @default true - */ - windowsHide?: boolean; + interface ProcessEnvOptions { uid?: number; gid?: number; cwd?: string; env?: NodeJS.ProcessEnv; + } + + interface CommonOptions extends ProcessEnvOptions { + /** + * @default true + */ + windowsHide?: boolean; /** * @default 0 */ @@ -249,16 +259,12 @@ declare module "child_process" { ): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; } - interface ForkOptions { - cwd?: string; - env?: NodeJS.ProcessEnv; + interface ForkOptions extends ProcessEnvOptions { execPath?: string; execArgv?: string[]; silent?: boolean; stdio?: StdioOptions; windowsVerbatimArguments?: boolean; - uid?: number; - gid?: number; } function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; @@ -285,7 +291,7 @@ declare module "child_process" { stderr: T; status: number; signal: string; - error: Error; + error?: Error; } function spawnSync(command: string): SpawnSyncReturns; function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; diff --git a/types/node/crypto.d.ts b/types/node/crypto.d.ts index 27bf801c9f..99c6e236f5 100644 --- a/types/node/crypto.d.ts +++ b/types/node/crypto.d.ts @@ -169,17 +169,17 @@ declare module "crypto" { function createCipheriv( algorithm: CipherCCMTypes, key: CipherKey, - iv: BinaryLike, + iv: BinaryLike | null, options: CipherCCMOptions ): CipherCCM; function createCipheriv( algorithm: CipherGCMTypes, key: CipherKey, - iv: BinaryLike, + iv: BinaryLike | null, options?: CipherGCMOptions ): CipherGCM; function createCipheriv( - algorithm: string, key: CipherKey, iv: BinaryLike, options?: stream.TransformOptions + algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions ): Cipher; interface Cipher extends NodeJS.ReadWriteStream { @@ -213,16 +213,16 @@ declare module "crypto" { function createDecipheriv( algorithm: CipherCCMTypes, key: BinaryLike, - iv: BinaryLike, + iv: BinaryLike | null, options: CipherCCMOptions, ): DecipherCCM; function createDecipheriv( algorithm: CipherGCMTypes, key: BinaryLike, - iv: BinaryLike, + iv: BinaryLike | null, options?: CipherGCMOptions, ): DecipherGCM; - function createDecipheriv(algorithm: string, key: BinaryLike, iv: BinaryLike, options?: stream.TransformOptions): Decipher; + function createDecipheriv(algorithm: string, key: BinaryLike, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher; interface Decipher extends NodeJS.ReadWriteStream { update(data: Binary): Buffer; @@ -405,6 +405,42 @@ declare module "crypto" { passphrase: string; } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + } + + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + + /** + * @default 0x10001 + */ + publicExponent?: number; + } + + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { /** * Key size in bits @@ -467,46 +503,55 @@ declare module "crypto" { function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; namespace generateKeyPair { function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; } } diff --git a/types/node/globals.d.ts b/types/node/globals.d.ts index cd7d67bbdf..210830f7e8 100644 --- a/types/node/globals.d.ts +++ b/types/node/globals.d.ts @@ -245,6 +245,7 @@ interface Buffer extends Uint8Array { compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; slice(start?: number, end?: number): Buffer; + subarray(begin: number, end?: number): Buffer; writeUIntLE(value: number, offset: number, byteLength: number): number; writeUIntBE(value: number, offset: number, byteLength: number): number; writeIntLE(value: number, offset: number, byteLength: number): number; @@ -267,6 +268,7 @@ interface Buffer extends Uint8Array { readFloatBE(offset: number): number; readDoubleLE(offset: number): number; readDoubleBE(offset: number): number; + reverse(): this; swap16(): Buffer; swap32(): Buffer; swap64(): Buffer; @@ -679,7 +681,7 @@ declare namespace NodeJS { type ExitListener = (code: number) => void; type RejectionHandledListener = (promise: Promise) => void; type UncaughtExceptionListener = (error: Error) => void; - type UnhandledRejectionListener = (reason: any, promise: Promise) => void; + type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; type WarningListener = (warning: Error) => void; type MessageListener = (message: any, sendHandle: any) => void; type SignalsListener = (signal: Signals) => void; @@ -719,6 +721,10 @@ declare namespace NodeJS { destroy(error?: Error): void; } + interface HRTime { + (time?: [number, number]): [number, number]; + } + interface Process extends EventEmitter { /** * Can also be a tty.WriteStream, not typed due to limitation.s @@ -793,12 +799,22 @@ declare namespace NodeJS { cpuUsage(previousValue?: CpuUsage): CpuUsage; nextTick(callback: Function, ...args: any[]): void; release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; /** * Can only be set if not in worker thread. */ umask(mask?: number): number; uptime(): number; - hrtime(time?: [number, number]): [number, number]; + hrtime: HRTime; domain: Domain; // Worker diff --git a/types/node/http.d.ts b/types/node/http.d.ts index b2557963a0..913cf98a37 100644 --- a/types/node/http.d.ts +++ b/types/node/http.d.ts @@ -147,8 +147,8 @@ declare module "http" { // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 // no args in writeContinue callback writeContinue(callback?: () => void): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; - writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; } // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 @@ -159,6 +159,7 @@ declare module "http" { constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + readonly path: string; abort(): void; onSocket(socket: net.Socket): void; setTimeout(timeout: number, callback?: () => void): this; diff --git a/types/node/http2.d.ts b/types/node/http2.d.ts index aecbca783f..48e35190d4 100644 --- a/types/node/http2.d.ts +++ b/types/node/http2.d.ts @@ -582,8 +582,8 @@ declare module "http2" { write(chunk: string | Buffer, callback?: (err: Error) => void): boolean; write(chunk: string | Buffer, encoding?: string, callback?: (err: Error) => void): boolean; writeContinue(): void; - writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; - writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): this; createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; addListener(event: string, listener: (...args: any[]) => void): this; diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 39db1d52fa..41bfd02671 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for non-npm package Node.js 11.9 +// Type definitions for non-npm package Node.js 11.10 // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped @@ -35,18 +35,19 @@ // Jeremie Rodriguez // Samuel Ainsworth // Kyle Uehlein +// Jordi Oliveras Rovira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// NOTE: These definitions support NodeJS and TypeScript 3.1. +// NOTE: These definitions support NodeJS and TypeScript 3.2. // NOTE: TypeScript version-specific augmentations can be found in the following paths: // - ~/base.d.ts - Shared definitions common to all TypeScript versions // - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 +// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 -// NOTE: Augmentations for TypeScript 3.1 and later should use individual files for overrides -// within the respective ~/ts3.1 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.1, so the older definitions will be found here. +// NOTE: Augmentations for TypeScript 3.2 and later should use individual files for overrides +// within the respective ~/ts3.2 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.2, so the older definitions will be found here. // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: /// @@ -54,6 +55,9 @@ // TypeScript 2.1-specific augmentations: // Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) +// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files +// just to ensure the names are known and node typings can be sued without importing these libs. +// if someone really needs these types the libs need to be added via --lib or in tsconfig.json interface MapConstructor { } interface WeakMapConstructor { } interface SetConstructor { } @@ -72,8 +76,9 @@ interface SymbolConstructor { readonly asyncIterator: symbol; } declare var Symbol: SymbolConstructor; -declare class SharedArrayBuffer { - constructor(byteSize: number); +// even this is just a forward declaration some properties are added otherwise +// it would be allowed to pass anything to e.g. Buffer.from() +interface SharedArrayBuffer { readonly byteLength: number; slice(begin?: number, end?: number): SharedArrayBuffer; } diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 089ca86307..900a8fa21a 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -8,24 +8,18 @@ import * as util from "util"; import * as tls from "tls"; import * as http from "http"; import * as https from "https"; -import * as net from "net"; import * as querystring from "querystring"; import * as path from "path"; -import * as childProcess from "child_process"; import * as cluster from "cluster"; import * as os from "os"; import * as vm from "vm"; import * as console2 from "console"; import * as string_decoder from "string_decoder"; -import * as stream from "stream"; import * as timers from "timers"; -import * as repl from "repl"; import * as v8 from "v8"; import * as dns from "dns"; import * as async_hooks from "async_hooks"; -import * as http2 from "http2"; import * as inspector from "inspector"; -import * as perf_hooks from "perf_hooks"; import * as trace_events from "trace_events"; import Module = require("module"); @@ -563,468 +557,6 @@ import Module = require("module"); } } -//////////////////////////////////////////////////// -/// Stream tests : http://nodejs.org/api/stream.html -//////////////////////////////////////////////////// - -// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options -function stream_readable_pipe_test() { - const rs = fs.createReadStream(Buffer.from('file.txt')); - const r = fs.createReadStream('file.txt'); - const z = zlib.createGzip({ finishFlush: zlib.constants.Z_FINISH }); - const w = fs.createWriteStream('file.txt.gz'); - - assert(typeof z.bytesRead === 'number'); - assert(typeof r.bytesRead === 'number'); - assert(typeof r.path === 'string'); - assert(rs.path instanceof Buffer); - - r.pipe(z).pipe(w); - - z.flush(); - r.close(); - z.close(); - rs.close(); -} - -// helpers -const compressMe = new Buffer("some data"); -const compressMeString = "compress me!"; - -zlib.deflate(compressMe, (err: Error | null, result: Buffer) => zlib.inflate(result, (err: Error | null, result: Buffer) => result)); -zlib.deflate( - compressMe, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => zlib.inflate( - result, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => result - ) -); -zlib.deflate(compressMeString, (err: Error | null, result: Buffer) => zlib.inflate(result, (err: Error | null, result: Buffer) => result)); -zlib.deflate( - compressMeString, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => zlib.inflate( - result, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => result - ) -); -const inflated = zlib.inflateSync(zlib.deflateSync(compressMe)); -const inflatedString = zlib.inflateSync(zlib.deflateSync(compressMeString)); - -zlib.deflateRaw(compressMe, (err: Error | null, result: Buffer) => zlib.inflateRaw(result, (err: Error | null, result: Buffer) => result)); -zlib.deflateRaw( - compressMe, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => zlib.inflateRaw( - result, { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => result - ) -); -zlib.deflateRaw(compressMeString, (err: Error | null, result: Buffer) => zlib.inflateRaw(result, (err: Error | null, result: Buffer) => result)); -zlib.deflateRaw( - compressMeString, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error | null, result: Buffer) => result), -); -const inflatedRaw: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMe)); -const inflatedRawString: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMeString)); - -zlib.gzip(compressMe, (err: Error | null, result: Buffer) => zlib.gunzip(result, (err: Error | null, result: Buffer) => result)); -zlib.gzip( - compressMe, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => zlib.gunzip( - result, { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => result - ) -); -const gunzipped: Buffer = zlib.gunzipSync(zlib.gzipSync(compressMe)); - -zlib.unzip(compressMe, (err: Error | null, result: Buffer) => result); -zlib.unzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error | null, result: Buffer) => result); -const unzipped: Buffer = zlib.unzipSync(compressMe); - -// Simplified constructors -function simplified_stream_ctor_test() { - new stream.Readable({ - read(size) { - // $ExpectType Readable - this; - // $ExpectType number - size; - }, - destroy(error, cb) { - // $ExpectType Error | null - error; - // $ExpectType (error: Error | null) => void - cb; - } - }); - - new stream.Writable({ - write(chunk, enc, cb) { - // $ExpectType Writable - this; - // $ExpectType any - chunk; - // $ExpectType string - enc; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - writev(chunks, cb) { - // $ExpectType Writable - this; - // $ExpectType { chunk: any; encoding: string; }[] - chunks; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - destroy(error, cb) { - // $ExpectType Writable - this; - // $ExpectType Error | null - error; - // $ExpectType (error: Error | null) => void - cb; - }, - final(cb) { - // $ExpectType Writable - this; - // $ExpectType (error?: Error | null | undefined) => void - cb; - } - }); - - new stream.Duplex({ - read(size) { - // $ExpectType Duplex - this; - // $ExpectType number - size; - }, - write(chunk, enc, cb) { - // $ExpectType Duplex - this; - // $ExpectType any - chunk; - // $ExpectType string - enc; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - writev(chunks, cb) { - // $ExpectType Duplex - this; - // $ExpectType { chunk: any; encoding: string; }[] - chunks; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - destroy(error, cb) { - // $ExpectType Duplex - this; - // $ExpectType Error | null - error; - // $ExpectType (error: Error | null) => void - cb; - }, - final(cb) { - // $ExpectType Duplex - this; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - readableObjectMode: true, - writableObjectMode: true - }); - - new stream.Transform({ - read(size) { - // $ExpectType Transform - this; - // $ExpectType number - size; - }, - write(chunk, enc, cb) { - // $ExpectType Transform - this; - // $ExpectType any - chunk; - // $ExpectType string - enc; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - writev(chunks, cb) { - // $ExpectType Transform - this; - // $ExpectType { chunk: any; encoding: string; }[] - chunks; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - destroy(error, cb) { - // $ExpectType Transform - this; - // $ExpectType Error | null - error; - // $ExpectType (error: Error | null) => void - cb; - }, - final(cb) { - // $ExpectType Transform - this; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - transform(chunk, enc, cb) { - // $ExpectType Transform - this; - // $ExpectType any - chunk; - // $ExpectType string - enc; - // $ExpectType TransformCallback - cb; - }, - flush(cb) { - // $ExpectType TransformCallback - cb; - }, - allowHalfOpen: true, - readableObjectMode: true, - writableObjectMode: true - }); -} - -function streamPipelineFinished() { - const cancel = stream.finished(process.stdin, (err?: Error) => {}); - cancel(); - - stream.pipeline(process.stdin, process.stdout, (err?: Error) => {}); -} - -async function asyncStreamPipelineFinished() { - const finished = util.promisify(stream.finished); - await finished(process.stdin); - - const pipeline = util.promisify(stream.pipeline); - await pipeline(process.stdin, process.stdout); -} - -////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html /// -////////////////////////////////////////////////// - -{ - { - const ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", - }); - const blah = ctx.context; - - const connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 - }; - const tlsSocket = tls.connect(connOpts); - - const ciphers: string[] = tls.getCiphers(); - const curve: string = tls.DEFAULT_ECDH_CURVE; - } - - { - let _server = tls.createServer({}); - let _boolean: boolean; - const _func1 = (err: Error, resp: Buffer) => { }; - const _func2 = (err: Error, sessionData: any) => { }; - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - */ - - _server = _server.addListener("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.addListener("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.addListener("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.addListener("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - const _err: Error = new Error(); - const _tlsSocket: tls.TLSSocket = tls.connect(1); - const _any: any = 1; - const _func: Function = () => {}; - const _buffer: Buffer = Buffer.from('a'); - _boolean = _server.emit("tlsClientError", _err, _tlsSocket); - _boolean = _server.emit("newSession", _any, _any, _func1); - _boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func); - _boolean = _server.emit("resumeSession", _any, _func2); - _boolean = _server.emit("secureConnection", _tlsSocket); - - _server = _server.on("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.on("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.on("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.on("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.on("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.once("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.once("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.once("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.once("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.once("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.prependListener("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.prependListener("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.prependListener("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.prependListener("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.prependOnceListener("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - // close callback parameter is optional - _server = _server.close(); - - // close callback parameter doesn't specify any arguments, so any - // function is acceptable - _server = _server.close(() => { }); - _server = _server.close((...args: any[]) => { }); - } - - { - let _TLSSocket = tls.connect({ - }); - let _boolean: boolean; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - */ - - _TLSSocket = _TLSSocket.addListener("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.addListener("secureConnect", () => { }); - - const _buffer: Buffer = Buffer.from(""); - _boolean = _TLSSocket.emit("OCSPResponse", _buffer); - _boolean = _TLSSocket.emit("secureConnect"); - - _TLSSocket = _TLSSocket.on("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.on("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.once("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.once("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependListener("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.prependListener("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependOnceListener("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.prependOnceListener("secureConnect", () => { }); - } -} - ////////////////////////////////////////////////////// /// Https tests : http://nodejs.org/api/https.html /// ////////////////////////////////////////////////////// @@ -1331,294 +863,6 @@ async function asyncStreamPipelineFinished() { const end2: string = decoder1.end(new Buffer('test')); } -////////////////////////////////////////////////////////////////////// -/// Child Process tests: https://nodejs.org/api/child_process.html /// -////////////////////////////////////////////////////////////////////// - -{ - { - childProcess.exec("echo test"); - childProcess.exec("echo test", { windowsHide: true }); - childProcess.spawn("echo"); - childProcess.spawn("echo", { windowsHide: true }); - childProcess.spawn("echo", ["test"], { windowsHide: true }); - childProcess.spawn("echo", ["test"], { windowsHide: true, argv0: "echo-test" }); - childProcess.spawn("echo", ["test"], { stdio: [0xdeadbeef, "inherit", undefined, "pipe"] }); - childProcess.spawnSync("echo test"); - childProcess.spawnSync("echo test", {windowsVerbatimArguments: false}); - childProcess.spawnSync("echo test", {windowsVerbatimArguments: false, argv0: "echo-test"}); - childProcess.spawnSync("echo test", {input: new Uint8Array([])}); - childProcess.spawnSync("echo test", {input: new DataView(new ArrayBuffer(1))}); - } - - { - childProcess.execFile("npm", () => {}); - childProcess.execFile("npm", { windowsHide: true }, () => {}); - childProcess.execFile("npm", ["-v"], () => {}); - childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); - childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); - childProcess.execFile("npm", { encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); - childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); - } - - { - childProcess.execFileSync("echo test", {input: new Uint8Array([])}); - childProcess.execFileSync("echo test", {input: new DataView(new ArrayBuffer(1))}); - } - - async function testPromisify() { - const execFile = util.promisify(childProcess.execFile); - let r: { stdout: string | Buffer, stderr: string | Buffer } = await execFile("npm"); - r = await execFile("npm", ["-v"]); - r = await execFile("npm", ["-v"], { encoding: 'utf-8' }); - r = await execFile("npm", ["-v"], { encoding: 'buffer' }); - r = await execFile("npm", { encoding: 'utf-8' }); - r = await execFile("npm", { encoding: 'buffer' }); - } - - { - let _cp = childProcess.spawn('asd'); - const _socket: net.Socket = net.createConnection(1); - const _server: net.Server = net.createServer(); - let _boolean: boolean; - - _boolean = _cp.send(1); - _boolean = _cp.send('one'); - _boolean = _cp.send({ - type: 'test' - }); - - _boolean = _cp.send(1, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, (error) => { - const _err: Error = error; - }); - - _boolean = _cp.send(1, _socket); - _boolean = _cp.send('one', _socket); - _boolean = _cp.send({ - type: 'test' - }, _socket); - - _boolean = _cp.send(1, _socket, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', _socket, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, (error) => { - const _err: Error = error; - }); - - _boolean = _cp.send(1, _socket, { - keepOpen: true - }); - _boolean = _cp.send('one', _socket, { - keepOpen: true - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, { - keepOpen: true - }); - - _boolean = _cp.send(1, _socket, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', _socket, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - - _boolean = _cp.send(1, _server); - _boolean = _cp.send('one', _server); - _boolean = _cp.send({ - type: 'test' - }, _server); - - _boolean = _cp.send(1, _server, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', _server, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _server, (error) => { - const _err: Error = error; - }); - - _boolean = _cp.send(1, _server, { - keepOpen: true - }); - _boolean = _cp.send('one', _server, { - keepOpen: true - }); - _boolean = _cp.send({ - type: 'test' - }, _server, { - keepOpen: true - }); - - _boolean = _cp.send(1, _server, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', _server, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _server, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - - _cp = _cp.addListener("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.addListener("disconnect", () => { }); - _cp = _cp.addListener("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.addListener("exit", (code, signal) => { - const _code: number | null = code; - const _signal: string | null = signal; - }); - _cp = _cp.addListener("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _boolean = _cp.emit("close", () => { }); - _boolean = _cp.emit("disconnect", () => { }); - _boolean = _cp.emit("error", () => { }); - _boolean = _cp.emit("exit", () => { }); - _boolean = _cp.emit("message", () => { }); - - _cp = _cp.on("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.on("disconnect", () => { }); - _cp = _cp.on("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.on("exit", (code, signal) => { - const _code: number | null = code; - const _signal: string | null = signal; - }); - _cp = _cp.on("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.once("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.once("disconnect", () => { }); - _cp = _cp.once("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.once("exit", (code, signal) => { - const _code: number | null = code; - const _signal: string | null = signal; - }); - _cp = _cp.once("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.prependListener("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.prependListener("disconnect", () => { }); - _cp = _cp.prependListener("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.prependListener("exit", (code, signal) => { - const _code: number | null = code; - const _signal: string | null = signal; - }); - _cp = _cp.prependListener("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.prependOnceListener("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.prependOnceListener("disconnect", () => { }); - _cp = _cp.prependOnceListener("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.prependOnceListener("exit", (code, signal) => { - const _code: number | null = code; - const _signal: string | null = signal; - }); - _cp = _cp.prependOnceListener("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - } - { - process.stdin.setEncoding('utf8'); - - process.stdin.on('readable', () => { - const chunk = process.stdin.read(); - if (chunk !== null) { - process.stdout.write(`data: ${chunk}`); - } - }); - - process.stdin.on('end', () => { - process.stdout.write('end'); - }); - - process.stdin.pipe(process.stdout); - - console.log(process.stdin.isTTY); - console.log(process.stdout.isTTY); - - console.log(process.stdin instanceof net.Socket); - console.log(process.stdout instanceof fs.ReadStream); - - const stdin: stream.Readable = process.stdin; - console.log(stdin instanceof net.Socket); - console.log(stdin instanceof fs.ReadStream); - - const stdout: stream.Writable = process.stdout; - console.log(stdout instanceof net.Socket); - console.log(stdout instanceof fs.WriteStream); - } -} - ////////////////////////////////////////////////////////////////////// /// cluster tests: https://nodejs.org/api/cluster.html /// ////////////////////////////////////////////////////////////////////// @@ -1967,7 +1211,7 @@ import * as p from "process"; process.prependListener("exit", (code: number) => { }); process.prependOnceListener("rejectionHandled", (promise: Promise) => { }); process.on("uncaughtException", (error: Error) => { }); - process.addListener("unhandledRejection", (reason: any, promise: Promise) => { }); + process.addListener("unhandledRejection", (reason: {} | null | undefined, promise: Promise) => { }); process.once("warning", (warning: Error) => { }); process.prependListener("message", (message: any, sendHandle: any) => { }); process.prependOnceListener("SIGBREAK", () => { }); @@ -2081,80 +1325,6 @@ import * as p from "process"; } } -///////////////////////////////////////////////////// -/// repl Tests : https://nodejs.org/api/repl.html /// -///////////////////////////////////////////////////// - -{ - { - let _server = repl.start(); - let _boolean: boolean; - const _ctx: vm.Context = {}; - - _server = _server.addListener("exit", () => { }); - _server = _server.addListener("reset", () => { }); - - _boolean = _server.emit("exit", () => { }); - _boolean = _server.emit("reset", _ctx); - - _server = _server.on("exit", () => { }); - _server = _server.on("reset", () => { }); - - _server = _server.once("exit", () => { }); - _server = _server.once("reset", () => { }); - - _server = _server.prependListener("exit", () => { }); - _server = _server.prependListener("reset", () => { }); - - _server = _server.prependOnceListener("exit", () => { }); - _server = _server.prependOnceListener("reset", () => { }); - - _server.outputStream.write("test"); - const line = _server.inputStream.read(); - - _server.clearBufferedCommand(); - _server.displayPrompt(); - _server.displayPrompt(true); - _server.defineCommand("cmd", function(text) { - // $ExpectType string - text; - // $ExpectType REPLServer - this; - }); - _server.defineCommand("cmd", { - help: "", - action(text) { - // $ExpectType string - text; - // $ExpectType REPLServer - this; - } - }); - - repl.start({ - eval() { - // $ExpectType REPLServer - this; - }, - writer() { - // $ExpectType REPLServer - this; - return ""; - } - }); - - function test() { - throw new repl.Recoverable(new Error("test")); - } - - _server.context['key0'] = 1; - _server.context['key1'] = ""; - _server.context['key2'] = true; - _server.context['key3'] = []; - _server.context['key4'] = {}; - } -} - /////////////////////////////////////////////////// /// DNS Tests : https://nodejs.org/api/dns.html /// /////////////////////////////////////////////////// @@ -2434,36 +1604,6 @@ import * as constants from 'constants'; v8.setFlagsFromString('--collect_maps'); } -//////////////////////////////////////////////////// -/// PerfHooks tests : https://nodejs.org/api/perf_hooks.html -//////////////////////////////////////////////////// -{ - perf_hooks.performance.mark('start'); - ( - () => {} - )(); - perf_hooks.performance.mark('end'); - - const { duration } = perf_hooks.performance.getEntriesByName('discover')[0]; - const timeOrigin = perf_hooks.performance.timeOrigin; - - const performanceObserverCallback: perf_hooks.PerformanceObserverCallback = (list, obs) => { - const { - duration, - entryType, - name, - startTime, - } = list.getEntries()[0]; - obs.disconnect(); - perf_hooks.performance.clearFunctions(); - }; - const obs = new perf_hooks.PerformanceObserver(performanceObserverCallback); - obs.observe({ - entryTypes: ['function'], - buffered: true, - }); -} - //////////////////////////////////////////////////// /// AsyncHooks tests : https://nodejs.org/api/async_hooks.html //////////////////////////////////////////////////// @@ -2536,576 +1676,6 @@ import * as constants from 'constants'; } } -/////////////////////////////////////////////////////////// -/// HTTP/2 Tests /// -/////////////////////////////////////////////////////////// - -{ - // Headers & Settings - { - const headers: http2.OutgoingHttpHeaders = { - ':status': 200, - 'content-type': 'text-plain', - ABC: ['has', 'more', 'than', 'one', 'value'], - undef: undefined - }; - - const settings: http2.Settings = { - headerTableSize: 0, - enablePush: true, - initialWindowSize: 0, - maxFrameSize: 0, - maxConcurrentStreams: 0, - maxHeaderListSize: 0 - }; - } - - // Http2Session - { - const http2Session: http2.Http2Session = {} as any; - const ee: events.EventEmitter = http2Session; - - http2Session.on('close', () => {}); - http2Session.on('connect', (session: http2.Http2Session, socket: net.Socket) => {}); - http2Session.on('error', (err: Error) => {}); - http2Session.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); - http2Session.on('goaway', (errorCode: number, lastStreamID: number, opaqueData: Buffer) => {}); - http2Session.on('localSettings', (settings: http2.Settings) => {}); - http2Session.on('remoteSettings', (settings: http2.Settings) => {}); - http2Session.on('stream', (stream: http2.Http2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - http2Session.on('timeout', () => {}); - http2Session.on('ping', () => {}); - - http2Session.destroy(); - - const alpnProtocol: string | undefined = http2Session.alpnProtocol; - const destroyed: boolean | undefined = http2Session.destroyed; - const encrypted: boolean | undefined = http2Session.encrypted; - const originSet: string[] | undefined = http2Session.originSet; - const pendingSettingsAck: boolean = http2Session.pendingSettingsAck; - let settings: http2.Settings = http2Session.localSettings; - const closed: boolean = http2Session.closed; - const connecting: boolean = http2Session.connecting; - settings = http2Session.remoteSettings; - - http2Session.ref(); - http2Session.unref(); - - const headers: http2.OutgoingHttpHeaders = {}; - const options: http2.ClientSessionRequestOptions = { - endStream: true, - exclusive: true, - parent: 0, - weight: 0, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {} - }; - (http2Session as http2.ClientHttp2Session).request(); - (http2Session as http2.ClientHttp2Session).request(headers); - (http2Session as http2.ClientHttp2Session).request(headers, options); - - const stream: http2.Http2Stream = {} as any; - http2Session.rstStream(stream); - http2Session.rstStream(stream, 0); - - http2Session.setTimeout(100, () => {}); - http2Session.close(() => {}); - - const socket: net.Socket | tls.TLSSocket = http2Session.socket; - let state: http2.SessionState = http2Session.state; - state = { - effectiveLocalWindowSize: 0, - effectiveRecvDataLength: 0, - nextStreamID: 0, - localWindowSize: 0, - lastProcStreamID: 0, - remoteWindowSize: 0, - outboundQueueSize: 0, - deflateDynamicTableSize: 0, - inflateDynamicTableSize: 0 - }; - - http2Session.priority(stream, { - exclusive: true, - parent: 0, - weight: 0, - silent: true - }); - - http2Session.settings(settings); - - http2Session.ping((err: Error | null, duration: number, payload: Buffer) => {}); - http2Session.ping(Buffer.from(''), (err: Error | null, duration: number, payload: Buffer) => {}); - http2Session.ping(new DataView(new Int8Array(1).buffer), (err: Error | null, duration: number, payload: Buffer) => {}); - } - - // Http2Stream - { - const http2Stream: http2.Http2Stream = {} as any; - const duplex: stream.Duplex = http2Stream; - - http2Stream.on('aborted', () => {}); - http2Stream.on('error', (err: Error) => {}); - http2Stream.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); - http2Stream.on('streamClosed', (code: number) => {}); - http2Stream.on('timeout', () => {}); - http2Stream.on('trailers', (trailers: http2.IncomingHttpHeaders, flags: number) => {}); - http2Stream.on('wantTrailers', () => {}); - - const aborted: boolean = http2Stream.aborted; - const closed: boolean = http2Stream.closed; - const destroyed: boolean = http2Stream.destroyed; - const pending: boolean = http2Stream.pending; - - http2Stream.priority({ - exclusive: true, - parent: 0, - weight: 0, - silent: true - }); - - const sesh: http2.Http2Session = http2Stream.session; - - http2Stream.setTimeout(100, () => {}); - - let state: http2.StreamState = http2Stream.state; - state = { - localWindowSize: 0, - state: 0, - streamLocalClose: 0, - streamRemoteClose: 0, - sumDependencyWeight: 0, - weight: 0 - }; - - http2Stream.close(); - http2Stream.close(0); - http2Stream.close(0, () => {}); - http2Stream.close(undefined, () => {}); - - // ClientHttp2Stream - const clientHttp2Stream: http2.ClientHttp2Stream = {} as any; - clientHttp2Stream.on('headers', (headers: http2.IncomingHttpHeaders, flags: number) => {}); - clientHttp2Stream.on('push', (headers: http2.IncomingHttpHeaders, flags: number) => {}); - clientHttp2Stream.on('response', (headers: http2.IncomingHttpHeaders & http2.IncomingHttpStatusHeader, flags: number) => { - const s: number = headers[':status']!; - }); - - // ServerHttp2Stream - const serverHttp2Stream: http2.ServerHttp2Stream = {} as any; - const headers: http2.OutgoingHttpHeaders = {}; - - serverHttp2Stream.additionalHeaders(headers); - const headerSent: boolean = serverHttp2Stream.headersSent; - const pushAllowed: boolean = serverHttp2Stream.pushAllowed; - serverHttp2Stream.pushStream(headers, (err: Error | null, pushStream: http2.ServerHttp2Stream, headers: http2.OutgoingHttpHeaders) => {}); - - const options: http2.ServerStreamResponseOptions = { - endStream: true, - waitForTrailers: true, - }; - serverHttp2Stream.respond(); - serverHttp2Stream.respond(headers); - serverHttp2Stream.respond(headers, options); - - const options2: http2.ServerStreamFileResponseOptions = { - statCheck: (stats: fs.Stats, headers: http2.OutgoingHttpHeaders, statOptions: http2.StatOptions) => {}, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {}, - offset: 0, - length: 0 - }; - serverHttp2Stream.respondWithFD(0); - serverHttp2Stream.respondWithFD(0, headers); - serverHttp2Stream.respondWithFD(0, headers, options2); - serverHttp2Stream.respondWithFD(0, headers, {statCheck: () => false}); - const options3: http2.ServerStreamFileResponseOptionsWithError = { - onError: (err: NodeJS.ErrnoException) => {}, - statCheck: (stats: fs.Stats, headers: http2.OutgoingHttpHeaders, statOptions: http2.StatOptions) => {}, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {}, - offset: 0, - length: 0 - }; - serverHttp2Stream.respondWithFile(''); - serverHttp2Stream.respondWithFile('', headers); - serverHttp2Stream.respondWithFile('', headers, options3); - serverHttp2Stream.respondWithFile('', headers, {statCheck: () => false}); - } - - // Http2Server / Http2SecureServer - { - const http2Server: http2.Http2Server = http2.createServer(); - const http2SecureServer: http2.Http2SecureServer = http2.createSecureServer(); - const s1: net.Server = http2Server; - const s2: tls.Server = http2SecureServer; - [http2Server, http2SecureServer].forEach((server) => { - server.on('sessionError', (err: Error) => {}); - server.on('checkContinue', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - server.on('stream', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - server.on('request', (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => {}); - server.on('timeout', () => {}); - }); - - http2SecureServer.on('unknownProtocol', (socket: tls.TLSSocket) => {}); - } - - // Public API (except constants) - { - let settings: http2.Settings = { - }; - const serverOptions: http2.ServerOptions = { - maxDeflateDynamicTableSize: 0, - maxReservedRemoteStreams: 0, - maxSendHeaderBlockLength: 0, - paddingStrategy: 0, - peerMaxConcurrentStreams: 0, - selectPadding: (frameLen: number, maxFrameLen: number) => 0, - settings, - allowHTTP1: true - }; - // tslint:disable-next-line prefer-object-spread (ts2.1 feature) - const secureServerOptions: http2.SecureServerOptions = Object.assign({}, serverOptions); - secureServerOptions.ca = ''; - const onRequestHandler = (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => { - // Http2ServerRequest - - const readable: stream.Readable = request; - let incomingHeaders: http2.IncomingHttpHeaders = request.headers; - incomingHeaders = request.trailers; - const httpVersion: string = request.httpVersion; - let method: string = request.method; - let rawHeaders: string[] = request.rawHeaders; - rawHeaders = request.rawTrailers; - let socket: net.Socket | tls.TLSSocket = request.socket; - let stream: http2.ServerHttp2Stream = request.stream; - const url: string = request.url; - - request.setTimeout(0, () => {}); - request.on('aborted', (hadError: boolean, code: number) => {}); - - // Http2ServerResponse - - let outgoingHeaders: http2.OutgoingHttpHeaders = { - }; - response.addTrailers(outgoingHeaders); - socket = response.connection; - const finished: boolean = response.finished; - response.sendDate = true; - response.statusCode = 200; - response.statusMessage = ''; - socket = response.socket; - stream = response.stream; - - method = response.getHeader(':method'); - const headers: string[] = response.getHeaderNames(); - outgoingHeaders = response.getHeaders(); - const hasMethod = response.hasHeader(':method'); - response.removeHeader(':method'); - response.setHeader(':method', 'GET'); - response.setHeader(':status', 200); - response.setHeader('some-list', ['', '']); - const headersSent: boolean = response.headersSent; - - response.setTimeout(0, () => {}); - response.createPushResponse(outgoingHeaders, (err: Error | null, res: http2.Http2ServerResponse) => {}); - - response.writeContinue(); - response.writeHead(200); - response.writeHead(200, outgoingHeaders); - response.writeHead(200, 'OK', outgoingHeaders); - response.writeHead(200, 'OK'); - response.write(''); - response.write('', (err: Error) => {}); - response.write('', 'utf8'); - response.write('', 'utf8', (err: Error) => {}); - response.write(Buffer.from([])); - response.write(Buffer.from([]), (err: Error) => {}); - response.write(Buffer.from([]), 'utf8'); - response.write(Buffer.from([]), 'utf8', (err: Error) => {}); - response.end(); - response.end(() => {}); - response.end(''); - response.end('', () => {}); - response.end('', 'utf8'); - response.end('', 'utf8', () => {}); - response.end(Buffer.from([])); - response.end(Buffer.from([]), () => {}); - response.end(Buffer.from([]), 'utf8'); - response.end(Buffer.from([]), 'utf8', () => {}); - - request.on('aborted', (hadError: boolean, code: number) => {}); - request.on('close', () => {}); - request.on('drain', () => {}); - request.on('error', (error: Error) => {}); - request.on('finish', () => {}); - }; - - let http2Server: http2.Http2Server; - let http2SecureServer: http2.Http2SecureServer; - - http2Server = http2.createServer(); - http2Server = http2.createServer(serverOptions); - http2Server = http2.createServer(onRequestHandler); - http2Server = http2.createServer(serverOptions, onRequestHandler); - - http2SecureServer = http2.createSecureServer(); - http2SecureServer = http2.createSecureServer(secureServerOptions); - http2SecureServer = http2.createSecureServer(onRequestHandler); - http2SecureServer = http2.createSecureServer(secureServerOptions, onRequestHandler); - - const clientSessionOptions: http2.ClientSessionOptions = { - maxDeflateDynamicTableSize: 0, - maxReservedRemoteStreams: 0, - maxSendHeaderBlockLength: 0, - paddingStrategy: 0, - peerMaxConcurrentStreams: 0, - selectPadding: (frameLen: number, maxFrameLen: number) => 0, - settings - }; - // tslint:disable-next-line prefer-object-spread (ts2.1 feature) - const secureClientSessionOptions: http2.SecureClientSessionOptions = Object.assign({}, clientSessionOptions); - secureClientSessionOptions.ca = ''; - const onConnectHandler = (session: http2.Http2Session, socket: net.Socket) => {}; - - const serverHttp2Session: http2.ServerHttp2Session = {} as any; - - serverHttp2Session.altsvc('', ''); - serverHttp2Session.altsvc('', 0); - serverHttp2Session.altsvc('', new url.URL('')); - serverHttp2Session.altsvc('', { origin: '' }); - serverHttp2Session.altsvc('', { origin: 0 }); - serverHttp2Session.altsvc('', { origin: new url.URL('') }); - - let clientHttp2Session: http2.ClientHttp2Session; - - clientHttp2Session = http2.connect(''); - clientHttp2Session = http2.connect('', onConnectHandler); - clientHttp2Session = http2.connect('', clientSessionOptions); - clientHttp2Session = http2.connect('', clientSessionOptions, onConnectHandler); - clientHttp2Session = http2.connect('', secureClientSessionOptions); - clientHttp2Session = http2.connect('', secureClientSessionOptions, onConnectHandler); - clientHttp2Session.on('altsvc', (alt: string, origin: string, number: number) => {}); - - settings = http2.getDefaultSettings(); - settings = http2.getPackedSettings(settings); - settings = http2.getUnpackedSettings(Buffer.from([])); - settings = http2.getUnpackedSettings(Uint8Array.from([])); - } - - // constants - { - const constants = http2.constants; - let num: number; - let str: string; - num = constants.NGHTTP2_SESSION_SERVER; - num = constants.NGHTTP2_SESSION_CLIENT; - num = constants.NGHTTP2_STREAM_STATE_IDLE; - num = constants.NGHTTP2_STREAM_STATE_OPEN; - num = constants.NGHTTP2_STREAM_STATE_RESERVED_LOCAL; - num = constants.NGHTTP2_STREAM_STATE_RESERVED_REMOTE; - num = constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL; - num = constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE; - num = constants.NGHTTP2_STREAM_STATE_CLOSED; - num = constants.NGHTTP2_NO_ERROR; - num = constants.NGHTTP2_PROTOCOL_ERROR; - num = constants.NGHTTP2_INTERNAL_ERROR; - num = constants.NGHTTP2_FLOW_CONTROL_ERROR; - num = constants.NGHTTP2_SETTINGS_TIMEOUT; - num = constants.NGHTTP2_STREAM_CLOSED; - num = constants.NGHTTP2_FRAME_SIZE_ERROR; - num = constants.NGHTTP2_REFUSED_STREAM; - num = constants.NGHTTP2_CANCEL; - num = constants.NGHTTP2_COMPRESSION_ERROR; - num = constants.NGHTTP2_CONNECT_ERROR; - num = constants.NGHTTP2_ENHANCE_YOUR_CALM; - num = constants.NGHTTP2_INADEQUATE_SECURITY; - num = constants.NGHTTP2_HTTP_1_1_REQUIRED; - num = constants.NGHTTP2_ERR_FRAME_SIZE_ERROR; - num = constants.NGHTTP2_FLAG_NONE; - num = constants.NGHTTP2_FLAG_END_STREAM; - num = constants.NGHTTP2_FLAG_END_HEADERS; - num = constants.NGHTTP2_FLAG_ACK; - num = constants.NGHTTP2_FLAG_PADDED; - num = constants.NGHTTP2_FLAG_PRIORITY; - num = constants.DEFAULT_SETTINGS_HEADER_TABLE_SIZE; - num = constants.DEFAULT_SETTINGS_ENABLE_PUSH; - num = constants.DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE; - num = constants.DEFAULT_SETTINGS_MAX_FRAME_SIZE; - num = constants.MAX_MAX_FRAME_SIZE; - num = constants.MIN_MAX_FRAME_SIZE; - num = constants.MAX_INITIAL_WINDOW_SIZE; - num = constants.NGHTTP2_DEFAULT_WEIGHT; - num = constants.NGHTTP2_SETTINGS_HEADER_TABLE_SIZE; - num = constants.NGHTTP2_SETTINGS_ENABLE_PUSH; - num = constants.NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; - num = constants.NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; - num = constants.NGHTTP2_SETTINGS_MAX_FRAME_SIZE; - num = constants.NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE; - num = constants.PADDING_STRATEGY_NONE; - num = constants.PADDING_STRATEGY_MAX; - num = constants.PADDING_STRATEGY_CALLBACK; - num = constants.HTTP_STATUS_CONTINUE; - num = constants.HTTP_STATUS_SWITCHING_PROTOCOLS; - num = constants.HTTP_STATUS_PROCESSING; - num = constants.HTTP_STATUS_OK; - num = constants.HTTP_STATUS_CREATED; - num = constants.HTTP_STATUS_ACCEPTED; - num = constants.HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION; - num = constants.HTTP_STATUS_NO_CONTENT; - num = constants.HTTP_STATUS_RESET_CONTENT; - num = constants.HTTP_STATUS_PARTIAL_CONTENT; - num = constants.HTTP_STATUS_MULTI_STATUS; - num = constants.HTTP_STATUS_ALREADY_REPORTED; - num = constants.HTTP_STATUS_IM_USED; - num = constants.HTTP_STATUS_MULTIPLE_CHOICES; - num = constants.HTTP_STATUS_MOVED_PERMANENTLY; - num = constants.HTTP_STATUS_FOUND; - num = constants.HTTP_STATUS_SEE_OTHER; - num = constants.HTTP_STATUS_NOT_MODIFIED; - num = constants.HTTP_STATUS_USE_PROXY; - num = constants.HTTP_STATUS_TEMPORARY_REDIRECT; - num = constants.HTTP_STATUS_PERMANENT_REDIRECT; - num = constants.HTTP_STATUS_BAD_REQUEST; - num = constants.HTTP_STATUS_UNAUTHORIZED; - num = constants.HTTP_STATUS_PAYMENT_REQUIRED; - num = constants.HTTP_STATUS_FORBIDDEN; - num = constants.HTTP_STATUS_NOT_FOUND; - num = constants.HTTP_STATUS_METHOD_NOT_ALLOWED; - num = constants.HTTP_STATUS_NOT_ACCEPTABLE; - num = constants.HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED; - num = constants.HTTP_STATUS_REQUEST_TIMEOUT; - num = constants.HTTP_STATUS_CONFLICT; - num = constants.HTTP_STATUS_GONE; - num = constants.HTTP_STATUS_LENGTH_REQUIRED; - num = constants.HTTP_STATUS_PRECONDITION_FAILED; - num = constants.HTTP_STATUS_PAYLOAD_TOO_LARGE; - num = constants.HTTP_STATUS_URI_TOO_LONG; - num = constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE; - num = constants.HTTP_STATUS_RANGE_NOT_SATISFIABLE; - num = constants.HTTP_STATUS_EXPECTATION_FAILED; - num = constants.HTTP_STATUS_TEAPOT; - num = constants.HTTP_STATUS_MISDIRECTED_REQUEST; - num = constants.HTTP_STATUS_UNPROCESSABLE_ENTITY; - num = constants.HTTP_STATUS_LOCKED; - num = constants.HTTP_STATUS_FAILED_DEPENDENCY; - num = constants.HTTP_STATUS_UNORDERED_COLLECTION; - num = constants.HTTP_STATUS_UPGRADE_REQUIRED; - num = constants.HTTP_STATUS_PRECONDITION_REQUIRED; - num = constants.HTTP_STATUS_TOO_MANY_REQUESTS; - num = constants.HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE; - num = constants.HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS; - num = constants.HTTP_STATUS_INTERNAL_SERVER_ERROR; - num = constants.HTTP_STATUS_NOT_IMPLEMENTED; - num = constants.HTTP_STATUS_BAD_GATEWAY; - num = constants.HTTP_STATUS_SERVICE_UNAVAILABLE; - num = constants.HTTP_STATUS_GATEWAY_TIMEOUT; - num = constants.HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED; - num = constants.HTTP_STATUS_VARIANT_ALSO_NEGOTIATES; - num = constants.HTTP_STATUS_INSUFFICIENT_STORAGE; - num = constants.HTTP_STATUS_LOOP_DETECTED; - num = constants.HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED; - num = constants.HTTP_STATUS_NOT_EXTENDED; - num = constants.HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED; - str = constants.HTTP2_HEADER_STATUS; - str = constants.HTTP2_HEADER_METHOD; - str = constants.HTTP2_HEADER_AUTHORITY; - str = constants.HTTP2_HEADER_SCHEME; - str = constants.HTTP2_HEADER_PATH; - str = constants.HTTP2_HEADER_ACCEPT_CHARSET; - str = constants.HTTP2_HEADER_ACCEPT_ENCODING; - str = constants.HTTP2_HEADER_ACCEPT_LANGUAGE; - str = constants.HTTP2_HEADER_ACCEPT_RANGES; - str = constants.HTTP2_HEADER_ACCEPT; - str = constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN; - str = constants.HTTP2_HEADER_AGE; - str = constants.HTTP2_HEADER_ALLOW; - str = constants.HTTP2_HEADER_AUTHORIZATION; - str = constants.HTTP2_HEADER_CACHE_CONTROL; - str = constants.HTTP2_HEADER_CONNECTION; - str = constants.HTTP2_HEADER_CONTENT_DISPOSITION; - str = constants.HTTP2_HEADER_CONTENT_ENCODING; - str = constants.HTTP2_HEADER_CONTENT_LANGUAGE; - str = constants.HTTP2_HEADER_CONTENT_LENGTH; - str = constants.HTTP2_HEADER_CONTENT_LOCATION; - str = constants.HTTP2_HEADER_CONTENT_MD5; - str = constants.HTTP2_HEADER_CONTENT_RANGE; - str = constants.HTTP2_HEADER_CONTENT_TYPE; - str = constants.HTTP2_HEADER_COOKIE; - str = constants.HTTP2_HEADER_DATE; - str = constants.HTTP2_HEADER_ETAG; - str = constants.HTTP2_HEADER_EXPECT; - str = constants.HTTP2_HEADER_EXPIRES; - str = constants.HTTP2_HEADER_FROM; - str = constants.HTTP2_HEADER_HOST; - str = constants.HTTP2_HEADER_IF_MATCH; - str = constants.HTTP2_HEADER_IF_MODIFIED_SINCE; - str = constants.HTTP2_HEADER_IF_NONE_MATCH; - str = constants.HTTP2_HEADER_IF_RANGE; - str = constants.HTTP2_HEADER_IF_UNMODIFIED_SINCE; - str = constants.HTTP2_HEADER_LAST_MODIFIED; - str = constants.HTTP2_HEADER_LINK; - str = constants.HTTP2_HEADER_LOCATION; - str = constants.HTTP2_HEADER_MAX_FORWARDS; - str = constants.HTTP2_HEADER_PREFER; - str = constants.HTTP2_HEADER_PROXY_AUTHENTICATE; - str = constants.HTTP2_HEADER_PROXY_AUTHORIZATION; - str = constants.HTTP2_HEADER_RANGE; - str = constants.HTTP2_HEADER_REFERER; - str = constants.HTTP2_HEADER_REFRESH; - str = constants.HTTP2_HEADER_RETRY_AFTER; - str = constants.HTTP2_HEADER_SERVER; - str = constants.HTTP2_HEADER_SET_COOKIE; - str = constants.HTTP2_HEADER_STRICT_TRANSPORT_SECURITY; - str = constants.HTTP2_HEADER_TRANSFER_ENCODING; - str = constants.HTTP2_HEADER_TE; - str = constants.HTTP2_HEADER_UPGRADE; - str = constants.HTTP2_HEADER_USER_AGENT; - str = constants.HTTP2_HEADER_VARY; - str = constants.HTTP2_HEADER_VIA; - str = constants.HTTP2_HEADER_WWW_AUTHENTICATE; - str = constants.HTTP2_HEADER_HTTP2_SETTINGS; - str = constants.HTTP2_HEADER_KEEP_ALIVE; - str = constants.HTTP2_HEADER_PROXY_CONNECTION; - str = constants.HTTP2_METHOD_ACL; - str = constants.HTTP2_METHOD_BASELINE_CONTROL; - str = constants.HTTP2_METHOD_BIND; - str = constants.HTTP2_METHOD_CHECKIN; - str = constants.HTTP2_METHOD_CHECKOUT; - str = constants.HTTP2_METHOD_CONNECT; - str = constants.HTTP2_METHOD_COPY; - str = constants.HTTP2_METHOD_DELETE; - str = constants.HTTP2_METHOD_GET; - str = constants.HTTP2_METHOD_HEAD; - str = constants.HTTP2_METHOD_LABEL; - str = constants.HTTP2_METHOD_LINK; - str = constants.HTTP2_METHOD_LOCK; - str = constants.HTTP2_METHOD_MERGE; - str = constants.HTTP2_METHOD_MKACTIVITY; - str = constants.HTTP2_METHOD_MKCALENDAR; - str = constants.HTTP2_METHOD_MKCOL; - str = constants.HTTP2_METHOD_MKREDIRECTREF; - str = constants.HTTP2_METHOD_MKWORKSPACE; - str = constants.HTTP2_METHOD_MOVE; - str = constants.HTTP2_METHOD_OPTIONS; - str = constants.HTTP2_METHOD_ORDERPATCH; - str = constants.HTTP2_METHOD_PATCH; - str = constants.HTTP2_METHOD_POST; - str = constants.HTTP2_METHOD_PRI; - str = constants.HTTP2_METHOD_PROPFIND; - str = constants.HTTP2_METHOD_PROPPATCH; - str = constants.HTTP2_METHOD_PUT; - str = constants.HTTP2_METHOD_REBIND; - str = constants.HTTP2_METHOD_REPORT; - str = constants.HTTP2_METHOD_SEARCH; - str = constants.HTTP2_METHOD_TRACE; - str = constants.HTTP2_METHOD_UNBIND; - str = constants.HTTP2_METHOD_UNCHECKOUT; - str = constants.HTTP2_METHOD_UNLINK; - str = constants.HTTP2_METHOD_UNLOCK; - str = constants.HTTP2_METHOD_UPDATE; - str = constants.HTTP2_METHOD_UPDATEREDIRECTREF; - str = constants.HTTP2_METHOD_VERSION_CONTROL; - } -} - /////////////////////////////////////////////////////////// /// Inspector Tests /// /////////////////////////////////////////////////////////// diff --git a/types/node/package.json b/types/node/package.json index c1f0c68752..cda6cc6dc8 100644 --- a/types/node/package.json +++ b/types/node/package.json @@ -2,10 +2,10 @@ "private": true, "types": "index", "typesVersions": { - ">=3.1.0-0": { + ">=3.2.0-0": { "*": [ - "ts3.1/*" + "ts3.2/*" ] } } -} \ No newline at end of file +} diff --git a/types/node/perf_hooks.d.ts b/types/node/perf_hooks.d.ts index 4f68895ce6..bf44d446eb 100644 --- a/types/node/perf_hooks.d.ts +++ b/types/node/perf_hooks.d.ts @@ -238,4 +238,67 @@ declare module "perf_hooks" { } const performance: Performance; + + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number; + } + + interface EventLoopDelayMonitor { + /** + * Enables the event loop delay sample timer. Returns `true` if the timer was started, `false` if it was already started. + */ + enable(): boolean; + /** + * Disables the event loop delay sample timer. Returns `true` if the timer was stopped, `false` if it was already stopped. + */ + disable(): boolean; + + /** + * Resets the collected histogram data. + */ + reset(): void; + + /** + * Returns the value at the given percentile. + * @param percentile A percentile value between 1 and 100. + */ + percentile(percentile: number): number; + + /** + * A `Map` object detailing the accumulated percentile distribution. + */ + readonly percentiles: Map; + + /** + * The number of times the event loop delay exceeded the maximum 1 hour eventloop delay threshold. + */ + readonly exceeds: number; + + /** + * The minimum recorded event loop delay. + */ + readonly min: number; + + /** + * The maximum recorded event loop delay. + */ + readonly max: number; + + /** + * The mean of the recorded event loop delays. + */ + readonly mean: number; + + /** + * The standard deviation of the recorded event loop delays. + */ + readonly stddev: number; + } + + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): EventLoopDelayMonitor; } diff --git a/types/node/repl.d.ts b/types/node/repl.d.ts index cb5a3d037b..71f490443d 100644 --- a/types/node/repl.d.ts +++ b/types/node/repl.d.ts @@ -260,6 +260,16 @@ declare module "repl" { */ clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @param path The path to the history file + */ + setupHistory(path: string, cb: (err: Error | null, repl: this) => void): void; + /** * events.EventEmitter * 1. close - inherited from `readline.Interface` diff --git a/types/node/stream.d.ts b/types/node/stream.d.ts index 122ae563c7..2b0e1c72ac 100644 --- a/types/node/stream.d.ts +++ b/types/node/stream.d.ts @@ -288,6 +288,8 @@ declare module "stream" { ...streams: Array, ): Promise; } + + interface Pipe { } } export = internal; diff --git a/types/node/test/buffer.ts b/types/node/test/buffer.ts index 37b02ef708..dd3329ba24 100644 --- a/types/node/test/buffer.ts +++ b/types/node/test/buffer.ts @@ -1,5 +1,5 @@ // Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; +import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; const utf8Buffer = new Buffer('test'); const base64Buffer = new Buffer('', 'base64'); @@ -38,7 +38,8 @@ const result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999); const arrUint8: Uint8Array = new Uint8Array(2); const buf5: Buffer = Buffer.from(arrUint8); const buf6: Buffer = Buffer.from(buf1); - const buf7: Buffer = Buffer.from(new SharedArrayBuffer(123)); + const sb: SharedArrayBuffer = {} as any; + const buf7: Buffer = Buffer.from(sb); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) @@ -201,3 +202,19 @@ b.fill('a').fill('b'); const buffer = new Buffer('123'); const octets = new Uint8Array(buffer.buffer); } + +// Inherited from Uint8Array but return buffer +{ + const b = Buffer.from('asd'); + let res: Buffer = b.reverse(); + res = b.subarray(1); +} + +// Buffer module, transcode function +{ + transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer + + const source: TranscodeEncoding = 'utf8'; + const target: TranscodeEncoding = 'ascii'; + transcode(Buffer.from('€'), source, target); // $ExpectType Buffer +} diff --git a/types/node/test/child_process.ts b/types/node/test/child_process.ts new file mode 100644 index 0000000000..cf5b3e4656 --- /dev/null +++ b/types/node/test/child_process.ts @@ -0,0 +1,305 @@ +import * as childProcess from 'child_process'; +import * as net from 'net'; +import * as fs from 'fs'; +import * as assert from 'assert'; +import { promisify } from 'util'; +import { Writable, Readable, Pipe } from 'stream'; + +{ + childProcess.exec("echo test"); + childProcess.exec("echo test", { windowsHide: true }); + childProcess.spawn("echo"); + childProcess.spawn("echo", { windowsHide: true }); + childProcess.spawn("echo", ["test"], { windowsHide: true }); + childProcess.spawn("echo", ["test"], { windowsHide: true, argv0: "echo-test" }); + childProcess.spawn("echo", ["test"], { stdio: [0xdeadbeef, "inherit", undefined, "pipe"] }); + childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test", {windowsVerbatimArguments: false}); + childProcess.spawnSync("echo test", {windowsVerbatimArguments: false, argv0: "echo-test"}); + childProcess.spawnSync("echo test", {input: new Uint8Array([])}); + childProcess.spawnSync("echo test", {input: new DataView(new ArrayBuffer(1))}); +} + +{ + childProcess.execFile("npm", () => {}); + childProcess.execFile("npm", { windowsHide: true }, () => {}); + childProcess.execFile("npm", ["-v"], () => {}); + childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); + childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); + childProcess.execFile("npm", { encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); + childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); +} + +{ + childProcess.execFileSync("echo test", {input: new Uint8Array([])}); + childProcess.execFileSync("echo test", {input: new DataView(new ArrayBuffer(1))}); +} + +{ + const forked = childProcess.fork('./', ['asd'], { + windowsVerbatimArguments: true, + silent: false, + stdio: "inherit", + execPath: '', + execArgv: ['asda'] + }); + const ipc: Pipe = forked.channel!; +} + +async function testPromisify() { + const execFile = promisify(childProcess.execFile); + let r: { stdout: string | Buffer, stderr: string | Buffer } = await execFile("npm"); + r = await execFile("npm", ["-v"]); + r = await execFile("npm", ["-v"], { encoding: 'utf-8' }); + r = await execFile("npm", ["-v"], { encoding: 'buffer' }); + r = await execFile("npm", { encoding: 'utf-8' }); + r = await execFile("npm", { encoding: 'buffer' }); +} + +{ + let cp = childProcess.spawn('asd'); + const _socket: net.Socket = net.createConnection(1); + const _server: net.Server = net.createServer(); + let _boolean: boolean; + + _boolean = cp.send(1); + _boolean = cp.send('one'); + _boolean = cp.send({ + type: 'test' + }); + + _boolean = cp.send(1, (error) => { + const _err: Error = error; + }); + _boolean = cp.send('one', (error) => { + const _err: Error = error; + }); + _boolean = cp.send({ + type: 'test' + }, (error) => { + const _err: Error = error; + }); + + _boolean = cp.send(1, _socket); + _boolean = cp.send('one', _socket); + _boolean = cp.send({ + type: 'test' + }, _socket); + + _boolean = cp.send(1, _socket, (error) => { + const _err: Error = error; + }); + _boolean = cp.send('one', _socket, (error) => { + const _err: Error = error; + }); + _boolean = cp.send({ + type: 'test' + }, _socket, (error) => { + const _err: Error = error; + }); + + _boolean = cp.send(1, _socket, { + keepOpen: true + }); + _boolean = cp.send('one', _socket, { + keepOpen: true + }); + _boolean = cp.send({ + type: 'test' + }, _socket, { + keepOpen: true + }); + + _boolean = cp.send(1, _socket, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + _boolean = cp.send('one', _socket, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + _boolean = cp.send({ + type: 'test' + }, _socket, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + + _boolean = cp.send(1, _server); + _boolean = cp.send('one', _server); + _boolean = cp.send({ + type: 'test' + }, _server); + + _boolean = cp.send(1, _server, (error) => { + const _err: Error = error; + }); + _boolean = cp.send('one', _server, (error) => { + const _err: Error = error; + }); + _boolean = cp.send({ + type: 'test' + }, _server, (error) => { + const _err: Error = error; + }); + + _boolean = cp.send(1, _server, { + keepOpen: true + }); + _boolean = cp.send('one', _server, { + keepOpen: true + }); + _boolean = cp.send({ + type: 'test' + }, _server, { + keepOpen: true + }); + + _boolean = cp.send(1, _server, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + _boolean = cp.send('one', _server, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + _boolean = cp.send({ + type: 'test' + }, _server, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + + const stdin: Writable | null = cp.stdio[0]; + const stdout: Readable | null = cp.stdio[1]; + const stderr: Readable | null = cp.stdio[2]; + const fd4: Readable | Writable | null = cp.stdio[3]!; + const fd5: Readable | Writable | null = cp.stdio[4]!; + + cp = cp.addListener("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + cp = cp.addListener("disconnect", () => { }); + cp = cp.addListener("error", (err) => { + const _err: Error = err; + }); + cp = cp.addListener("exit", (code, signal) => { + const _code: number | null = code; + const _signal: string | null = signal; + }); + cp = cp.addListener("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + + _boolean = cp.emit("close", () => { }); + _boolean = cp.emit("disconnect", () => { }); + _boolean = cp.emit("error", () => { }); + _boolean = cp.emit("exit", () => { }); + _boolean = cp.emit("message", () => { }); + + cp = cp.on("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + cp = cp.on("disconnect", () => { }); + cp = cp.on("error", (err) => { + const _err: Error = err; + }); + cp = cp.on("exit", (code, signal) => { + const _code: number | null = code; + const _signal: string | null = signal; + }); + cp = cp.on("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + + cp = cp.once("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + cp = cp.once("disconnect", () => { }); + cp = cp.once("error", (err) => { + const _err: Error = err; + }); + cp = cp.once("exit", (code, signal) => { + const _code: number | null = code; + const _signal: string | null = signal; + }); + cp = cp.once("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + + cp = cp.prependListener("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + cp = cp.prependListener("disconnect", () => { }); + cp = cp.prependListener("error", (err) => { + const _err: Error = err; + }); + cp = cp.prependListener("exit", (code, signal) => { + const _code: number | null = code; + const _signal: string | null = signal; + }); + cp = cp.prependListener("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + + cp = cp.prependOnceListener("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + cp = cp.prependOnceListener("disconnect", () => { }); + cp = cp.prependOnceListener("error", (err) => { + const _err: Error = err; + }); + cp = cp.prependOnceListener("exit", (code, signal) => { + const _code: number | null = code; + const _signal: string | null = signal; + }); + cp = cp.prependOnceListener("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); +} +{ + process.stdin.setEncoding('utf8'); + + process.stdin.on('readable', () => { + const chunk = process.stdin.read(); + if (chunk !== null) { + process.stdout.write(`data: ${chunk}`); + } + }); + + process.stdin.on('end', () => { + process.stdout.write('end'); + }); + + process.stdin.pipe(process.stdout); + + console.log(process.stdin.isTTY); + console.log(process.stdout.isTTY); + + console.log(process.stdin instanceof net.Socket); + console.log(process.stdout instanceof fs.ReadStream); + + const stdin: Readable = process.stdin; + console.log(stdin instanceof net.Socket); + console.log(stdin instanceof fs.ReadStream); + + const stdout: Writable = process.stdout; + console.log(stdout instanceof net.Socket); + console.log(stdout instanceof fs.WriteStream); +} diff --git a/types/node/test/crypto.ts b/types/node/test/crypto.ts index 8238567557..4dbe6e06ff 100644 --- a/types/node/test/crypto.ts +++ b/types/node/test/crypto.ts @@ -113,7 +113,7 @@ import { promisify } from 'util'; } { - const key = 'keykeykeykeykeykeykeykey'; + const key: string | null = 'keykeykeykeykeykeykeykey'; const nonce = crypto.randomBytes(12); const aad = Buffer.from('0123456789', 'hex'); diff --git a/types/node/test/http.ts b/types/node/test/http.ts index 6e4db63a2c..462722a8ff 100644 --- a/types/node/test/http.ts +++ b/types/node/test/http.ts @@ -65,7 +65,7 @@ import * as net from 'net'; res.addTrailers({ 'x-foo': 'bar' }); // writeHead - res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n'); + res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n').end(); res.writeHead(200, { 'Transfer-Encoding': 'chunked' }); res.writeHead(200); @@ -112,6 +112,9 @@ import * as net from 'net'; // event req.on('data', () => { }); + + // path + const path: string = req.path; } { diff --git a/types/node/test/http2.ts b/types/node/test/http2.ts new file mode 100644 index 0000000000..0bada91a97 --- /dev/null +++ b/types/node/test/http2.ts @@ -0,0 +1,604 @@ +import { + Settings, + Http2Session, + Http2Stream, + ClientSessionRequestOptions, + ClientHttp2Session, + SessionState, + StreamState, + ClientHttp2Stream, + IncomingHttpStatusHeader, + ServerHttp2Stream, + ServerStreamResponseOptions, + ServerStreamFileResponseOptions, + StatOptions, + ServerStreamFileResponseOptionsWithError, + Http2Server, + Http2SecureServer, + createSecureServer, + Http2ServerRequest, + Http2ServerResponse, + SecureServerOptions, + ClientSessionOptions, + SecureClientSessionOptions, + ServerHttp2Session, + connect, + getDefaultSettings, + getPackedSettings, + getUnpackedSettings, + OutgoingHttpHeaders, + IncomingHttpHeaders, + createServer, + constants, + ServerOptions +} from "http2"; +import { EventEmitter } from "events"; +import { Stats } from "fs"; +import { Socket, Server } from "net"; +import { TLSSocket } from "tls"; +import { Duplex, Readable } from "stream"; +import { URL } from 'url'; + +// Headers & Settings +{ + const headers: OutgoingHttpHeaders = { + ':status': 200, + 'content-type': 'text-plain', + ABC: ['has', 'more', 'than', 'one', 'value'], + undef: undefined + }; + + const settings: Settings = { + headerTableSize: 0, + enablePush: true, + initialWindowSize: 0, + maxFrameSize: 0, + maxConcurrentStreams: 0, + maxHeaderListSize: 0 + }; +} + +// Http2Session +{ + const http2Session: Http2Session = {} as any; + const ee: EventEmitter = http2Session; + + http2Session.on('close', () => {}); + http2Session.on('connect', (session: Http2Session, socket: Socket) => {}); + http2Session.on('error', (err: Error) => {}); + http2Session.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); + http2Session.on('goaway', (errorCode: number, lastStreamID: number, opaqueData: Buffer) => {}); + http2Session.on('localSettings', (settings: Settings) => {}); + http2Session.on('remoteSettings', (settings: Settings) => {}); + http2Session.on('stream', (stream: Http2Stream, headers: IncomingHttpHeaders, flags: number) => {}); + http2Session.on('timeout', () => {}); + http2Session.on('ping', () => {}); + + http2Session.destroy(); + + const alpnProtocol: string | undefined = http2Session.alpnProtocol; + const destroyed: boolean | undefined = http2Session.destroyed; + const encrypted: boolean | undefined = http2Session.encrypted; + const originSet: string[] | undefined = http2Session.originSet; + const pendingSettingsAck: boolean = http2Session.pendingSettingsAck; + let settings: Settings = http2Session.localSettings; + const closed: boolean = http2Session.closed; + const connecting: boolean = http2Session.connecting; + settings = http2Session.remoteSettings; + + http2Session.ref(); + http2Session.unref(); + + const headers: OutgoingHttpHeaders = {}; + const options: ClientSessionRequestOptions = { + endStream: true, + exclusive: true, + parent: 0, + weight: 0, + getTrailers: (trailers: OutgoingHttpHeaders) => {} + }; + (http2Session as ClientHttp2Session).request(); + (http2Session as ClientHttp2Session).request(headers); + (http2Session as ClientHttp2Session).request(headers, options); + + const stream: Http2Stream = {} as any; + http2Session.rstStream(stream); + http2Session.rstStream(stream, 0); + + http2Session.setTimeout(100, () => {}); + http2Session.close(() => {}); + + const socket: Socket | TLSSocket = http2Session.socket; + let state: SessionState = http2Session.state; + state = { + effectiveLocalWindowSize: 0, + effectiveRecvDataLength: 0, + nextStreamID: 0, + localWindowSize: 0, + lastProcStreamID: 0, + remoteWindowSize: 0, + outboundQueueSize: 0, + deflateDynamicTableSize: 0, + inflateDynamicTableSize: 0 + }; + + http2Session.priority(stream, { + exclusive: true, + parent: 0, + weight: 0, + silent: true + }); + + http2Session.settings(settings); + + http2Session.ping((err: Error | null, duration: number, payload: Buffer) => {}); + http2Session.ping(Buffer.from(''), (err: Error | null, duration: number, payload: Buffer) => {}); + http2Session.ping(new DataView(new Int8Array(1).buffer), (err: Error | null, duration: number, payload: Buffer) => {}); +} + +// Http2Stream +{ + const http2Stream: Http2Stream = {} as any; + const duplex: Duplex = http2Stream; + + http2Stream.on('aborted', () => {}); + http2Stream.on('error', (err: Error) => {}); + http2Stream.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); + http2Stream.on('streamClosed', (code: number) => {}); + http2Stream.on('timeout', () => {}); + http2Stream.on('trailers', (trailers: IncomingHttpHeaders, flags: number) => {}); + http2Stream.on('wantTrailers', () => {}); + + const aborted: boolean = http2Stream.aborted; + const closed: boolean = http2Stream.closed; + const destroyed: boolean = http2Stream.destroyed; + const pending: boolean = http2Stream.pending; + + http2Stream.priority({ + exclusive: true, + parent: 0, + weight: 0, + silent: true + }); + + const sesh: Http2Session = http2Stream.session; + + http2Stream.setTimeout(100, () => {}); + + let state: StreamState = http2Stream.state; + state = { + localWindowSize: 0, + state: 0, + streamLocalClose: 0, + streamRemoteClose: 0, + sumDependencyWeight: 0, + weight: 0 + }; + + http2Stream.close(); + http2Stream.close(0); + http2Stream.close(0, () => {}); + http2Stream.close(undefined, () => {}); + + // ClientHttp2Stream + const clientHttp2Stream: ClientHttp2Stream = {} as any; + clientHttp2Stream.on('headers', (headers: IncomingHttpHeaders, flags: number) => {}); + clientHttp2Stream.on('push', (headers: IncomingHttpHeaders, flags: number) => {}); + clientHttp2Stream.on('response', (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => { + const s: number = headers[':status']!; + }); + + // ServerHttp2Stream + const serverHttp2Stream: ServerHttp2Stream = {} as any; + const headers: OutgoingHttpHeaders = {}; + + serverHttp2Stream.additionalHeaders(headers); + const headerSent: boolean = serverHttp2Stream.headersSent; + const pushAllowed: boolean = serverHttp2Stream.pushAllowed; + serverHttp2Stream.pushStream(headers, (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => {}); + + const options: ServerStreamResponseOptions = { + endStream: true, + waitForTrailers: true, + }; + serverHttp2Stream.respond(); + serverHttp2Stream.respond(headers); + serverHttp2Stream.respond(headers, options); + + const options2: ServerStreamFileResponseOptions = { + statCheck: (stats: Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => {}, + getTrailers: (trailers: OutgoingHttpHeaders) => {}, + offset: 0, + length: 0 + }; + serverHttp2Stream.respondWithFD(0); + serverHttp2Stream.respondWithFD(0, headers); + serverHttp2Stream.respondWithFD(0, headers, options2); + serverHttp2Stream.respondWithFD(0, headers, {statCheck: () => false}); + const options3: ServerStreamFileResponseOptionsWithError = { + onError: (err: NodeJS.ErrnoException) => {}, + statCheck: (stats: Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => {}, + getTrailers: (trailers: OutgoingHttpHeaders) => {}, + offset: 0, + length: 0 + }; + serverHttp2Stream.respondWithFile(''); + serverHttp2Stream.respondWithFile('', headers); + serverHttp2Stream.respondWithFile('', headers, options3); + serverHttp2Stream.respondWithFile('', headers, {statCheck: () => false}); +} + +// Http2Server / Http2SecureServer +{ + const http2Server: Http2Server = createServer(); + const http2SecureServer: Http2SecureServer = createSecureServer(); + const s1: Server = http2Server; + const s2: Server = http2SecureServer; + [http2Server, http2SecureServer].forEach((server) => { + server.on('sessionError', (err: Error) => {}); + server.on('checkContinue', (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => {}); + server.on('stream', (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => {}); + server.on('request', (request: Http2ServerRequest, response: Http2ServerResponse) => {}); + server.on('timeout', () => {}); + }); + + http2SecureServer.on('unknownProtocol', (socket: TLSSocket) => {}); +} + +// Public API (except constants) +{ + let settings: Settings = { + }; + const serverOptions: ServerOptions = { + maxDeflateDynamicTableSize: 0, + maxReservedRemoteStreams: 0, + maxSendHeaderBlockLength: 0, + paddingStrategy: 0, + peerMaxConcurrentStreams: 0, + selectPadding: (frameLen: number, maxFrameLen: number) => 0, + settings, + allowHTTP1: true + }; + // tslint:disable-next-line prefer-object-spread (ts2.1 feature) + const secureServerOptions: SecureServerOptions = Object.assign({}, serverOptions); + secureServerOptions.ca = ''; + const onRequestHandler = (request: Http2ServerRequest, response: Http2ServerResponse) => { + // Http2ServerRequest + + const readable: Readable = request; + let incomingHeaders: IncomingHttpHeaders = request.headers; + incomingHeaders = request.trailers; + const httpVersion: string = request.httpVersion; + let method: string = request.method; + let rawHeaders: string[] = request.rawHeaders; + rawHeaders = request.rawTrailers; + let socket: Socket | TLSSocket = request.socket; + let stream: ServerHttp2Stream = request.stream; + const url: string = request.url; + + request.setTimeout(0, () => {}); + request.on('aborted', (hadError: boolean, code: number) => {}); + + // Http2ServerResponse + + let outgoingHeaders: OutgoingHttpHeaders = { + }; + response.addTrailers(outgoingHeaders); + socket = response.connection; + const finished: boolean = response.finished; + response.sendDate = true; + response.statusCode = 200; + response.statusMessage = ''; + socket = response.socket; + stream = response.stream; + + method = response.getHeader(':method'); + const headers: string[] = response.getHeaderNames(); + outgoingHeaders = response.getHeaders(); + const hasMethod = response.hasHeader(':method'); + response.removeHeader(':method'); + response.setHeader(':method', 'GET'); + response.setHeader(':status', 200); + response.setHeader('some-list', ['', '']); + const headersSent: boolean = response.headersSent; + + response.setTimeout(0, () => {}); + response.createPushResponse(outgoingHeaders, (err: Error | null, res: Http2ServerResponse) => {}); + + response.writeContinue(); + response.writeHead(200).end(); + response.writeHead(200, outgoingHeaders); + response.writeHead(200, 'OK', outgoingHeaders); + response.writeHead(200, 'OK'); + response.write(''); + response.write('', (err: Error) => {}); + response.write('', 'utf8'); + response.write('', 'utf8', (err: Error) => {}); + response.write(Buffer.from([])); + response.write(Buffer.from([]), (err: Error) => {}); + response.write(Buffer.from([]), 'utf8'); + response.write(Buffer.from([]), 'utf8', (err: Error) => {}); + response.end(); + response.end(() => {}); + response.end(''); + response.end('', () => {}); + response.end('', 'utf8'); + response.end('', 'utf8', () => {}); + response.end(Buffer.from([])); + response.end(Buffer.from([]), () => {}); + response.end(Buffer.from([]), 'utf8'); + response.end(Buffer.from([]), 'utf8', () => {}); + + request.on('aborted', (hadError: boolean, code: number) => {}); + request.on('close', () => {}); + request.on('drain', () => {}); + request.on('error', (error: Error) => {}); + request.on('finish', () => {}); + }; + + let http2Server: Http2Server; + let http2SecureServer: Http2SecureServer; + + http2Server = createServer(); + http2Server = createServer(serverOptions); + http2Server = createServer(onRequestHandler); + http2Server = createServer(serverOptions, onRequestHandler); + + http2SecureServer = createSecureServer(); + http2SecureServer = createSecureServer(secureServerOptions); + http2SecureServer = createSecureServer(onRequestHandler); + http2SecureServer = createSecureServer(secureServerOptions, onRequestHandler); + + const clientSessionOptions: ClientSessionOptions = { + maxDeflateDynamicTableSize: 0, + maxReservedRemoteStreams: 0, + maxSendHeaderBlockLength: 0, + paddingStrategy: 0, + peerMaxConcurrentStreams: 0, + selectPadding: (frameLen: number, maxFrameLen: number) => 0, + settings + }; + // tslint:disable-next-line prefer-object-spread (ts2.1 feature) + const secureClientSessionOptions: SecureClientSessionOptions = Object.assign({}, clientSessionOptions); + secureClientSessionOptions.ca = ''; + const onConnectHandler = (session: Http2Session, socket: Socket) => {}; + + const serverHttp2Session: ServerHttp2Session = {} as any; + + serverHttp2Session.altsvc('', ''); + serverHttp2Session.altsvc('', 0); + serverHttp2Session.altsvc('', new URL('')); + serverHttp2Session.altsvc('', { origin: '' }); + serverHttp2Session.altsvc('', { origin: 0 }); + serverHttp2Session.altsvc('', { origin: new URL('') }); + + let clientHttp2Session: ClientHttp2Session; + + clientHttp2Session = connect(''); + clientHttp2Session = connect('', onConnectHandler); + clientHttp2Session = connect('', clientSessionOptions); + clientHttp2Session = connect('', clientSessionOptions, onConnectHandler); + clientHttp2Session = connect('', secureClientSessionOptions); + clientHttp2Session = connect('', secureClientSessionOptions, onConnectHandler); + clientHttp2Session.on('altsvc', (alt: string, origin: string, number: number) => {}); + + settings = getDefaultSettings(); + settings = getPackedSettings(settings); + settings = getUnpackedSettings(Buffer.from([])); + settings = getUnpackedSettings(Uint8Array.from([])); +} + +// constants +{ + const consts = constants; + let num: number; + let str: string; + num = consts.NGHTTP2_SESSION_SERVER; + num = consts.NGHTTP2_SESSION_CLIENT; + num = consts.NGHTTP2_STREAM_STATE_IDLE; + num = consts.NGHTTP2_STREAM_STATE_OPEN; + num = consts.NGHTTP2_STREAM_STATE_RESERVED_LOCAL; + num = consts.NGHTTP2_STREAM_STATE_RESERVED_REMOTE; + num = consts.NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL; + num = consts.NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE; + num = consts.NGHTTP2_STREAM_STATE_CLOSED; + num = consts.NGHTTP2_NO_ERROR; + num = consts.NGHTTP2_PROTOCOL_ERROR; + num = consts.NGHTTP2_INTERNAL_ERROR; + num = consts.NGHTTP2_FLOW_CONTROL_ERROR; + num = consts.NGHTTP2_SETTINGS_TIMEOUT; + num = consts.NGHTTP2_STREAM_CLOSED; + num = consts.NGHTTP2_FRAME_SIZE_ERROR; + num = consts.NGHTTP2_REFUSED_STREAM; + num = consts.NGHTTP2_CANCEL; + num = consts.NGHTTP2_COMPRESSION_ERROR; + num = consts.NGHTTP2_CONNECT_ERROR; + num = consts.NGHTTP2_ENHANCE_YOUR_CALM; + num = consts.NGHTTP2_INADEQUATE_SECURITY; + num = consts.NGHTTP2_HTTP_1_1_REQUIRED; + num = consts.NGHTTP2_ERR_FRAME_SIZE_ERROR; + num = consts.NGHTTP2_FLAG_NONE; + num = consts.NGHTTP2_FLAG_END_STREAM; + num = consts.NGHTTP2_FLAG_END_HEADERS; + num = consts.NGHTTP2_FLAG_ACK; + num = consts.NGHTTP2_FLAG_PADDED; + num = consts.NGHTTP2_FLAG_PRIORITY; + num = consts.DEFAULT_SETTINGS_HEADER_TABLE_SIZE; + num = consts.DEFAULT_SETTINGS_ENABLE_PUSH; + num = consts.DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE; + num = consts.DEFAULT_SETTINGS_MAX_FRAME_SIZE; + num = consts.MAX_MAX_FRAME_SIZE; + num = consts.MIN_MAX_FRAME_SIZE; + num = consts.MAX_INITIAL_WINDOW_SIZE; + num = consts.NGHTTP2_DEFAULT_WEIGHT; + num = consts.NGHTTP2_SETTINGS_HEADER_TABLE_SIZE; + num = consts.NGHTTP2_SETTINGS_ENABLE_PUSH; + num = consts.NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; + num = consts.NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; + num = consts.NGHTTP2_SETTINGS_MAX_FRAME_SIZE; + num = consts.NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE; + num = consts.PADDING_STRATEGY_NONE; + num = consts.PADDING_STRATEGY_MAX; + num = consts.PADDING_STRATEGY_CALLBACK; + num = consts.HTTP_STATUS_CONTINUE; + num = consts.HTTP_STATUS_SWITCHING_PROTOCOLS; + num = consts.HTTP_STATUS_PROCESSING; + num = consts.HTTP_STATUS_OK; + num = consts.HTTP_STATUS_CREATED; + num = consts.HTTP_STATUS_ACCEPTED; + num = consts.HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION; + num = consts.HTTP_STATUS_NO_CONTENT; + num = consts.HTTP_STATUS_RESET_CONTENT; + num = consts.HTTP_STATUS_PARTIAL_CONTENT; + num = consts.HTTP_STATUS_MULTI_STATUS; + num = consts.HTTP_STATUS_ALREADY_REPORTED; + num = consts.HTTP_STATUS_IM_USED; + num = consts.HTTP_STATUS_MULTIPLE_CHOICES; + num = consts.HTTP_STATUS_MOVED_PERMANENTLY; + num = consts.HTTP_STATUS_FOUND; + num = consts.HTTP_STATUS_SEE_OTHER; + num = consts.HTTP_STATUS_NOT_MODIFIED; + num = consts.HTTP_STATUS_USE_PROXY; + num = consts.HTTP_STATUS_TEMPORARY_REDIRECT; + num = consts.HTTP_STATUS_PERMANENT_REDIRECT; + num = consts.HTTP_STATUS_BAD_REQUEST; + num = consts.HTTP_STATUS_UNAUTHORIZED; + num = consts.HTTP_STATUS_PAYMENT_REQUIRED; + num = consts.HTTP_STATUS_FORBIDDEN; + num = consts.HTTP_STATUS_NOT_FOUND; + num = consts.HTTP_STATUS_METHOD_NOT_ALLOWED; + num = consts.HTTP_STATUS_NOT_ACCEPTABLE; + num = consts.HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED; + num = consts.HTTP_STATUS_REQUEST_TIMEOUT; + num = consts.HTTP_STATUS_CONFLICT; + num = consts.HTTP_STATUS_GONE; + num = consts.HTTP_STATUS_LENGTH_REQUIRED; + num = consts.HTTP_STATUS_PRECONDITION_FAILED; + num = consts.HTTP_STATUS_PAYLOAD_TOO_LARGE; + num = consts.HTTP_STATUS_URI_TOO_LONG; + num = consts.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE; + num = consts.HTTP_STATUS_RANGE_NOT_SATISFIABLE; + num = consts.HTTP_STATUS_EXPECTATION_FAILED; + num = consts.HTTP_STATUS_TEAPOT; + num = consts.HTTP_STATUS_MISDIRECTED_REQUEST; + num = consts.HTTP_STATUS_UNPROCESSABLE_ENTITY; + num = consts.HTTP_STATUS_LOCKED; + num = consts.HTTP_STATUS_FAILED_DEPENDENCY; + num = consts.HTTP_STATUS_UNORDERED_COLLECTION; + num = consts.HTTP_STATUS_UPGRADE_REQUIRED; + num = consts.HTTP_STATUS_PRECONDITION_REQUIRED; + num = consts.HTTP_STATUS_TOO_MANY_REQUESTS; + num = consts.HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE; + num = consts.HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS; + num = consts.HTTP_STATUS_INTERNAL_SERVER_ERROR; + num = consts.HTTP_STATUS_NOT_IMPLEMENTED; + num = consts.HTTP_STATUS_BAD_GATEWAY; + num = consts.HTTP_STATUS_SERVICE_UNAVAILABLE; + num = consts.HTTP_STATUS_GATEWAY_TIMEOUT; + num = consts.HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED; + num = consts.HTTP_STATUS_VARIANT_ALSO_NEGOTIATES; + num = consts.HTTP_STATUS_INSUFFICIENT_STORAGE; + num = consts.HTTP_STATUS_LOOP_DETECTED; + num = consts.HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED; + num = consts.HTTP_STATUS_NOT_EXTENDED; + num = consts.HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED; + str = consts.HTTP2_HEADER_STATUS; + str = consts.HTTP2_HEADER_METHOD; + str = consts.HTTP2_HEADER_AUTHORITY; + str = consts.HTTP2_HEADER_SCHEME; + str = consts.HTTP2_HEADER_PATH; + str = consts.HTTP2_HEADER_ACCEPT_CHARSET; + str = consts.HTTP2_HEADER_ACCEPT_ENCODING; + str = consts.HTTP2_HEADER_ACCEPT_LANGUAGE; + str = consts.HTTP2_HEADER_ACCEPT_RANGES; + str = consts.HTTP2_HEADER_ACCEPT; + str = consts.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN; + str = consts.HTTP2_HEADER_AGE; + str = consts.HTTP2_HEADER_ALLOW; + str = consts.HTTP2_HEADER_AUTHORIZATION; + str = consts.HTTP2_HEADER_CACHE_CONTROL; + str = consts.HTTP2_HEADER_CONNECTION; + str = consts.HTTP2_HEADER_CONTENT_DISPOSITION; + str = consts.HTTP2_HEADER_CONTENT_ENCODING; + str = consts.HTTP2_HEADER_CONTENT_LANGUAGE; + str = consts.HTTP2_HEADER_CONTENT_LENGTH; + str = consts.HTTP2_HEADER_CONTENT_LOCATION; + str = consts.HTTP2_HEADER_CONTENT_MD5; + str = consts.HTTP2_HEADER_CONTENT_RANGE; + str = consts.HTTP2_HEADER_CONTENT_TYPE; + str = consts.HTTP2_HEADER_COOKIE; + str = consts.HTTP2_HEADER_DATE; + str = consts.HTTP2_HEADER_ETAG; + str = consts.HTTP2_HEADER_EXPECT; + str = consts.HTTP2_HEADER_EXPIRES; + str = consts.HTTP2_HEADER_FROM; + str = consts.HTTP2_HEADER_HOST; + str = consts.HTTP2_HEADER_IF_MATCH; + str = consts.HTTP2_HEADER_IF_MODIFIED_SINCE; + str = consts.HTTP2_HEADER_IF_NONE_MATCH; + str = consts.HTTP2_HEADER_IF_RANGE; + str = consts.HTTP2_HEADER_IF_UNMODIFIED_SINCE; + str = consts.HTTP2_HEADER_LAST_MODIFIED; + str = consts.HTTP2_HEADER_LINK; + str = consts.HTTP2_HEADER_LOCATION; + str = consts.HTTP2_HEADER_MAX_FORWARDS; + str = consts.HTTP2_HEADER_PREFER; + str = consts.HTTP2_HEADER_PROXY_AUTHENTICATE; + str = consts.HTTP2_HEADER_PROXY_AUTHORIZATION; + str = consts.HTTP2_HEADER_RANGE; + str = consts.HTTP2_HEADER_REFERER; + str = consts.HTTP2_HEADER_REFRESH; + str = consts.HTTP2_HEADER_RETRY_AFTER; + str = consts.HTTP2_HEADER_SERVER; + str = consts.HTTP2_HEADER_SET_COOKIE; + str = consts.HTTP2_HEADER_STRICT_TRANSPORT_SECURITY; + str = consts.HTTP2_HEADER_TRANSFER_ENCODING; + str = consts.HTTP2_HEADER_TE; + str = consts.HTTP2_HEADER_UPGRADE; + str = consts.HTTP2_HEADER_USER_AGENT; + str = consts.HTTP2_HEADER_VARY; + str = consts.HTTP2_HEADER_VIA; + str = consts.HTTP2_HEADER_WWW_AUTHENTICATE; + str = consts.HTTP2_HEADER_HTTP2_SETTINGS; + str = consts.HTTP2_HEADER_KEEP_ALIVE; + str = consts.HTTP2_HEADER_PROXY_CONNECTION; + str = consts.HTTP2_METHOD_ACL; + str = consts.HTTP2_METHOD_BASELINE_CONTROL; + str = consts.HTTP2_METHOD_BIND; + str = consts.HTTP2_METHOD_CHECKIN; + str = consts.HTTP2_METHOD_CHECKOUT; + str = consts.HTTP2_METHOD_CONNECT; + str = consts.HTTP2_METHOD_COPY; + str = consts.HTTP2_METHOD_DELETE; + str = consts.HTTP2_METHOD_GET; + str = consts.HTTP2_METHOD_HEAD; + str = consts.HTTP2_METHOD_LABEL; + str = consts.HTTP2_METHOD_LINK; + str = consts.HTTP2_METHOD_LOCK; + str = consts.HTTP2_METHOD_MERGE; + str = consts.HTTP2_METHOD_MKACTIVITY; + str = consts.HTTP2_METHOD_MKCALENDAR; + str = consts.HTTP2_METHOD_MKCOL; + str = consts.HTTP2_METHOD_MKREDIRECTREF; + str = consts.HTTP2_METHOD_MKWORKSPACE; + str = consts.HTTP2_METHOD_MOVE; + str = consts.HTTP2_METHOD_OPTIONS; + str = consts.HTTP2_METHOD_ORDERPATCH; + str = consts.HTTP2_METHOD_PATCH; + str = consts.HTTP2_METHOD_POST; + str = consts.HTTP2_METHOD_PRI; + str = consts.HTTP2_METHOD_PROPFIND; + str = consts.HTTP2_METHOD_PROPPATCH; + str = consts.HTTP2_METHOD_PUT; + str = consts.HTTP2_METHOD_REBIND; + str = consts.HTTP2_METHOD_REPORT; + str = consts.HTTP2_METHOD_SEARCH; + str = consts.HTTP2_METHOD_TRACE; + str = consts.HTTP2_METHOD_UNBIND; + str = consts.HTTP2_METHOD_UNCHECKOUT; + str = consts.HTTP2_METHOD_UNLINK; + str = consts.HTTP2_METHOD_UNLOCK; + str = consts.HTTP2_METHOD_UPDATE; + str = consts.HTTP2_METHOD_UPDATEREDIRECTREF; + str = consts.HTTP2_METHOD_VERSION_CONTROL; +} diff --git a/types/node/test/perf_hooks.ts b/types/node/test/perf_hooks.ts new file mode 100644 index 0000000000..8d4c4e23d2 --- /dev/null +++ b/types/node/test/perf_hooks.ts @@ -0,0 +1,42 @@ +import { performance, monitorEventLoopDelay, PerformanceObserverCallback, PerformanceObserver } from 'perf_hooks'; + +performance.mark('start'); +( + () => {} +)(); +performance.mark('end'); + +const { duration } = performance.getEntriesByName('discover')[0]; +const timeOrigin = performance.timeOrigin; + +const performanceObserverCallback: PerformanceObserverCallback = (list, obs) => { + const { + duration, + entryType, + name, + startTime, + } = list.getEntries()[0]; + obs.disconnect(); + performance.clearFunctions(); +}; +const obs = new PerformanceObserver(performanceObserverCallback); +obs.observe({ + entryTypes: ['function'], + buffered: true, +}); + +const monitor = monitorEventLoopDelay({ + resolution: 42, +}); + +monitor.enable(); +monitor.reset(); +monitor.disable(); +const perc: number = monitor.percentile(99); +const perc2: number | undefined = monitor.percentiles.get(42); + +const min: number = monitor.min; +const max: number = monitor.max; +const mean: number = monitor.mean; +const stddev: number = monitor.stddev; +const exceeds: number = monitor.exceeds; diff --git a/types/node/test/repl.ts b/types/node/test/repl.ts new file mode 100644 index 0000000000..b536cd4dc1 --- /dev/null +++ b/types/node/test/repl.ts @@ -0,0 +1,73 @@ +import { start, Recoverable } from "repl"; +import { Context } from "vm"; + +{ + let server = start(); + let _boolean: boolean; + const _ctx: Context = {}; + + server.setupHistory('hurr/durr', (err, repl) => { + }); + + server = server.addListener("exit", () => { }); + server = server.addListener("reset", () => { }); + + _boolean = server.emit("exit", () => { }); + _boolean = server.emit("reset", _ctx); + + server = server.on("exit", () => { }); + server = server.on("reset", () => { }); + + server = server.once("exit", () => { }); + server = server.once("reset", () => { }); + + server = server.prependListener("exit", () => { }); + server = server.prependListener("reset", () => { }); + + server = server.prependOnceListener("exit", () => { }); + server = server.prependOnceListener("reset", () => { }); + + server.outputStream.write("test"); + const line = server.inputStream.read(); + + server.clearBufferedCommand(); + server.displayPrompt(); + server.displayPrompt(true); + server.defineCommand("cmd", function(text) { + // $ExpectType string + text; + // $ExpectType REPLServer + this; + }); + server.defineCommand("cmd", { + help: "", + action(text) { + // $ExpectType string + text; + // $ExpectType REPLServer + this; + } + }); + + start({ + eval() { + // $ExpectType REPLServer + this; + }, + writer() { + // $ExpectType REPLServer + this; + return ""; + } + }); + + function test() { + throw new Recoverable(new Error("test")); + } + + server.context['key0'] = 1; + server.context['key1'] = ""; + server.context['key2'] = true; + server.context['key3'] = []; + server.context['key4'] = {}; +} diff --git a/types/node/test/stream.ts b/types/node/test/stream.ts new file mode 100644 index 0000000000..6fd656e61c --- /dev/null +++ b/types/node/test/stream.ts @@ -0,0 +1,194 @@ +import { Readable, Writable, Transform, finished, pipeline, Duplex } from "stream"; +import { promisify } from "util"; +import { createReadStream, createWriteStream } from "fs"; +import { createGzip, constants } from "zlib"; +import { ok as assert } from 'assert'; + +// Simplified constructors +function simplified_stream_ctor_test() { + new Readable({ + read(size) { + // $ExpectType Readable + this; + // $ExpectType number + size; + }, + destroy(error, cb) { + // $ExpectType Error | null + error; + // $ExpectType (error: Error | null) => void + cb; + } + }); + + new Writable({ + write(chunk, enc, cb) { + // $ExpectType Writable + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + writev(chunks, cb) { + // $ExpectType Writable + this; + // $ExpectType { chunk: any; encoding: string; }[] + chunks; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + destroy(error, cb) { + // $ExpectType Writable + this; + // $ExpectType Error | null + error; + // $ExpectType (error: Error | null) => void + cb; + }, + final(cb) { + // $ExpectType Writable + this; + // $ExpectType (error?: Error | null | undefined) => void + cb; + } + }); + + new Duplex({ + read(size) { + // $ExpectType Duplex + this; + // $ExpectType number + size; + }, + write(chunk, enc, cb) { + // $ExpectType Duplex + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + writev(chunks, cb) { + // $ExpectType Duplex + this; + // $ExpectType { chunk: any; encoding: string; }[] + chunks; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + destroy(error, cb) { + // $ExpectType Duplex + this; + // $ExpectType Error | null + error; + // $ExpectType (error: Error | null) => void + cb; + }, + final(cb) { + // $ExpectType Duplex + this; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + readableObjectMode: true, + writableObjectMode: true + }); + + new Transform({ + read(size) { + // $ExpectType Transform + this; + // $ExpectType number + size; + }, + write(chunk, enc, cb) { + // $ExpectType Transform + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + writev(chunks, cb) { + // $ExpectType Transform + this; + // $ExpectType { chunk: any; encoding: string; }[] + chunks; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + destroy(error, cb) { + // $ExpectType Transform + this; + // $ExpectType Error | null + error; + // $ExpectType (error: Error | null) => void + cb; + }, + final(cb) { + // $ExpectType Transform + this; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + transform(chunk, enc, cb) { + // $ExpectType Transform + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType TransformCallback + cb; + }, + flush(cb) { + // $ExpectType TransformCallback + cb; + }, + allowHalfOpen: true, + readableObjectMode: true, + writableObjectMode: true + }); +} + +function streamPipelineFinished() { + const cancel = finished(process.stdin, (err?: Error) => {}); + cancel(); + + pipeline(process.stdin, process.stdout, (err?: Error) => {}); +} + +async function asyncStreamPipelineFinished() { + const fin = promisify(finished); + await fin(process.stdin); + + const pipe = promisify(pipeline); + await pipe(process.stdin, process.stdout); +} + +// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options +function stream_readable_pipe_test() { + const rs = createReadStream(Buffer.from('file.txt')); + const r = createReadStream('file.txt'); + const z = createGzip({ finishFlush: constants.Z_FINISH }); + const w = createWriteStream('file.txt.gz'); + + assert(typeof z.bytesRead === 'number'); + assert(typeof r.bytesRead === 'number'); + assert(typeof r.path === 'string'); + assert(rs.path instanceof Buffer); + + r.pipe(z).pipe(w); + + z.flush(); + r.close(); + z.close(); + rs.close(); +} diff --git a/types/node/test/tls.ts b/types/node/test/tls.ts new file mode 100644 index 0000000000..807e41393f --- /dev/null +++ b/types/node/test/tls.ts @@ -0,0 +1,206 @@ +import { createSecureContext, SecureContext, ConnectionOptions, connect, getCiphers, DEFAULT_ECDH_CURVE, createServer, TLSSocket } from "tls"; + +{ + const ctx: SecureContext = createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", + }); + const blah = ctx.context; + + const connOpts: ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + const tlsSocket = connect(connOpts); + + const ciphers: string[] = getCiphers(); + const curve: string = DEFAULT_ECDH_CURVE; +} + +{ + let _server = createServer({}); + let _boolean: boolean; + const _func1 = (err: Error, resp: Buffer) => { }; + const _func2 = (err: Error, sessionData: any) => { }; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + */ + + _server = _server.addListener("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: TLSSocket = tlsSocket; + }); + _server = _server.addListener("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.addListener("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.addListener("secureConnection", (tlsSocket) => { + const _tlsSocket: TLSSocket = tlsSocket; + }); + + const _err: Error = new Error(); + const _tlsSocket: TLSSocket = connect(1); + const _any: any = 1; + const _func: Function = () => {}; + const _buffer: Buffer = Buffer.from('a'); + _boolean = _server.emit("tlsClientError", _err, _tlsSocket); + _boolean = _server.emit("newSession", _any, _any, _func1); + _boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func); + _boolean = _server.emit("resumeSession", _any, _func2); + _boolean = _server.emit("secureConnection", _tlsSocket); + + _server = _server.on("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: TLSSocket = tlsSocket; + }); + _server = _server.on("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.on("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.on("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.on("secureConnection", (tlsSocket) => { + const _tlsSocket: TLSSocket = tlsSocket; + }); + + _server = _server.once("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: TLSSocket = tlsSocket; + }); + _server = _server.once("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.once("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.once("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.once("secureConnection", (tlsSocket) => { + const _tlsSocket: TLSSocket = tlsSocket; + }); + + _server = _server.prependListener("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: TLSSocket = tlsSocket; + }); + _server = _server.prependListener("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.prependListener("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.prependListener("secureConnection", (tlsSocket) => { + const _tlsSocket: TLSSocket = tlsSocket; + }); + + _server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: TLSSocket = tlsSocket; + }); + _server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.prependOnceListener("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { + const _tlsSocket: TLSSocket = tlsSocket; + }); + + // close callback parameter is optional + _server = _server.close(); + + // close callback parameter doesn't specify any arguments, so any + // function is acceptable + _server = _server.close(() => { }); + _server = _server.close((...args: any[]) => { }); +} + +{ + let socket = connect({ + }); + let _boolean: boolean; + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + */ + + socket = socket.addListener("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + socket = socket.addListener("secureConnect", () => { }); + + const _buffer: Buffer = Buffer.from(""); + _boolean = socket.emit("OCSPResponse", _buffer); + _boolean = socket.emit("secureConnect"); + + socket = socket.on("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + socket = socket.on("secureConnect", () => { }); + + socket = socket.once("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + socket = socket.once("secureConnect", () => { }); + + socket = socket.prependListener("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + socket = socket.prependListener("secureConnect", () => { }); + + socket = socket.prependOnceListener("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + socket = socket.prependOnceListener("secureConnect", () => { }); + + socket.once('session', (buff: Buffer) => {}); +} diff --git a/types/node/test/zlib.ts b/types/node/test/zlib.ts new file mode 100644 index 0000000000..d76803a919 --- /dev/null +++ b/types/node/test/zlib.ts @@ -0,0 +1,120 @@ +import { + deflate, + inflate, + inflateSync, + deflateSync, + deflateRaw, + inflateRaw, + inflateRawSync, + deflateRawSync, + gunzip, + gzip, + gunzipSync, + gzipSync, + unzip, + unzipSync, + constants, + createBrotliCompress, + BrotliOptions, + createBrotliDecompress, + BrotliCompress, + BrotliDecompress, + brotliCompress, + brotliDecompressSync, + brotliDecompress, +} from "zlib"; + +const compressMe = new Buffer("some data"); +const compressMeString = "compress me!"; + +// Deflate / Inflate + +deflate(compressMe, (err: Error | null, result: Buffer) => inflate(result, (err: Error | null, result: Buffer) => result)); +deflate( + compressMe, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => inflate( + result, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => result + ) +); +deflate(compressMeString, (err: Error | null, result: Buffer) => inflate(result, (err: Error | null, result: Buffer) => result)); +deflate( + compressMeString, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => inflate( + result, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => result + ) +); +const inflated = inflateSync(deflateSync(compressMe)); +const inflatedString = inflateSync(deflateSync(compressMeString)); + +deflateRaw(compressMe, (err: Error | null, result: Buffer) => inflateRaw(result, (err: Error | null, result: Buffer) => result)); +deflateRaw( + compressMe, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => inflateRaw( + result, { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => result + ) +); +deflateRaw(compressMeString, (err: Error | null, result: Buffer) => inflateRaw(result, (err: Error | null, result: Buffer) => result)); +deflateRaw( + compressMeString, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => inflateRaw(result, { finishFlush: constants.Z_SYNC_FLUSH }, (err: Error | null, result: Buffer) => result), +); +const inflatedRaw: Buffer = inflateRawSync(deflateRawSync(compressMe)); +const inflatedRawString: Buffer = inflateRawSync(deflateRawSync(compressMeString)); + +// gzip + +gzip(compressMe, (err: Error | null, result: Buffer) => gunzip(result, (err: Error | null, result: Buffer) => result)); +gzip( + compressMe, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => gunzip( + result, { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => result + ) +); +const gunzipped: Buffer = gunzipSync(gzipSync(compressMe)); + +unzip(compressMe, (err: Error | null, result: Buffer) => result); +unzip(compressMe, { finishFlush: constants.Z_SYNC_FLUSH }, (err: Error | null, result: Buffer) => result); +const unzipped: Buffer = unzipSync(compressMe); + +const bOpts: BrotliOptions = { + chunkSize: 123, + flush: 123123, + params: { + [constants.BROTLI_PARAM_LARGE_WINDOW]: true, + [constants.BROTLI_PARAM_NPOSTFIX]: 123, + }, + finishFlush: 123123, +}; + +// brotli + +let bC: BrotliCompress = createBrotliCompress(); +bC = createBrotliCompress(bOpts); +let bD: BrotliDecompress = createBrotliDecompress(); +bD = createBrotliDecompress(bOpts); +// gzip + +brotliCompress(compressMe, (err: Error | null, result: Buffer) => gunzip(result, (err: Error | null, result: Buffer) => result)); +brotliCompress( + compressMe, + { finishFlush: constants.BROTLI_OPERATION_FINISH }, + (err: Error | null, result: Buffer) => gunzip( + result, { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => result + ) +); +const brotlied: Buffer = brotliDecompressSync(brotliDecompressSync(compressMe)); + +brotliDecompress(compressMe, (err: Error | null, result: Buffer) => result); +brotliDecompress(compressMe, { finishFlush: constants.BROTLI_OPERATION_FINISH }, (err: Error | null, result: Buffer) => result); diff --git a/types/node/tls.d.ts b/types/node/tls.d.ts index e7222b5a5b..ef9a7bd4b0 100644 --- a/types/node/tls.d.ts +++ b/types/node/tls.d.ts @@ -218,26 +218,32 @@ declare module "tls" { addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "OCSPResponse", response: Buffer): boolean; emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "OCSPResponse", listener: (response: Buffer) => void): this; on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "OCSPResponse", listener: (response: Buffer) => void): this; once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; } interface TlsOptions extends SecureContextOptions { diff --git a/types/node/ts3.1/node-tests.ts b/types/node/ts3.1/node-tests.ts deleted file mode 100644 index 18db498871..0000000000 --- a/types/node/ts3.1/node-tests.ts +++ /dev/null @@ -1,2 +0,0 @@ -// tslint:disable-next-line:no-bad-reference -import "../node-tests"; diff --git a/types/node/ts3.2/globals.d.ts b/types/node/ts3.2/globals.d.ts new file mode 100644 index 0000000000..c14a1a36b1 --- /dev/null +++ b/types/node/ts3.2/globals.d.ts @@ -0,0 +1,8 @@ +// tslint:disable-next-line:no-bad-reference +/// + +declare namespace NodeJS { + interface HRTime { + bigint(): bigint; + } +} diff --git a/types/node/ts3.1/index.d.ts b/types/node/ts3.2/index.d.ts similarity index 66% rename from types/node/ts3.1/index.d.ts rename to types/node/ts3.2/index.d.ts index be36602300..ce7709bc7c 100644 --- a/types/node/ts3.1/index.d.ts +++ b/types/node/ts3.2/index.d.ts @@ -1,18 +1,20 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.1. +// NOTE: These definitions support NodeJS and TypeScript 3.2. // NOTE: TypeScript version-specific augmentations can be found in the following paths: // - ~/base.d.ts - Shared definitions common to all TypeScript versions // - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 +// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 // Reference required types from the default lib: /// -/// +/// /// +/// // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: // tslint:disable-next-line:no-bad-reference /// -// TypeScript 3.1-specific augmentations: +// TypeScript 3.2-specific augmentations: /// +/// diff --git a/types/node/ts3.2/node-tests.ts b/types/node/ts3.2/node-tests.ts new file mode 100644 index 0000000000..3f64e22e81 --- /dev/null +++ b/types/node/ts3.2/node-tests.ts @@ -0,0 +1,11 @@ +// tslint:disable-next-line:no-bad-reference +import "../node-tests"; + +////////////////////////////////////////////////////////// +/// Global Tests : https://nodejs.org/api/global.html /// +////////////////////////////////////////////////////////// +{ + { + const hrtimeBigint: bigint = process.hrtime.bigint(); + } +} diff --git a/types/node/ts3.1/tsconfig.json b/types/node/ts3.2/tsconfig.json similarity index 100% rename from types/node/ts3.1/tsconfig.json rename to types/node/ts3.2/tsconfig.json diff --git a/types/node/ts3.1/tslint.json b/types/node/ts3.2/tslint.json similarity index 100% rename from types/node/ts3.1/tslint.json rename to types/node/ts3.2/tslint.json diff --git a/types/node/ts3.1/util.d.ts b/types/node/ts3.2/util.d.ts similarity index 100% rename from types/node/ts3.1/util.d.ts rename to types/node/ts3.2/util.d.ts diff --git a/types/node/tsconfig.json b/types/node/tsconfig.json index e16d482b6f..831c9861f0 100644 --- a/types/node/tsconfig.json +++ b/types/node/tsconfig.json @@ -43,16 +43,24 @@ "worker_threads.d.ts", "zlib.d.ts", "node-tests.ts", - "test/http.ts", - "test/readline.ts", - "test/global.ts", - "test/worker_threads.ts", - "test/util.ts", - "test/net.ts", - "test/dgram.ts", + "test/buffer.ts", + "test/child_process.ts", + "test/crypto.ts", + "test/dgram.ts", + "test/global.ts", + "test/http.ts", + "test/http2.ts", + "test/net.ts", + "test/perf_hooks.ts", + "test/readline.ts", + "test/stream.ts", "test/tty.ts", - "test/crypto.ts" + "test/util.ts", + "test/repl.ts", + "test/worker_threads.ts", + "test/zlib.ts", + "test/tls.ts" ], "compilerOptions": { "module": "commonjs", diff --git a/types/node/v0/index.d.ts b/types/node/v0/index.d.ts index 1f29bbcc10..2190660451 100644 --- a/types/node/v0/index.d.ts +++ b/types/node/v0/index.d.ts @@ -531,6 +531,7 @@ declare module "http" { write(str: string, encoding?: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; + readonly path: string; write(chunk: any, encoding?: string): void; abort(): void; setTimeout(timeout: number, callback?: Function): void; diff --git a/types/node/v10/buffer.d.ts b/types/node/v10/buffer.d.ts index 1d618f2c4b..0fe668b17d 100644 --- a/types/node/v10/buffer.d.ts +++ b/types/node/v10/buffer.d.ts @@ -2,6 +2,10 @@ declare module "buffer" { export const INSPECT_MAX_BYTES: number; const BuffType: typeof Buffer; + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + + export function transcode(source: Buffer | Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { /** @deprecated since v6.0.0, use Buffer.allocUnsafeSlow() */ new(size: number): Buffer; diff --git a/types/node/v10/child_process.d.ts b/types/node/v10/child_process.d.ts index c8d20b8249..1114247bee 100644 --- a/types/node/v10/child_process.d.ts +++ b/types/node/v10/child_process.d.ts @@ -293,7 +293,7 @@ declare module "child_process" { stderr: T; status: number; signal: string; - error: Error; + error?: Error; } function spawnSync(command: string): SpawnSyncReturns; function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; diff --git a/types/node/v10/globals.d.ts b/types/node/v10/globals.d.ts index 23cab2f1f8..534c03240d 100644 --- a/types/node/v10/globals.d.ts +++ b/types/node/v10/globals.d.ts @@ -696,6 +696,10 @@ declare namespace NodeJS { destroy(error?: Error): void; } + interface HRTime { + (time?: [number, number]): [number, number]; + } + interface Process extends EventEmitter { stdout: WriteStream; stderr: WriteStream; @@ -766,7 +770,7 @@ declare namespace NodeJS { release: ProcessRelease; umask(mask?: number): number; uptime(): number; - hrtime(time?: [number, number]): [number, number]; + hrtime: HRTime; domain: Domain; // Worker diff --git a/types/node/v10/http.d.ts b/types/node/v10/http.d.ts index 5e1ebcc127..b55ab680cf 100644 --- a/types/node/v10/http.d.ts +++ b/types/node/v10/http.d.ts @@ -154,6 +154,7 @@ declare module "http" { constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + readonly path: string; abort(): void; onSocket(socket: net.Socket): void; setTimeout(timeout: number, callback?: () => void): this; diff --git a/types/node/v10/index.d.ts b/types/node/v10/index.d.ts index a237502039..65f057b262 100644 --- a/types/node/v10/index.d.ts +++ b/types/node/v10/index.d.ts @@ -33,6 +33,7 @@ // Jeremie Rodriguez // Samuel Ainsworth // Kyle Uehlein +// Jordi Oliveras Rovira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // NOTE: These definitions support NodeJS and TypeScript 3.1. diff --git a/types/node/v10/node-tests.ts b/types/node/v10/node-tests.ts index 3614c30f97..6602ce7af2 100644 --- a/types/node/v10/node-tests.ts +++ b/types/node/v10/node-tests.ts @@ -35,7 +35,7 @@ import * as trace_events from "trace_events"; import Module = require("module"); // Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; +import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -47,6 +47,7 @@ import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buff x.children.push(y); x.parent = require.main; require.main = y; + const hrtimeArray: [number, number] = process.hrtime(); } } @@ -632,6 +633,15 @@ function bufferTests() { const buffer = new Buffer('123'); const octets = new Uint8Array(buffer.buffer); } + + // Buffer module, transcode function + { + transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer + + const source: TranscodeEncoding = 'utf8'; + const target: TranscodeEncoding = 'ascii'; + transcode(Buffer.from('€'), source, target); // $ExpectType Buffer + } } //////////////////////////////////////////////////// diff --git a/types/node/v10/package.json b/types/node/v10/package.json index c1f0c68752..cda6cc6dc8 100644 --- a/types/node/v10/package.json +++ b/types/node/v10/package.json @@ -2,10 +2,10 @@ "private": true, "types": "index", "typesVersions": { - ">=3.1.0-0": { + ">=3.2.0-0": { "*": [ - "ts3.1/*" + "ts3.2/*" ] } } -} \ No newline at end of file +} diff --git a/types/node/v10/ts3.1/node-tests.ts b/types/node/v10/ts3.1/node-tests.ts deleted file mode 100644 index 18db498871..0000000000 --- a/types/node/v10/ts3.1/node-tests.ts +++ /dev/null @@ -1,2 +0,0 @@ -// tslint:disable-next-line:no-bad-reference -import "../node-tests"; diff --git a/types/node/v10/ts3.2/globals.d.ts b/types/node/v10/ts3.2/globals.d.ts new file mode 100644 index 0000000000..c14a1a36b1 --- /dev/null +++ b/types/node/v10/ts3.2/globals.d.ts @@ -0,0 +1,8 @@ +// tslint:disable-next-line:no-bad-reference +/// + +declare namespace NodeJS { + interface HRTime { + bigint(): bigint; + } +} diff --git a/types/node/v10/ts3.1/index.d.ts b/types/node/v10/ts3.2/index.d.ts similarity index 66% rename from types/node/v10/ts3.1/index.d.ts rename to types/node/v10/ts3.2/index.d.ts index be36602300..ce7709bc7c 100644 --- a/types/node/v10/ts3.1/index.d.ts +++ b/types/node/v10/ts3.2/index.d.ts @@ -1,18 +1,20 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.1. +// NOTE: These definitions support NodeJS and TypeScript 3.2. // NOTE: TypeScript version-specific augmentations can be found in the following paths: // - ~/base.d.ts - Shared definitions common to all TypeScript versions // - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 +// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 // Reference required types from the default lib: /// -/// +/// /// +/// // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: // tslint:disable-next-line:no-bad-reference /// -// TypeScript 3.1-specific augmentations: +// TypeScript 3.2-specific augmentations: /// +/// diff --git a/types/node/v10/ts3.2/node-tests.ts b/types/node/v10/ts3.2/node-tests.ts new file mode 100644 index 0000000000..3f64e22e81 --- /dev/null +++ b/types/node/v10/ts3.2/node-tests.ts @@ -0,0 +1,11 @@ +// tslint:disable-next-line:no-bad-reference +import "../node-tests"; + +////////////////////////////////////////////////////////// +/// Global Tests : https://nodejs.org/api/global.html /// +////////////////////////////////////////////////////////// +{ + { + const hrtimeBigint: bigint = process.hrtime.bigint(); + } +} diff --git a/types/node/v10/ts3.1/tsconfig.json b/types/node/v10/ts3.2/tsconfig.json similarity index 100% rename from types/node/v10/ts3.1/tsconfig.json rename to types/node/v10/ts3.2/tsconfig.json diff --git a/types/node/v10/ts3.1/tslint.json b/types/node/v10/ts3.2/tslint.json similarity index 100% rename from types/node/v10/ts3.1/tslint.json rename to types/node/v10/ts3.2/tslint.json diff --git a/types/node/v10/ts3.1/util.d.ts b/types/node/v10/ts3.2/util.d.ts similarity index 100% rename from types/node/v10/ts3.1/util.d.ts rename to types/node/v10/ts3.2/util.d.ts diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index f52a8d01f8..279c3cefbf 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -785,6 +785,7 @@ declare module "http" { write(str: string, encoding?: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; + readonly path: string; write(chunk: any, encoding?: string): void; abort(): void; setTimeout(timeout: number, callback?: Function): void; diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 6dd1ad1dc0..f4fa74291c 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -857,6 +857,7 @@ declare module "http" { write(str: string, encoding?: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; + readonly path: string; write(chunk: any, encoding?: string): void; abort(): void; setTimeout(timeout: number, callback?: Function): void; diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index a4fde30a97..611b9b7903 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -8,6 +8,7 @@ // Sebastian Silbermann // Hoàng Văn Khải // Sander Koenders +// Jordi Oliveras Rovira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ @@ -683,6 +684,8 @@ declare module "buffer" { export var INSPECT_MAX_BYTES: number; var BuffType: typeof Buffer; var SlowBuffType: typeof SlowBuffer; + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + export function transcode(source: Buffer, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } @@ -854,6 +857,7 @@ declare module "http" { write(str: string, encoding?: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; + readonly path: string; write(chunk: any, encoding?: string): void; abort(): void; setTimeout(timeout: number, callback?: Function): void; diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index 764dc6e8d0..81c33d9658 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -28,7 +28,7 @@ import * as v8 from "v8"; import * as dns from "dns"; // Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; +import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -448,6 +448,15 @@ function bufferTests() { let buffer = new Buffer('123'); let octets = new Uint8Array(buffer.buffer); } + + // Buffer module, transcode function + { + transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer + + const source: TranscodeEncoding = 'utf8'; + const target: TranscodeEncoding = 'ascii'; + transcode(Buffer.from('€'), source, target); // $ExpectType Buffer + } } diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index 1fac090367..9728ade03f 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -22,6 +22,7 @@ // Hoàng Văn Khải // Lishude // Andrew Makarov +// Jordi Oliveras Rovira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -909,6 +910,8 @@ declare module "buffer" { export var INSPECT_MAX_BYTES: number; var BuffType: typeof Buffer; var SlowBuffType: typeof SlowBuffer; + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + export function transcode(source: Buffer | Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } @@ -1101,6 +1104,7 @@ declare module "http" { constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + readonly path: string; abort(): void; onSocket(socket: net.Socket): void; setTimeout(timeout: number, callback?: () => void): this; @@ -2288,7 +2292,7 @@ declare module "child_process" { stderr: T; status: number; signal: string; - error: Error; + error?: Error; } export function spawnSync(command: string): SpawnSyncReturns; export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; diff --git a/types/node/v8/node-tests.ts b/types/node/v8/node-tests.ts index 76f2ef380e..706b39600a 100644 --- a/types/node/v8/node-tests.ts +++ b/types/node/v8/node-tests.ts @@ -33,7 +33,7 @@ import * as perf_hooks from "perf_hooks"; import Module = require("module"); // Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; +import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -568,6 +568,15 @@ function bufferTests() { let buffer = new Buffer('123'); let octets = new Uint8Array(buffer.buffer); } + + // Buffer module, transcode function + { + transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer + + const source: TranscodeEncoding = 'utf8'; + const target: TranscodeEncoding = 'ascii'; + transcode(Buffer.from('€'), source, target); // $ExpectType Buffer + } } //////////////////////////////////////////////////// diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 220afd9e60..9934b38eb4 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -26,6 +26,7 @@ // Lishude // Andrew Makarov // Eugene Y. Q. Shen +// Jordi Oliveras Rovira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** inspector module types */ @@ -993,6 +994,8 @@ declare module "buffer" { export var INSPECT_MAX_BYTES: number; var BuffType: typeof Buffer; var SlowBuffType: typeof SlowBuffer; + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + export function transcode(source: Buffer | Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } @@ -1186,6 +1189,7 @@ declare module "http" { constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + readonly path: string; abort(): void; onSocket(socket: net.Socket): void; setTimeout(timeout: number, callback?: () => void): this; diff --git a/types/node/v9/node-tests.ts b/types/node/v9/node-tests.ts index e9c4f70ebb..4d0b5407c7 100644 --- a/types/node/v9/node-tests.ts +++ b/types/node/v9/node-tests.ts @@ -33,7 +33,7 @@ import * as perf_hooks from "perf_hooks"; import Module = require("module"); // Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; +import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -594,6 +594,15 @@ function bufferTests() { let buffer = new Buffer('123'); let octets = new Uint8Array(buffer.buffer); } + + // Buffer module, transcode function + { + transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer + + const source: TranscodeEncoding = 'utf8'; + const target: TranscodeEncoding = 'ascii'; + transcode(Buffer.from('€'), source, target); // $ExpectType Buffer + } } //////////////////////////////////////////////////// diff --git a/types/node/zlib.d.ts b/types/node/zlib.d.ts index dff374b8f5..60983fee91 100644 --- a/types/node/zlib.d.ts +++ b/types/node/zlib.d.ts @@ -2,9 +2,18 @@ declare module "zlib" { import * as stream from "stream"; interface ZlibOptions { - flush?: number; // default: zlib.constants.Z_NO_FLUSH - finishFlush?: number; // default: zlib.constants.Z_FINISH - chunkSize?: number; // default: 16*1024 + /** + * @default constants.Z_NO_FLUSH + */ + flush?: number; + /** + * @default constants.Z_FINISH + */ + finishFlush?: number; + /** + * @default 16*1024 + */ + chunkSize?: number; windowBits?: number; level?: number; // compression only memLevel?: number; // compression only @@ -12,6 +21,27 @@ declare module "zlib" { dictionary?: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default } + interface BrotliOptions { + /** + * @default constants.BROTLI_OPERATION_PROCESS + */ + flush?: number; + /** + * @default constants.BROTLI_OPERATION_FINISH + */ + finishFlush?: number; + /** + * @default 16*1024 + */ + chunkSize?: number; + params?: { + /** + * Each key is a `constants.BROTLI_*` constant. + */ + [key: number]: boolean | number; + }; + } + interface Zlib { /** @deprecated Use bytesWritten instead. */ readonly bytesRead: number; @@ -29,6 +59,8 @@ declare module "zlib" { reset(): void; } + interface BrotliCompress extends stream.Transform, Zlib { } + interface BrotliDecompress extends stream.Transform, Zlib { } interface Gzip extends stream.Transform, Zlib { } interface Gunzip extends stream.Transform, Zlib { } interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } @@ -37,6 +69,8 @@ declare module "zlib" { interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } interface Unzip extends stream.Transform, Zlib { } + function createBrotliCompress(options?: BrotliOptions): BrotliCompress; + function createBrotliDecompress(options?: BrotliOptions): BrotliDecompress; function createGzip(options?: ZlibOptions): Gzip; function createGunzip(options?: ZlibOptions): Gunzip; function createDeflate(options?: ZlibOptions): Deflate; @@ -46,96 +80,273 @@ declare module "zlib" { function createUnzip(options?: ZlibOptions): Unzip; type InputType = string | Buffer | DataView | ArrayBuffer | NodeJS.TypedArray; - function deflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function deflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + + type CompressCallback = (error: Error | null, result: Buffer) => void; + + function brotliCompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; + function brotliCompress(buf: InputType, callback: CompressCallback): void; + function brotliCompressSync(buf: InputType, options?: BrotliOptions): Buffer; + function brotliDecompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; + function brotliDecompress(buf: InputType, callback: CompressCallback): void; + function brotliDecompressSync(buf: InputType, options?: BrotliOptions): Buffer; + function deflate(buf: InputType, callback: CompressCallback): void; + function deflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; - function deflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function deflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function deflateRaw(buf: InputType, callback: CompressCallback): void; + function deflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; - function gzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function gzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function gzip(buf: InputType, callback: CompressCallback): void; + function gzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; - function gunzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function gunzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function gunzip(buf: InputType, callback: CompressCallback): void; + function gunzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; - function inflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function inflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function inflate(buf: InputType, callback: CompressCallback): void; + function inflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; - function inflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function inflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function inflateRaw(buf: InputType, callback: CompressCallback): void; + function inflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; - function unzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function unzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function unzip(buf: InputType, callback: CompressCallback): void; + function unzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; namespace constants { - // Allowed flush values. + const BROTLI_DECODE: number; + const BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: number; + const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: number; + const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: number; + const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: number; + const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: number; + const BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: number; + const BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: number; + const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: number; + const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: number; + const BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: number; + const BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: number; + const BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: number; + const BROTLI_DECODER_ERROR_FORMAT_DISTANCE: number; + const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: number; + const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: number; + const BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: number; + const BROTLI_DECODER_ERROR_FORMAT_PADDING_1: number; + const BROTLI_DECODER_ERROR_FORMAT_PADDING_2: number; + const BROTLI_DECODER_ERROR_FORMAT_RESERVED: number; + const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: number; + const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: number; + const BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: number; + const BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: number; + const BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: number; + const BROTLI_DECODER_ERROR_UNREACHABLE: number; + const BROTLI_DECODER_NEEDS_MORE_INPUT: number; + const BROTLI_DECODER_NEEDS_MORE_OUTPUT: number; + const BROTLI_DECODER_NO_ERROR: number; + const BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: number; + const BROTLI_DECODER_PARAM_LARGE_WINDOW: number; + const BROTLI_DECODER_RESULT_ERROR: number; + const BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: number; + const BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: number; + const BROTLI_DECODER_RESULT_SUCCESS: number; + const BROTLI_DECODER_SUCCESS: number; - const Z_NO_FLUSH: number; - const Z_PARTIAL_FLUSH: number; - const Z_SYNC_FLUSH: number; - const Z_FULL_FLUSH: number; - const Z_FINISH: number; - const Z_BLOCK: number; - const Z_TREES: number; + const BROTLI_DEFAULT_MODE: number; + const BROTLI_DEFAULT_QUALITY: number; + const BROTLI_DEFAULT_WINDOW: number; + const BROTLI_ENCODE: number; + const BROTLI_LARGE_MAX_WINDOW_BITS: number; + const BROTLI_MAX_INPUT_BLOCK_BITS: number; + const BROTLI_MAX_QUALITY: number; + const BROTLI_MAX_WINDOW_BITS: number; + const BROTLI_MIN_INPUT_BLOCK_BITS: number; + const BROTLI_MIN_QUALITY: number; + const BROTLI_MIN_WINDOW_BITS: number; - // Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events. + const BROTLI_MODE_FONT: number; + const BROTLI_MODE_GENERIC: number; + const BROTLI_MODE_TEXT: number; - const Z_OK: number; - const Z_STREAM_END: number; - const Z_NEED_DICT: number; - const Z_ERRNO: number; - const Z_STREAM_ERROR: number; - const Z_DATA_ERROR: number; - const Z_MEM_ERROR: number; - const Z_BUF_ERROR: number; - const Z_VERSION_ERROR: number; + const BROTLI_OPERATION_EMIT_METADATA: number; + const BROTLI_OPERATION_FINISH: number; + const BROTLI_OPERATION_FLUSH: number; + const BROTLI_OPERATION_PROCESS: number; - // Compression levels. + const BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: number; + const BROTLI_PARAM_LARGE_WINDOW: number; + const BROTLI_PARAM_LGBLOCK: number; + const BROTLI_PARAM_LGWIN: number; + const BROTLI_PARAM_MODE: number; + const BROTLI_PARAM_NDIRECT: number; + const BROTLI_PARAM_NPOSTFIX: number; + const BROTLI_PARAM_QUALITY: number; + const BROTLI_PARAM_SIZE_HINT: number; + + const DEFLATE: number; + const DEFLATERAW: number; + const GUNZIP: number; + const GZIP: number; + const INFLATE: number; + const INFLATERAW: number; + const UNZIP: number; - const Z_NO_COMPRESSION: number; - const Z_BEST_SPEED: number; const Z_BEST_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BLOCK: number; + const Z_BUF_ERROR: number; + const Z_DATA_ERROR: number; + + const Z_DEFAULT_CHUNK: number; const Z_DEFAULT_COMPRESSION: number; - - // Compression strategy. - - const Z_FILTERED: number; - const Z_HUFFMAN_ONLY: number; - const Z_RLE: number; - const Z_FIXED: number; + const Z_DEFAULT_LEVEL: number; + const Z_DEFAULT_MEMLEVEL: number; const Z_DEFAULT_STRATEGY: number; + const Z_DEFAULT_WINDOWBITS: number; + + const Z_ERRNO: number; + const Z_FILTERED: number; + const Z_FINISH: number; + const Z_FIXED: number; + const Z_FULL_FLUSH: number; + const Z_HUFFMAN_ONLY: number; + const Z_MAX_CHUNK: number; + const Z_MAX_LEVEL: number; + const Z_MAX_MEMLEVEL: number; + const Z_MAX_WINDOWBITS: number; + const Z_MEM_ERROR: number; + const Z_MIN_CHUNK: number; + const Z_MIN_LEVEL: number; + const Z_MIN_MEMLEVEL: number; + const Z_MIN_WINDOWBITS: number; + const Z_NEED_DICT: number; + const Z_NO_COMPRESSION: number; + const Z_NO_FLUSH: number; + const Z_OK: number; + const Z_PARTIAL_FLUSH: number; + const Z_RLE: number; + const Z_STREAM_END: number; + const Z_STREAM_ERROR: number; + const Z_SYNC_FLUSH: number; + const Z_VERSION_ERROR: number; + const ZLIB_VERNUM: number; } - // Constants + /** + * @deprecated + */ const Z_NO_FLUSH: number; + /** + * @deprecated + */ const Z_PARTIAL_FLUSH: number; + /** + * @deprecated + */ const Z_SYNC_FLUSH: number; + /** + * @deprecated + */ const Z_FULL_FLUSH: number; + /** + * @deprecated + */ const Z_FINISH: number; + /** + * @deprecated + */ const Z_BLOCK: number; + /** + * @deprecated + */ const Z_TREES: number; + /** + * @deprecated + */ const Z_OK: number; + /** + * @deprecated + */ const Z_STREAM_END: number; + /** + * @deprecated + */ const Z_NEED_DICT: number; + /** + * @deprecated + */ const Z_ERRNO: number; + /** + * @deprecated + */ const Z_STREAM_ERROR: number; + /** + * @deprecated + */ const Z_DATA_ERROR: number; + /** + * @deprecated + */ const Z_MEM_ERROR: number; + /** + * @deprecated + */ const Z_BUF_ERROR: number; + /** + * @deprecated + */ const Z_VERSION_ERROR: number; + /** + * @deprecated + */ const Z_NO_COMPRESSION: number; + /** + * @deprecated + */ const Z_BEST_SPEED: number; + /** + * @deprecated + */ const Z_BEST_COMPRESSION: number; + /** + * @deprecated + */ const Z_DEFAULT_COMPRESSION: number; + /** + * @deprecated + */ const Z_FILTERED: number; + /** + * @deprecated + */ const Z_HUFFMAN_ONLY: number; + /** + * @deprecated + */ const Z_RLE: number; + /** + * @deprecated + */ const Z_FIXED: number; + /** + * @deprecated + */ const Z_DEFAULT_STRATEGY: number; + /** + * @deprecated + */ const Z_BINARY: number; + /** + * @deprecated + */ const Z_TEXT: number; + /** + * @deprecated + */ const Z_ASCII: number; + /** + * @deprecated + */ const Z_UNKNOWN: number; + /** + * @deprecated + */ const Z_DEFLATED: number; } diff --git a/types/normalize-url/index.d.ts b/types/normalize-url/index.d.ts deleted file mode 100644 index fd76c4f72a..0000000000 --- a/types/normalize-url/index.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -// 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/normalize-url-tests.ts b/types/normalize-url/normalize-url-tests.ts deleted file mode 100644 index 961be30c0d..0000000000 --- a/types/normalize-url/normalize-url-tests.ts +++ /dev/null @@ -1,17 +0,0 @@ -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/normalize-url/tslint.json b/types/normalize-url/tslint.json deleted file mode 100644 index 279473e356..0000000000 --- a/types/normalize-url/tslint.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - // This package uses the Function type, and it will take effort to fix. - "ban-types": false - } -} diff --git a/types/npm-list-author-packages/index.d.ts b/types/npm-list-author-packages/index.d.ts new file mode 100644 index 0000000000..d482c7f514 --- /dev/null +++ b/types/npm-list-author-packages/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for npm-list-author-packages 2.0 +// Project: https://github.com/kgryte/npm-list-author-packages#readme +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace list { + interface Options { + /** registry port. Default: 443 (HTTPS) or 80 (HTTP). */ + port?: 443 | 80; + /** registry protocol. Default: 'https'. */ + protocol?: 'http' | 'https'; + /** registry. Default: 'registry.npmjs.org'. */ + registry?: string; + /** author username (required). */ + username: string; + } + + type Callback = (error: Error | null, data: string[]) => void; + + function factory(opts: Options, callback: Callback): () => void; +} + +declare function list(opts: list.Options, callback: list.Callback): void; + +export = list; diff --git a/types/npm-list-author-packages/npm-list-author-packages-tests.ts b/types/npm-list-author-packages/npm-list-author-packages-tests.ts new file mode 100644 index 0000000000..4f2d08d778 --- /dev/null +++ b/types/npm-list-author-packages/npm-list-author-packages-tests.ts @@ -0,0 +1,18 @@ +import list = require('npm-list-author-packages'); + +const opts: list.Options = { + port: 80, + protocol: 'http', + registry: 'my.favorite.npm/registry', + username: 'kgryte', +}; + +list(opts, (error, data) => { + data; // $ExpectType string[] +}); + +const get = list.factory({ username: 'kgryte' }, (error, data) => { + data; // $ExpectType string[] +}); + +get(); diff --git a/types/wait-for-localhost/tsconfig.json b/types/npm-list-author-packages/tsconfig.json similarity index 91% rename from types/wait-for-localhost/tsconfig.json rename to types/npm-list-author-packages/tsconfig.json index fb190a232f..e05e42ead0 100644 --- a/types/wait-for-localhost/tsconfig.json +++ b/types/npm-list-author-packages/tsconfig.json @@ -6,8 +6,8 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": true, "strictFunctionTypes": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "wait-for-localhost-tests.ts" + "npm-list-author-packages-tests.ts" ] } diff --git a/types/npm-list-author-packages/tslint.json b/types/npm-list-author-packages/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/npm-list-author-packages/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 42544390d9..b55d2cbb42 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] * @@ -12111,12 +12118,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -12457,12 +12466,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -12972,12 +12983,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -13358,12 +13371,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -13709,13 +13726,14 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -15081,12 +15100,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -15436,12 +15457,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -15967,12 +15990,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -16357,12 +16382,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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..f976e947ec 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] * @@ -12111,12 +12118,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -12457,12 +12466,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -12972,12 +12983,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -13358,12 +13371,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -13709,13 +13726,14 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -15081,12 +15100,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -15436,12 +15457,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -15967,12 +15990,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -16357,12 +16382,13 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * 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] * @@ -32055,15 +32085,19 @@ declare namespace Excel { } /** * - * Represents a collection of all the styles. WARNING: The StyleCollection items array has a known issue when loading items from the collection. Do not use `StyleCollection.items`, any `load()` method, and the `toJSON()` method. - * + * Represents a collection of all the styles. + * WARNING: There's currently a known issue with the StyleCollection.items array when loading items from the collection. + * Until this issue is resolved, do not use the StyleCollection.items property, the StyleCollection.load() method, + * or the StyleCollection.toJSON() method. * [Api set: ExcelApi 1.7] */ class StyleCollection 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; - /** - * WARNING: The StyleCollection items array has a known issue when loading items from the collection. Do not use `StyleCollection.items`, any `load()` method, and the `toJSON()` method. + /** + * WARNING: There's currently a known issue with the `StyleCollection.items` array when loading items from the collection. + * Until this issue is resolved, do not use the `StyleCollection.items` property, the `StyleCollection.load()` method, + * or the `StyleCollection.toJSON()` method. */ readonly items: Excel.Style[]; /** @@ -32085,13 +32119,17 @@ declare namespace Excel { */ getItem(name: string): Excel.Style; /** - * WARNING: The StyleCollection items array has a known issue when loading items from the collection. Do not use `StyleCollection.items`, any `load()` method, and the `toJSON()` method. + * WARNING: There's currently a known issue with the `StyleCollection.items` array when loading items from the collection. + * Until this issue is resolved, do not use the `StyleCollection.items` property, the `StyleCollection.load()` method, + * or the `StyleCollection.toJSON()` method. */ load(option?: Excel.Interfaces.StyleCollectionLoadOptions & Excel.Interfaces.CollectionLoadOptions): Excel.StyleCollection; load(option?: string | string[]): Excel.StyleCollection; load(option?: OfficeExtension.LoadOption): Excel.StyleCollection; /** - * WARNING: The StyleCollection items array has a known issue when loading items from the collection. Do not use `StyleCollection.items`, any `load()` method, and the `toJSON()` method. + * WARNING: There's currently a known issue with the `StyleCollection.items` array when loading items from the collection. + * Until this issue is resolved, do not use the `StyleCollection.items` property, the `StyleCollection.load()` method, + * or the `StyleCollection.toJSON()` method. */ toJSON(): Excel.Interfaces.StyleCollectionData; } diff --git a/types/onetime/index.d.ts b/types/onetime/index.d.ts index c7406307bc..f1c6b56ad0 100644 --- a/types/onetime/index.d.ts +++ b/types/onetime/index.d.ts @@ -1,36 +1,45 @@ -// Type definitions for onetime 2.0 +// Type definitions for onetime 3.0 // Project: https://github.com/sindresorhus/onetime#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 export = oneTime; -declare function oneTime(fn: () => R, options?: oneTime.Options): () => R; -declare function oneTime(fn: (t1: T1) => R, options?: oneTime.Options): (t1: T1) => R; -declare function oneTime(fn: (t1: T1, t2: T2) => R, options?: oneTime.Options): (t1: T1, t2: T2) => R; -declare function oneTime(fn: (t1: T1, t2: T2, t3: T3) => R, options?: oneTime.Options): (t1: T1, t2: T2, t3: T3) => R; -declare function oneTime( - fn: (t1: T1, t2: T2, t3: T3, t4: T4) => R, options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4) => R; -declare function oneTime( - fn: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R, options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R; -declare function oneTime( - fn: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6) => R, options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6) => R; -declare function oneTime( - fn: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7) => R, - options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7) => R; -declare function oneTime( - fn: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8) => R, - options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8) => R; -declare function oneTime( - fn: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9) => R, - options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9) => R; -declare function oneTime( - fn: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9, t10: T10) => R, - options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9, t10: T10) => R; -declare function oneTime(fn: (...args: any[]) => R, options?: oneTime.Options): (...args: any[]) => R; +/** + * Ensure a function is only called once. When called multiple times it will return the return value from the first call. + * + * @param fn Function that should only be called once. + * @returns A function that only calls `fn` once. + */ +declare function oneTime( + fn: (...args: T) => R, + options?: oneTime.Options +): (...args: T) => R; declare namespace oneTime { + /** + * Get the number of times `fn` has been called. + * + * @param fn Function to get call count from. + * @returns A number representing how many times `fn` has been called. + * + * @example + * const foo = onetime(() => {}); + * foo(); + * foo(); + * foo(); + * + * console.log(onetime.callCount(foo)); + * //=> 3 + */ + function callCount(fn: (...args: any[]) => any): number | undefined; + interface Options { + /** + * Throw an error when called more than once. + * @default false + */ throw?: boolean; } } diff --git a/types/onetime/onetime-tests.ts b/types/onetime/onetime-tests.ts index 840edb6cc2..4678eb45db 100644 --- a/types/onetime/onetime-tests.ts +++ b/types/onetime/onetime-tests.ts @@ -3,29 +3,10 @@ import onetime = require('onetime'); const foo = onetime(() => 5); foo(); // $ExpectType number -const foo2 = onetime(() => true, {throw: true}); +const foo2 = onetime(() => true, { throw: true }); foo2(); // $ExpectType boolean onetime((t1: boolean) => 5)(true); // $ExpectType number onetime((t1: boolean, t2: string) => 5)(true, ''); // $ExpectType number -onetime((t1: boolean, t2: string, t3: number) => 5)(true, '', 5); // $ExpectType number -onetime((t1: boolean, t2: string, t3: number, t4: undefined) => 5)(true, '', 5, undefined); // $ExpectType number -onetime((t1: boolean, t2: string, t3: number, t4: undefined, t5: string) => 5)(true, '', 5, undefined, ''); // $ExpectType number -onetime((t1: boolean, t2: string, t3: number, t4: undefined, t5: string, t6: number) => 5)(true, '', 5, undefined, '', 6); // $ExpectType number -onetime((t1: boolean, t2: string, t3: number, t4: undefined, t5: string, t6: number, t7: boolean) => 5)(true, '', 5, undefined, '', 6, false); // $ExpectType number -const t8 = onetime( - (t1: boolean, t2: string, t3: number, t4: undefined, t5: string, t6: number, t7: boolean, t8: string) => 5); -t8(true, '', 5, undefined, '', 6, false, ''); // $ExpectType number - -const t9 = onetime( - (t1: boolean, t2: string, t3: number, t4: undefined, t5: string, t6: number, t7: boolean, t8: string, t9: number) => 5); -t9(true, '', 5, undefined, '', 6, false, '', 1); // $ExpectType number - -const t10 = onetime( - (t1: boolean, t2: string, t3: number, t4: undefined, t5: string, t6: number, t7: boolean, t8: string, t9: number, t10: boolean) => 5); -t10(true, '', 5, undefined, '', 6, false, '', 1, true); // $ExpectType number - -const t11 = onetime( - (t1: boolean, t2: string, t3: number, t4: undefined, t5: string, t6: number, t7: boolean, t8: string, t9: number, t10: boolean, t11: string) => 5); -t11(true, '', 5, undefined, '', 6, false, '', 1, true, 5); // $ExpectType number +onetime.callCount((t1: boolean, t2: string) => 5); // $ExpectType number | undefined diff --git a/types/onetime/tsconfig.json b/types/onetime/tsconfig.json index 84d3da86b8..39df78e5bc 100644 --- a/types/onetime/tsconfig.json +++ b/types/onetime/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "onetime-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/onetime/v2/index.d.ts b/types/onetime/v2/index.d.ts new file mode 100644 index 0000000000..c7406307bc --- /dev/null +++ b/types/onetime/v2/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for onetime 2.0 +// Project: https://github.com/sindresorhus/onetime#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = oneTime; + +declare function oneTime(fn: () => R, options?: oneTime.Options): () => R; +declare function oneTime(fn: (t1: T1) => R, options?: oneTime.Options): (t1: T1) => R; +declare function oneTime(fn: (t1: T1, t2: T2) => R, options?: oneTime.Options): (t1: T1, t2: T2) => R; +declare function oneTime(fn: (t1: T1, t2: T2, t3: T3) => R, options?: oneTime.Options): (t1: T1, t2: T2, t3: T3) => R; +declare function oneTime( + fn: (t1: T1, t2: T2, t3: T3, t4: T4) => R, options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4) => R; +declare function oneTime( + fn: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R, options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R; +declare function oneTime( + fn: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6) => R, options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6) => R; +declare function oneTime( + fn: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7) => R, + options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7) => R; +declare function oneTime( + fn: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8) => R, + options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8) => R; +declare function oneTime( + fn: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9) => R, + options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9) => R; +declare function oneTime( + fn: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9, t10: T10) => R, + options?: oneTime.Options): (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9, t10: T10) => R; +declare function oneTime(fn: (...args: any[]) => R, options?: oneTime.Options): (...args: any[]) => R; + +declare namespace oneTime { + interface Options { + throw?: boolean; + } +} diff --git a/types/onetime/v2/onetime-tests.ts b/types/onetime/v2/onetime-tests.ts new file mode 100644 index 0000000000..840edb6cc2 --- /dev/null +++ b/types/onetime/v2/onetime-tests.ts @@ -0,0 +1,31 @@ +import onetime = require('onetime'); + +const foo = onetime(() => 5); +foo(); // $ExpectType number + +const foo2 = onetime(() => true, {throw: true}); +foo2(); // $ExpectType boolean + +onetime((t1: boolean) => 5)(true); // $ExpectType number +onetime((t1: boolean, t2: string) => 5)(true, ''); // $ExpectType number +onetime((t1: boolean, t2: string, t3: number) => 5)(true, '', 5); // $ExpectType number +onetime((t1: boolean, t2: string, t3: number, t4: undefined) => 5)(true, '', 5, undefined); // $ExpectType number +onetime((t1: boolean, t2: string, t3: number, t4: undefined, t5: string) => 5)(true, '', 5, undefined, ''); // $ExpectType number +onetime((t1: boolean, t2: string, t3: number, t4: undefined, t5: string, t6: number) => 5)(true, '', 5, undefined, '', 6); // $ExpectType number +onetime((t1: boolean, t2: string, t3: number, t4: undefined, t5: string, t6: number, t7: boolean) => 5)(true, '', 5, undefined, '', 6, false); // $ExpectType number + +const t8 = onetime( + (t1: boolean, t2: string, t3: number, t4: undefined, t5: string, t6: number, t7: boolean, t8: string) => 5); +t8(true, '', 5, undefined, '', 6, false, ''); // $ExpectType number + +const t9 = onetime( + (t1: boolean, t2: string, t3: number, t4: undefined, t5: string, t6: number, t7: boolean, t8: string, t9: number) => 5); +t9(true, '', 5, undefined, '', 6, false, '', 1); // $ExpectType number + +const t10 = onetime( + (t1: boolean, t2: string, t3: number, t4: undefined, t5: string, t6: number, t7: boolean, t8: string, t9: number, t10: boolean) => 5); +t10(true, '', 5, undefined, '', 6, false, '', 1, true); // $ExpectType number + +const t11 = onetime( + (t1: boolean, t2: string, t3: number, t4: undefined, t5: string, t6: number, t7: boolean, t8: string, t9: number, t10: boolean, t11: string) => 5); +t11(true, '', 5, undefined, '', 6, false, '', 1, true, 5); // $ExpectType number diff --git a/types/internal-ip/v2/tsconfig.json b/types/onetime/v2/tsconfig.json similarity index 84% rename from types/internal-ip/v2/tsconfig.json rename to types/onetime/v2/tsconfig.json index bae5b7feb8..bda103d103 100644 --- a/types/internal-ip/v2/tsconfig.json +++ b/types/onetime/v2/tsconfig.json @@ -13,8 +13,8 @@ "../../" ], "paths": { - "internal-ip": [ - "internal-ip/v2" + "onetime": [ + "onetime/v2" ] }, "types": [], @@ -23,6 +23,6 @@ }, "files": [ "index.d.ts", - "internal-ip-tests.ts" + "onetime-tests.ts" ] } diff --git a/types/onetime/v2/tslint.json b/types/onetime/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/onetime/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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-event/v1/tslint.json b/types/p-event/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-event/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.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/p-queue/index.d.ts b/types/p-queue/index.d.ts index 10c1179815..96fda8426a 100644 --- a/types/p-queue/index.d.ts +++ b/types/p-queue/index.d.ts @@ -1,45 +1,56 @@ -// Type definitions for p-queue 3.0 +// Type definitions for p-queue 3.1 // Project: https://github.com/sindresorhus/p-queue#readme // Definitions by: BendingBender // Evan Shortiss // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 + +/// + +import { EventEmitter } from 'events'; export = PQueue; -declare class PQueue { +/** + * Promise queue with concurrency control. + */ +declare class PQueue< + TEnqueueOptions extends PQueue.QueueAddOptions = PQueue.DefaultAddOptions +> extends EventEmitter { /** * Size of the queue. */ - size: number; + readonly size: number; /** * Number of pending promises. */ - pending: number; + readonly pending: number; /** * Whether the queue is currently paused. */ - isPaused: boolean; + readonly isPaused: boolean; - constructor(opts?: PQueue.Options); + constructor(opts?: PQueue.Options); /** - * Returns the promise returned by calling fn. + * Adds a sync or async task to the queue. Always returns a promise. * @param fn Promise-returning/async function. + * @param opts */ - add(fn: PQueue.Task, opts?: O): Promise; + add(fn: PQueue.Task, opts?: TEnqueueOptions): Promise; /** - * Same as .add(), but accepts an array of async functions and - * returns a promise that resolves when all async functions are resolved. + * Same as `.add()`, but accepts an array of sync or async functions + * and returns a promise that resolves when all functions are resolved. * @param fn Array of Promise-returning/async functions. */ - addAll(fns: Array>, opts?: O): Promise; + addAll(fns: Array>, opts?: TEnqueueOptions): Promise; /** * Returns a promise that settles when the queue becomes empty. + * * Can be called multiple times. Useful if you for example add * additional items at a later time. */ @@ -47,17 +58,18 @@ declare class PQueue; /** * Start (or resume) executing enqueued tasks within concurrency limit. - * No need to call this if queue is not paused (via options.autoStart = false - * or by .pause() method.) + * No need to call this if queue is not paused + * (via `options.autoStart = false` or by `.pause()` method.) */ start(): void; @@ -70,6 +82,20 @@ declare class PQueue void): this; + on(event: 'active', listener: () => void): this; + once(event: 'active', listener: () => void): this; + prependListener(event: 'active', listener: () => void): this; + prependOnceListener(event: 'active', listener: () => void): this; + removeListener(event: 'active', listener: () => void): this; + off(event: 'active', listener: () => void): this; + removeAllListeners(event?: 'active'): this; + listeners(event: 'active'): Array<() => void>; + rawListeners(event: 'active'): Array<() => void>; + emit(event: 'active'): boolean; + eventNames(): Array<'active'>; + listenerCount(type: 'active'): number; } declare namespace PQueue { @@ -77,30 +103,58 @@ declare namespace PQueue { [key: string]: any; } - interface QueueClassConstructor { - new(): QueueClass; + interface QueueClassConstructor { + new (): QueueClass; } - interface QueueClass { + interface QueueClass { size: number; - enqueue(run: () => void, options?: O): void; + enqueue(run: () => void, options?: TEnqueueOptions): void; dequeue(): (() => void) | undefined; } - interface Options { + interface Options { + /** + * Concurrency limit. Minimum: `1`. + * @default Infinity + */ concurrency?: number; + /** + * Whether queue tasks within concurrency limit, are auto-executed as soon as they're added. + * @default true + */ autoStart?: boolean; - queueClass?: QueueClassConstructor; + /** + * Class with a `enqueue` and `dequeue` method, and a `size` getter. See the + * [Custom QueueClass](https://github.com/sindresorhus/p-queue#custom-queueclass) section. + */ + queueClass?: QueueClassConstructor; + /** + * The max number of runs in the given interval of time. Minimum: `1`. + * @default Infinity + */ intervalCap?: number; + /** + * The length of time in milliseconds before the interval count resets. Must be finite. Minimum: `0`. + * @default 0 + */ interval?: number; + /** + * Whether the task must finish in the given interval or will be carried over into the next interval count. + * @default false + */ carryoverConcurrencyCount?: boolean; } interface DefaultAddOptions { + /** + * Priority of operation. Operations with greater priority will be scheduled first. + * @default 0 + */ priority?: number; } - type Task = () => Promise; + type Task = (() => PromiseLike) | (() => T); } diff --git a/types/p-queue/p-queue-tests.ts b/types/p-queue/p-queue-tests.ts index e12723a7d4..4ce6fbb13e 100644 --- a/types/p-queue/p-queue-tests.ts +++ b/types/p-queue/p-queue-tests.ts @@ -1,31 +1,31 @@ import PQueue = require('p-queue'); -const queue = new PQueue({concurrency: 1}); +const queue = new PQueue({ concurrency: 1 }); +new PQueue({ autoStart: false }); +new PQueue({ intervalCap: 1 }); +new PQueue({ interval: 0 }); +new PQueue({ carryoverConcurrencyCount: true }); -queue.add(() => Promise.resolve('sindresorhus.com')).then((sindre) => { - const str: string = sindre; -}); +queue.add(() => Promise.resolve('sindresorhus.com')); // $ExpectType Promise +queue.add(() => 'sindresorhus.com'); // $ExpectType Promise +queue.add(() => 'sindresorhus.com', { priority: 1 }); // $ExpectType Promise -queue.addAll([() => Promise.resolve('oh'), () => Promise.resolve('hi')]).then(r => { - r.indexOf('h'); -}); +queue.addAll([() => Promise.resolve('oh'), () => 'hi']); // $ExpectType Promise +queue.addAll([() => Promise.resolve('oh'), () => 1]); // $ExpectType Promise<(string | number)[]> +queue.addAll([() => Promise.resolve('oh'), () => 'hi'], { priority: 1 }); // $ExpectType Promise -Promise.resolve((): Promise => Promise.resolve('unicorn')) - .then(task => queue.add(task, {priority: 5})) - .then(unicorn => { - const str: string = unicorn; - }); - -queue.onEmpty().then(() => {}); -queue.onIdle().then(() => {}); +queue.onEmpty(); // $ExpectType Promise +queue.onIdle(); // $ExpectType Promise queue.start(); queue.pause(); queue.clear(); -let num: number; -num = queue.size; -num = queue.pending; -const paused = queue.isPaused; +queue.size; // $ExpectType number +queue.size = 1; // $ExpectError +queue.pending; // $ExpectType number +queue.pending = 5; // $ExpectError +queue.isPaused; // $ExpectType boolean +queue.isPaused = true; // $ExpectError class QueueClass implements PQueue.QueueClass<{ any: string }> { private readonly queue: Array<() => void>; @@ -45,5 +45,5 @@ class QueueClass implements PQueue.QueueClass<{ any: string }> { } } -const queue2 = new PQueue({queueClass: QueueClass}); -queue2.add(() => Promise.resolve(), {any: 'hi'}); +const queue2 = new PQueue({ queueClass: QueueClass }); +queue2.add(() => Promise.resolve(), { any: 'hi' }); 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/pg-copy-streams/tslint.json b/types/pg-copy-streams/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pg-copy-streams/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/phantom/phantom-tests.ts b/types/phantom/phantom-tests.ts index b83ac3cc02..a611f195be 100644 --- a/types/phantom/phantom-tests.ts +++ b/types/phantom/phantom-tests.ts @@ -96,7 +96,7 @@ phantom.create(["--web-security=no", "--ignore-ssl-errors=yes"]).then((ph) => { phantom.create().then((ph) => { return ph.createPage().then((page) => { page.open("http://localhost:9901/cookie").then((status) => { - var someFunc = (aaa: string, my_obj: Object) => { + var someFunc = function (aaa: string, my_obj: Object) { var attribute_to_want = aaa; var h2Arr: string[] = []; var results = document.querySelectorAll(attribute_to_want); 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/pino-http/index.d.ts b/types/pino-http/index.d.ts index 54ac4e9149..86fae78a3e 100644 --- a/types/pino-http/index.d.ts +++ b/types/pino-http/index.d.ts @@ -20,6 +20,7 @@ declare namespace PinoHttp { genReqId?: GenReqId; useLevel?: Level; stream?: DestinationStream; + customLogLevel?: (res: ServerResponse, error: Error) => Level; } interface GenReqId { diff --git a/types/pino-http/pino-http-tests.ts b/types/pino-http/pino-http-tests.ts index 8a86bf08e8..013e23ae10 100644 --- a/types/pino-http/pino-http-tests.ts +++ b/types/pino-http/pino-http-tests.ts @@ -18,3 +18,4 @@ pinoHttp({ genReqId: (req) => Buffer.allocUnsafe(16) }); pinoHttp({ useLevel: 'error' }); pinoHttp({ prettyPrint: true }); pinoHttp(new Writable()); +pinoHttp({ customLogLevel(req, res) { return 'info'; } }); diff --git a/types/pkijs/index.d.ts b/types/pkijs/index.d.ts index 106dfa2405..63cbee5207 100644 --- a/types/pkijs/index.d.ts +++ b/types/pkijs/index.d.ts @@ -1908,6 +1908,12 @@ declare module "pkijs/src/RelativeDistinguishedNames" { fromSchema(schema: any): void; toSchema(): any; toJSON(): any; + /** + * Compare two RDN values, or RDN with ArrayBuffer value + * @param {(RelativeDistinguishedNames|ArrayBuffer)} compareTo The value compare to current + * @returns {boolean} + */ + isEqual(compareTo: RelativeDistinguishedNames|ArrayBuffer): boolean; } } diff --git a/types/pkijs/pkijs-tests.ts b/types/pkijs/pkijs-tests.ts index 6b7b73bb00..f2c9a88990 100644 --- a/types/pkijs/pkijs-tests.ts +++ b/types/pkijs/pkijs-tests.ts @@ -12,6 +12,8 @@ import SignerInfo from "pkijs/src/SignerInfo"; import IssuerAndSerialNumber from "pkijs/src/IssuerAndSerialNumber"; import SignedAndUnsignedAttributes from "pkijs/src/SignedAndUnsignedAttributes"; import ContentInfo from "pkijs/src/ContentInfo"; +import RelativeDistinguishedNames from "pkijs/src/RelativeDistinguishedNames"; + // ********************************************************************************* let cmsSignedBuffer = new ArrayBuffer(0); // ArrayBuffer with loaded or created CMS_Signed const trustedCertificates: Certificate[] = []; // Array of root certificates from "CA Bundle" @@ -657,4 +659,14 @@ function handleCABundle(evt: Event) { event => parseCAbundle((event.target as any).result); tempReader.readAsArrayBuffer(currentFiles[0]); -} \ No newline at end of file +} + +function typetest_RelativeDN_isEqual() { + + const rdn1 = new RelativeDistinguishedNames(); + const rdn2 = new RelativeDistinguishedNames(); + const arraybuf = new ArrayBuffer(1); + + rdn1.isEqual(rdn2); // $ExpectType boolean + rdn1.isEqual(arraybuf); // $ExpectType boolean +} 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..7ad3c2a82f 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.3 // 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,18 +120,21 @@ 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; + filter: (callback: (req: Request) => boolean) => RouteHandler; passthrough(value?: boolean): RouteHandler; intercept( fn: (req: Request, res: Response, intercept: Intercept) => EventListenerResponse ): RouteHandler; - recordingName(recordingName: string): RouteHandler; + recordingName(recordingName?: string): RouteHandler; configure(config: PollyConfig): RouteHandler; } export class PollyServer { diff --git a/types/pollyjs__core/pollyjs__core-tests.ts b/types/pollyjs__core/pollyjs__core-tests.ts index 0644eff7f4..cfe9047ccd 100644 --- a/types/pollyjs__core/pollyjs__core-tests.ts +++ b/types/pollyjs__core/pollyjs__core-tests.ts @@ -113,6 +113,16 @@ async function test() { /* Do something else */ }); + server + .get('/users/:id') + .filter(req => req.params.id === '1') + .filter(req => req.params.id !== '2') + .recordingName('test') + .recordingName() + .intercept((_req, res) => { + res.status(200).json({ email: 'user1@test.com' }); + }); + /* Intercept all Google Analytic requests and respond with a 200 */ server.get('/google-analytics/*path').intercept((req, res, intercept) => { if (req.pathname === 'test') { @@ -127,5 +137,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-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/qs/index.d.ts b/types/qs/index.d.ts index 2a3b10a273..aead3eb442 100644 --- a/types/qs/index.d.ts +++ b/types/qs/index.d.ts @@ -19,7 +19,7 @@ declare namespace QueryString { encode?: boolean; encoder?: (str: string) => any; filter?: Array | ((prefix: string, value: any) => any); - arrayFormat?: 'indices' | 'brackets' | 'repeat'; + arrayFormat?: 'indices' | 'brackets' | 'repeat' | 'comma'; indices?: boolean; sort?: (a: any, b: any) => number; serializeDate?: (d: Date) => string; 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..16ba23d85b 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); @@ -2180,7 +2180,7 @@ class Rectangle { this.colors = Array.prototype.slice.call(arguments, 1); } - Circle.prototype.area = () => Math.PI * Math.pow(this.r, 2); + Circle.prototype.area = function() { return Math.PI * Math.pow(this.r, 2); }; const circleN = R.constructN(2, Circle); let c1 = circleN(1, "red"); @@ -2623,7 +2623,7 @@ class Rectangle { const Why: any = ((val: boolean) => { const why = {} as any; why.val = val; - why.and = (x: boolean) => this.val && x; + why.and = function(x: boolean) { return this.val && x; }; return Why; })(true); const why = new Why(true); 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-leaflet/index.d.ts b/types/react-leaflet/index.d.ts index c362a1f23c..04fe17a04f 100644 --- a/types/react-leaflet/index.d.ts +++ b/types/react-leaflet/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-leaflet 1.1 +// Type definitions for react-leaflet 2.2 // Project: https://github.com/PaulLeCam/react-leaflet // Definitions by: Dave Leaver , David Schneider , Yui T. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -118,12 +118,20 @@ export type LeafletEvents = MapEvents // These type parameters aren't needed for instantiating a component, but they are useful for // extending react-leaflet classes. -export class MapComponent extends React.Component

    { +export interface MapComponentProps { + leaflet?: LeafletContext; + pane?: string; +} + +export class MapEvented extends React.Component

    { _leafletEvents: LeafletEvents; leafletElement: E; extractLeafletEvents(props: P): LeafletEvents; bindLeafletEvents(next: LeafletEvents, prev: LeafletEvents): LeafletEvents; fireLeafletEvent(type: string, data: any): void; +} + +export class MapComponent

    extends MapEvented { getOptions(props: P): P; } @@ -131,221 +139,313 @@ export interface MapProps extends MapEvents, Leaflet.MapOptions, Leaflet.LocateO animate?: boolean; bounds?: Leaflet.LatLngBoundsExpression; boundsOptions?: Leaflet.FitBoundsOptions; - center?: Leaflet.LatLngExpression; - children?: Children; + children: Children; className?: string; id?: string; - maxBounds?: Leaflet.LatLngBoundsExpression; - maxZoom?: number; - minZoom?: number; style?: React.CSSProperties; useFlyTo?: boolean; - zoom?: number; + viewport?: Viewport; + whenReady?: () => void; } -export class Map

    extends MapComponent { - className?: string; - container: HTMLDivElement; - getChildContext(): { layerContainer: E, map: E }; +export class Map

    extends MapEvented { + className: string | null | undefined; + contextValue: LeafletContext | null | undefined; + container: HTMLDivElement | null | undefined; + viewport: Viewport; createLeafletElement(props: P): E; updateLeafletElement(fromProps: P, toProps: P): void; - bindContainer(container: HTMLDivElement): void; + onViewportChange: (viewport: Viewport | null) => void; + onViewportChanged: (viewport: Viewport | null) => void; + bindContainer(container: HTMLDivElement | null | undefined): void; shouldUpdateCenter(next: Leaflet.LatLngExpression, prev: Leaflet.LatLngExpression): boolean; shouldUpdateBounds(next: Leaflet.LatLngBoundsExpression, prev: Leaflet.LatLngBoundsExpression): boolean; } +export interface DivOverlayProps extends MapComponentProps, Leaflet.DivOverlayOptions { + children: Children; + onClose?: () => void; + onOpen?: () => void; +} + +export interface DivOverlayTypes extends Leaflet.Evented { + isOpen: () => boolean; + update: () => void; +} + +export class DivOverlay

    extends MapComponent { + createLeafletElement(_props: P): void; + updateLeafletElement(_prevProps: P, _props: P): void; + onClose: () => void; + onOpen: () => void; + onRender: () => void; +} + export interface PaneProps { - name?: string; children?: Children; - map?: Leaflet.Map; className?: string; + leaflet?: LeafletContext; + name?: string; style?: React.CSSProperties; pane?: string; } export interface PaneState { - name?: string; + name: string | null | undefined; + context: LeafletContext | null | undefined; } export class Pane

    extends React.Component { - getChildContext(): { pane: string }; createPane(props: P): void; removePane(): void; setStyle(arg: { style?: string, className?: string }): void; - getParentPane(): HTMLElement | undefined; - getPane(name: string): HTMLElement | undefined; + getParentPane(): HTMLElement | null | undefined; + getPane(name: string | null | undefined): HTMLElement | null | undefined; } -export interface MapLayerProps { +export interface MapLayerProps extends MapComponentProps { + attribution?: string; children?: Children; } + +export type AddLayerHandler = (layer: Leaflet.Layer, name: string, checked?: boolean) => void; + +export type RemoveLayerHandler = (layer: Leaflet.Layer) => void; + export interface LayerContainer { - addLayer(layer: Leaflet.Layer): this; - removeLayer(layer: number | Leaflet.Layer): this; + addLayer: AddLayerHandler; + removeLayer: RemoveLayerHandler; } -export class MapLayer

    extends MapComponent { + +export interface LeafletContext { + map?: Leaflet.Map; + pane?: string; + layerContainer?: LayerContainer; + popupContainer?: Leaflet.Layer; +} + +export type LatLng = Leaflet.LatLng | number[] | object; + +export type LatLngBounds = Leaflet.LatLngBounds | LatLng[]; + +export type Point = [number, number] | Leaflet.Point; + +export interface Viewport { + center: [number, number] | null | undefined; + zoom: number | null | undefined; +} + +export class MapLayer

    extends MapComponent { + contextValue: LeafletContext | null | undefined; + leafletElement: E; createLeafletElement(props: P): E; updateLeafletElement(fromProps: P, toProps: P): void; readonly layerContainer: LayerContainer | Leaflet.Map; } -export interface GridLayerProps extends Leaflet.GridLayerOptions { - children?: Children; +export interface GridLayerProps extends MapLayerProps, Leaflet.GridLayerOptions { } +export class GridLayer

    extends MapLayer { + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; + getOptions(props: P): P; } -export class GridLayer

    extends MapLayer {} -export interface TileLayerProps extends TileLayerEvents, Leaflet.TileLayerOptions { +export interface TileLayerProps extends GridLayerProps, TileLayerEvents, Leaflet.TileLayerOptions { + url: string; +} +export class TileLayer

    extends GridLayer { + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; +} + +export interface WMSTileLayerProps extends TileLayerEvents, Leaflet.WMSOptions, GridLayerProps { children?: Children; url: string; } -export class TileLayer

    extends GridLayer { } - -export interface WMSTileLayerProps extends TileLayerEvents, Leaflet.WMSOptions { - children?: Children; - url: string; +export class WMSTileLayer

    extends GridLayer { + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; + getOptions(params: P): P; } -export class WMSTileLayer

    extends GridLayer { } -export interface ImageOverlayProps extends Leaflet.ImageOverlayOptions { - bounds: Leaflet.LatLngBoundsExpression; - children?: Children; - url: string; +export interface ImageOverlayProps extends MapLayerProps, Leaflet.ImageOverlayOptions { + bounds?: Leaflet.LatLngBoundsExpression; + url: string | HTMLImageElement; + zIndex?: number; } export class ImageOverlay

    extends MapLayer { - getChildContext(): { popupContainer: E }; + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; } -export interface LayerGroupProps { - children?: Children; -} -export class LayerGroup

    extends MapLayer { - getChildContext(): { layerContainer: E }; +export class LayerGroup

    extends MapLayer { + createLeafletElement(props: P): E; } -export interface MarkerProps extends MarkerEvents, Leaflet.MarkerOptions { - children?: Children; +export interface MarkerProps extends MapLayerProps, MarkerEvents, Leaflet.MarkerOptions { position: Leaflet.LatLngExpression; } export class Marker

    extends MapLayer { - getChildContext(): { popupContainer: E }; + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; } export interface PathProps extends PathEvents, Leaflet.PathOptions, MapLayerProps { } -export abstract class Path

    extends MapLayer { +export abstract class Path

    extends MapLayer { getChildContext(): { popupContainer: E }; getPathOptions(props: P): Leaflet.PathOptions; setStyle(options: Leaflet.PathOptions): void; setStyleIfChanged(fromProps: P, toProps: P): void; } -export interface CircleProps extends PathEvents, Leaflet.CircleMarkerOptions { +export interface CircleProps extends MapLayerProps, PathEvents, Leaflet.CircleMarkerOptions { center: Leaflet.LatLngExpression; - children?: Children; radius: number; } -export class Circle

    extends Path { } +export class Circle

    extends Path { + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; +} -export interface CircleMarkerProps extends PathEvents, Leaflet.CircleMarkerOptions { +export interface CircleMarkerProps extends PathProps, PathEvents, Leaflet.CircleMarkerOptions { center: Leaflet.LatLngExpression; - children?: Children; radius: number; } -export class CircleMarker

    extends Path { } - -export interface FeatureGroupProps extends FeatureGroupEvents, Leaflet.PathOptions { - children?: Children; -} -export class FeatureGroup

    extends Path { - getChildContext(): { layerContainer: E, popupContainer: E }; +export class CircleMarker

    extends Path { + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; } -export interface GeoJSONProps extends FeatureGroupEvents, Leaflet.GeoJSONOptions { - children?: Children; +export interface FeatureGroupProps extends MapLayerProps, FeatureGroupEvents, Leaflet.PathOptions { } +export class FeatureGroup

    extends LayerGroup { + createLeafletElement(props: P): E; +} + +export interface GeoJSONProps extends PathProps, FeatureGroupEvents, Leaflet.GeoJSONOptions { data: GeoJSON.GeoJsonObject; - style?: Leaflet.StyleFunction; } -export class GeoJSON

    extends Path { } +export class GeoJSON

    extends FeatureGroup { + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; +} -export interface PolylineProps extends PathEvents, Leaflet.PolylineOptions { - children?: Children; +export interface PolylineProps extends PathProps, PathEvents, Leaflet.PolylineOptions { positions: Leaflet.LatLngExpression[] | Leaflet.LatLngExpression[][]; } -export class Polyline

    extends Path { } +export class Polyline

    extends Path { + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; +} -export interface PolygonProps extends PathEvents, Leaflet.PolylineOptions { - children?: Children; - popupContainer?: Leaflet.FeatureGroup; +export interface PolygonProps extends PathProps, PathEvents, Leaflet.PolylineOptions { positions: Leaflet.LatLngExpression[] | Leaflet.LatLngExpression[][] | Leaflet.LatLngExpression[][][]; } -export class Polygon

    extends Path { } - -export interface RectangleProps extends PathEvents, Leaflet.PolylineOptions { - children?: Children; - bounds: Leaflet.LatLngBoundsExpression; - popupContainer?: Leaflet.FeatureGroup; +export class Polygon

    extends Path { + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; } -export class Rectangle

    extends Path { } -export interface PopupProps extends Leaflet.PopupOptions { - children?: Children; +export interface RectangleProps extends PathProps, PathEvents, Leaflet.PolylineOptions { + bounds: Leaflet.LatLngBoundsExpression; +} +export class Rectangle

    extends Path { + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; +} + +export interface PopupProps extends Leaflet.PopupOptions, DivOverlayProps { position?: Leaflet.LatLngExpression; } -export class Popup

    extends MapComponent { +export class Popup

    extends DivOverlay { + getOptions(props: P): P; + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; onPopupOpen(arg: { popup: E }): void; onPopupClose(arg: { popup: E }): void; - renderPopupContent(): void; - removePopupContent(): void; + onRender: () => void; } -export interface TooltipProps extends Leaflet.TooltipOptions { - children?: Children; -} -export class Tooltip

    extends MapComponent { +export interface TooltipProps extends Leaflet.TooltipOptions, DivOverlayProps { } +export class Tooltip

    extends DivOverlay { onTooltipOpen(arg: { tooltip: E }): void; onTooltipClose(arg: { tooltip: E }): void; - renderTooltipContent(): void; - removeTooltipContent(): void; } -export type MapControlProps = Leaflet.ControlOptions; +export type MapControlProps = { + leaflet?: LeafletContext +} & Leaflet.ControlOptions; + export class MapControl

    extends React.Component

    { leafletElement: E; createLeafletElement(props: P): E; updateLeafletElement(fromProps: P, toProps: P): void; } -export type AttributionControlProps = Leaflet.Control.AttributionOptions; -export class AttributionControl

    extends MapControl { } - -export interface LayersControlProps extends LayersControlEvents, Leaflet.Control.LayersOptions { - baseLayers?: Leaflet.Control.LayersObject; - children?: Children; - overlays?: Leaflet.Control.LayersObject; +export type AttributionControlProps = Leaflet.Control.AttributionOptions & MapControlProps; +export class AttributionControl

    extends MapControl { + createLeafletElement(props: P): E; +} + +export interface LayersControlProps extends MapControlProps, LayersControlEvents, Leaflet.Control.LayersOptions { + children: Children; + collapsed?: boolean; +} +export class LayersControl

    extends MapControl { + controlProps: { + addBaseLayer: AddLayerHandler, + addOverlay: AddLayerHandler, + removeLayer: RemoveLayerHandler, + removeLayerControl: RemoveLayerHandler + }; + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; + addBaseLayer(layer: Leaflet.Layer, name: string, checked: boolean): void; + addOverlay(layer: Leaflet.Layer, name: string, checked: boolean): void; + removeLayer(layer: Leaflet.Layer): void; + removeLayerControl(layer: Leaflet.Layer): void; } -export class LayersControl

    extends MapControl { } export namespace LayersControl { - interface BaseControlledLayerProps { + interface ControlledLayerProps { + addBaseLayer?: AddLayerHandler; + addOverlay?: AddLayerHandler; checked?: boolean; - children?: Children; - removeLayer?(layer: Leaflet.Layer): void; - removeLayerControl?(layer: Leaflet.Layer): void; - } - interface ControlledLayerProps extends BaseControlledLayerProps { - addBaseLayer?(layer: Leaflet.Layer, name: string, checked: boolean): void; - addOverlay?(layer: Leaflet.Layer, name: string, checked: boolean): void; + children: Children; + leaflet?: LeafletContext; name: string; + removeLayer?: RemoveLayerHandler; + removeLayerControl?: RemoveLayerHandler; } - class ControlledLayer

    extends React.Component

    { - layer?: Leaflet.Layer; - getChildContext(): { layerContainer: LayerContainer }; - addLayer(): void; + class ControlledLayer

    extends React.Component

    { + contextValue: LeafletContext; + layer: Leaflet.Layer | null | undefined; removeLayer(layer: Leaflet.Layer): void; } - class BaseLayer

    extends ControlledLayer

    { } - class Overlay

    extends ControlledLayer

    { } + class BaseLayer

    extends ControlledLayer

    { + constructor(props: ControlledLayerProps); + addLayer: (layer: Leaflet.Layer) => void; + } + class Overlay

    extends ControlledLayer

    { + constructor(props: ControlledLayerProps); + addLayer: (layer: Leaflet.Layer) => void; + } } -export type ScaleControlProps = Leaflet.Control.ScaleOptions; -export class ScaleControl

    extends MapControl { } +export type ScaleControlProps = Leaflet.Control.ScaleOptions & MapControlProps; +export class ScaleControl

    extends MapControl { + createLeafletElement(props: P): E; +} -export type ZoomControlProps = Leaflet.Control.ZoomOptions; -export class ZoomControl

    extends MapControl { } +export type ZoomControlProps = Leaflet.Control.ZoomOptions & MapControlProps; +export class ZoomControl

    extends MapControl { + createLeafletElement(props: P): E; +} + +// context.js +export const LeafletProvider: React.Provider; +export const LeafletConsumer: React.Consumer; + +export interface ContextProps { + leaflet?: LeafletContext; +} +export type Omit = Pick>; + +export function withLeaflet(WrappedComponent: React.ComponentType): React.ComponentType>; diff --git a/types/react-leaflet/react-leaflet-tests.tsx b/types/react-leaflet/react-leaflet-tests.tsx index fe9825c465..5d1fc2ce7e 100644 --- a/types/react-leaflet/react-leaflet-tests.tsx +++ b/types/react-leaflet/react-leaflet-tests.tsx @@ -16,8 +16,10 @@ import { MapProps, Marker, MarkerProps, + Path, Pane, Polygon, + PolygonProps, Polyline, Popup, PopupProps, @@ -25,7 +27,10 @@ import { TileLayer, Tooltip, WMSTileLayer, - ZoomControl + ZoomControl, + LeafletProvider, + withLeaflet, + Viewport } from 'react-leaflet'; const { BaseLayer, Overlay } = LayersControl; @@ -207,7 +212,7 @@ export class CustomComponent extends Component } } -// SOURCE ??? +// Similar to custom-icons.js export class MarkerWithDivIconExample extends Component { render() { return ( @@ -628,6 +633,43 @@ export class VectorLayersExample extends Component { } } +// viewport.js + +const viewportCenter: [number, number] = [51.505, -0.09]; + +const DEFAULT_VIEWPORT = { + center: viewportCenter, + zoom: 13 +}; + +export class ViewportExample extends Component { + state = { + viewport: DEFAULT_VIEWPORT + }; + + onClickReset = () => { + this.setState({ viewport: DEFAULT_VIEWPORT }); + } + + onViewportChanged = (viewport: Viewport) => { + this.setState({ viewport }); + } + + render() { + return ( + + + + ); + } +} + // wms-tile-layer.js interface WMSTileLayerExampleState { lat: number; @@ -729,6 +771,8 @@ class LegendControl extends MapControl } } +const legendControlComponent = withLeaflet(LegendControl); + const LegendControlExample = () => ( ( ); + +class CustomPolygon extends Path { + createLeafletElement(props: PolygonProps) { + const el = new L.Polygon(props.positions, this.getOptions(props)); + this.contextValue = { ...props.leaflet, popupContainer: el }; + return el; + } + + updateLeafletElement(fromProps: PolygonProps, toProps: PolygonProps) { + if (toProps.positions !== fromProps.positions) { + this.leafletElement.setLatLngs(toProps.positions); + } + this.setStyleIfChanged(fromProps, toProps); + } + + render() { + const { children } = this.props; + return children == null || this.contextValue == null ? null : ( + {children} + ); + } +} +const leafletComponent = withLeaflet(CustomPolygon); diff --git a/types/react-leaflet/v1/index.d.ts b/types/react-leaflet/v1/index.d.ts new file mode 100644 index 0000000000..c362a1f23c --- /dev/null +++ b/types/react-leaflet/v1/index.d.ts @@ -0,0 +1,351 @@ +// Type definitions for react-leaflet 1.1 +// Project: https://github.com/PaulLeCam/react-leaflet +// Definitions by: Dave Leaver , David Schneider , Yui T. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as Leaflet from 'leaflet'; +import * as React from 'react'; + +// All events need to be lowercase so they don't collide with React.DOMAttributes +// which already declares things with some of the same names + +export type Children = React.ReactNode | React.ReactNode[]; + +export interface MapEvents { + onclick?(event: Leaflet.LeafletMouseEvent): void; + ondblclick?(event: Leaflet.LeafletMouseEvent): void; + onmousedown?(event: Leaflet.LeafletMouseEvent): void; + onmouseup?(event: Leaflet.LeafletMouseEvent): void; + onmouseover?(event: Leaflet.LeafletMouseEvent): void; + onmouseout?(event: Leaflet.LeafletMouseEvent): void; + onmousemove?(event: Leaflet.LeafletMouseEvent): void; + oncontextmenu?(event: Leaflet.LeafletMouseEvent): void; + onfocus?(event: Leaflet.LeafletEvent): void; + onblur?(event: Leaflet.LeafletEvent): void; + onpreclick?(event: Leaflet.LeafletMouseEvent): void; + onload?(event: Leaflet.LeafletEvent): void; + onunload?(event: Leaflet.LeafletEvent): void; + onviewreset?(event: Leaflet.LeafletEvent): void; + onmove?(event: Leaflet.LeafletEvent): void; + onmovestart?(event: Leaflet.LeafletEvent): void; + onmoveend?(event: Leaflet.LeafletEvent): void; + ondragstart?(event: Leaflet.LeafletEvent): void; + ondrag?(event: Leaflet.LeafletEvent): void; + ondragend?(event: Leaflet.DragEndEvent): void; + onzoomstart?(event: Leaflet.LeafletEvent): void; + onzoomend?(event: Leaflet.LeafletEvent): void; + onzoomlevelschange?(event: Leaflet.LeafletEvent): void; + onresize?(event: Leaflet.ResizeEvent): void; + onautopanstart?(event: Leaflet.LeafletEvent): void; + onlayeradd?(event: Leaflet.LayerEvent): void; + onlayerremove?(event: Leaflet.LayerEvent): void; + onbaselayerchange?(event: Leaflet.LayersControlEvent): void; + onoverlayadd?(event: Leaflet.LayersControlEvent): void; + onoverlayremove?(event: Leaflet.LayersControlEvent): void; + onlocationfound?(event: Leaflet.LocationEvent): void; + onlocationerror?(event: Leaflet.ErrorEvent): void; + onpopupopen?(event: Leaflet.PopupEvent): void; + onpopupclose?(event: Leaflet.PopupEvent): void; +} + +export interface MarkerEvents { + onclick?(event: Leaflet.LeafletMouseEvent): void; + ondblclick?(event: Leaflet.LeafletMouseEvent): void; + onmousedown?(event: Leaflet.LeafletMouseEvent): void; + onmouseover?(event: Leaflet.LeafletMouseEvent): void; + onmouseout?(event: Leaflet.LeafletMouseEvent): void; + oncontextmenu?(event: Leaflet.LeafletMouseEvent): void; + ondragstart?(event: Leaflet.LeafletEvent): void; + ondrag?(event: Leaflet.LeafletEvent): void; + ondragend?(event: Leaflet.DragEndEvent): void; + onmove?(event: Leaflet.LeafletEvent): void; + onadd?(event: Leaflet.LeafletEvent): void; + onremove?(event: Leaflet.LeafletEvent): void; + onpopupopen?(event: Leaflet.PopupEvent): void; + onpopupclose?(event: Leaflet.PopupEvent): void; +} + +export interface TileLayerEvents { + onloading?(event: Leaflet.LeafletEvent): void; + onload?(event: Leaflet.LeafletEvent): void; + ontileloadstart?(event: Leaflet.TileEvent): void; + ontileload?(event: Leaflet.TileEvent): void; + ontileunload?(event: Leaflet.TileEvent): void; + ontileerror?(event: Leaflet.TileEvent): void; +} + +export interface PathEvents { + onclick?(event: Leaflet.LeafletMouseEvent): void; + ondblclick?(event: Leaflet.LeafletMouseEvent): void; + onmousedown?(event: Leaflet.LeafletMouseEvent): void; + onmouseover?(event: Leaflet.LeafletMouseEvent): void; + onmouseout?(event: Leaflet.LeafletMouseEvent): void; + oncontextmenu?(event: Leaflet.LeafletMouseEvent): void; + onadd?(event: Leaflet.LeafletEvent): void; + onremove?(event: Leaflet.LeafletEvent): void; + onpopupopen?(event: Leaflet.PopupEvent): void; + onpopupclose?(event: Leaflet.PopupEvent): void; +} + +export interface FeatureGroupEvents { + onclick?(event: Leaflet.LeafletMouseEvent): void; + ondblclick?(event: Leaflet.LeafletMouseEvent): void; + onmouseover?(event: Leaflet.LeafletMouseEvent): void; + onmouseout?(event: Leaflet.LeafletMouseEvent): void; + oncontextmenu?(event: Leaflet.LeafletMouseEvent): void; + onlayeradd?(event: Leaflet.LayerEvent): void; + onlayerremove?(event: Leaflet.LayerEvent): void; +} + +export interface LayersControlEvents { + onbaselayerchange?(event: Leaflet.LayersControlEvent): void; + onoverlayadd?(event: Leaflet.LayersControlEvent): void; + onoverlayremove?(event: Leaflet.LayersControlEvent): void; +} + +export type LeafletEvents = MapEvents + & MarkerEvents + & TileLayerEvents + & PathEvents + & FeatureGroupEvents + & LayersControlEvents; + +// Most react-leaflet components take two type parameters: +// - P : the component's props object +// - E : the corresponding Leaflet element + +// These type parameters aren't needed for instantiating a component, but they are useful for +// extending react-leaflet classes. + +export class MapComponent extends React.Component

    { + _leafletEvents: LeafletEvents; + leafletElement: E; + extractLeafletEvents(props: P): LeafletEvents; + bindLeafletEvents(next: LeafletEvents, prev: LeafletEvents): LeafletEvents; + fireLeafletEvent(type: string, data: any): void; + getOptions(props: P): P; +} + +export interface MapProps extends MapEvents, Leaflet.MapOptions, Leaflet.LocateOptions, Leaflet.FitBoundsOptions { + animate?: boolean; + bounds?: Leaflet.LatLngBoundsExpression; + boundsOptions?: Leaflet.FitBoundsOptions; + center?: Leaflet.LatLngExpression; + children?: Children; + className?: string; + id?: string; + maxBounds?: Leaflet.LatLngBoundsExpression; + maxZoom?: number; + minZoom?: number; + style?: React.CSSProperties; + useFlyTo?: boolean; + zoom?: number; +} + +export class Map

    extends MapComponent { + className?: string; + container: HTMLDivElement; + getChildContext(): { layerContainer: E, map: E }; + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; + bindContainer(container: HTMLDivElement): void; + shouldUpdateCenter(next: Leaflet.LatLngExpression, prev: Leaflet.LatLngExpression): boolean; + shouldUpdateBounds(next: Leaflet.LatLngBoundsExpression, prev: Leaflet.LatLngBoundsExpression): boolean; +} + +export interface PaneProps { + name?: string; + children?: Children; + map?: Leaflet.Map; + className?: string; + style?: React.CSSProperties; + pane?: string; +} +export interface PaneState { + name?: string; +} +export class Pane

    extends React.Component { + getChildContext(): { pane: string }; + createPane(props: P): void; + removePane(): void; + setStyle(arg: { style?: string, className?: string }): void; + getParentPane(): HTMLElement | undefined; + getPane(name: string): HTMLElement | undefined; +} + +export interface MapLayerProps { + children?: Children; +} +export interface LayerContainer { + addLayer(layer: Leaflet.Layer): this; + removeLayer(layer: number | Leaflet.Layer): this; +} +export class MapLayer

    extends MapComponent { + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; + readonly layerContainer: LayerContainer | Leaflet.Map; +} + +export interface GridLayerProps extends Leaflet.GridLayerOptions { + children?: Children; +} +export class GridLayer

    extends MapLayer {} + +export interface TileLayerProps extends TileLayerEvents, Leaflet.TileLayerOptions { + children?: Children; + url: string; +} +export class TileLayer

    extends GridLayer { } + +export interface WMSTileLayerProps extends TileLayerEvents, Leaflet.WMSOptions { + children?: Children; + url: string; +} +export class WMSTileLayer

    extends GridLayer { } + +export interface ImageOverlayProps extends Leaflet.ImageOverlayOptions { + bounds: Leaflet.LatLngBoundsExpression; + children?: Children; + url: string; +} +export class ImageOverlay

    extends MapLayer { + getChildContext(): { popupContainer: E }; +} + +export interface LayerGroupProps { + children?: Children; +} +export class LayerGroup

    extends MapLayer { + getChildContext(): { layerContainer: E }; +} + +export interface MarkerProps extends MarkerEvents, Leaflet.MarkerOptions { + children?: Children; + position: Leaflet.LatLngExpression; +} +export class Marker

    extends MapLayer { + getChildContext(): { popupContainer: E }; +} + +export interface PathProps extends PathEvents, Leaflet.PathOptions, MapLayerProps { } +export abstract class Path

    extends MapLayer { + getChildContext(): { popupContainer: E }; + getPathOptions(props: P): Leaflet.PathOptions; + setStyle(options: Leaflet.PathOptions): void; + setStyleIfChanged(fromProps: P, toProps: P): void; +} + +export interface CircleProps extends PathEvents, Leaflet.CircleMarkerOptions { + center: Leaflet.LatLngExpression; + children?: Children; + radius: number; +} +export class Circle

    extends Path { } + +export interface CircleMarkerProps extends PathEvents, Leaflet.CircleMarkerOptions { + center: Leaflet.LatLngExpression; + children?: Children; + radius: number; +} +export class CircleMarker

    extends Path { } + +export interface FeatureGroupProps extends FeatureGroupEvents, Leaflet.PathOptions { + children?: Children; +} +export class FeatureGroup

    extends Path { + getChildContext(): { layerContainer: E, popupContainer: E }; +} + +export interface GeoJSONProps extends FeatureGroupEvents, Leaflet.GeoJSONOptions { + children?: Children; + data: GeoJSON.GeoJsonObject; + style?: Leaflet.StyleFunction; +} +export class GeoJSON

    extends Path { } + +export interface PolylineProps extends PathEvents, Leaflet.PolylineOptions { + children?: Children; + positions: Leaflet.LatLngExpression[] | Leaflet.LatLngExpression[][]; +} +export class Polyline

    extends Path { } + +export interface PolygonProps extends PathEvents, Leaflet.PolylineOptions { + children?: Children; + popupContainer?: Leaflet.FeatureGroup; + positions: Leaflet.LatLngExpression[] | Leaflet.LatLngExpression[][] | Leaflet.LatLngExpression[][][]; +} +export class Polygon

    extends Path { } + +export interface RectangleProps extends PathEvents, Leaflet.PolylineOptions { + children?: Children; + bounds: Leaflet.LatLngBoundsExpression; + popupContainer?: Leaflet.FeatureGroup; +} +export class Rectangle

    extends Path { } + +export interface PopupProps extends Leaflet.PopupOptions { + children?: Children; + position?: Leaflet.LatLngExpression; +} +export class Popup

    extends MapComponent { + onPopupOpen(arg: { popup: E }): void; + onPopupClose(arg: { popup: E }): void; + renderPopupContent(): void; + removePopupContent(): void; +} + +export interface TooltipProps extends Leaflet.TooltipOptions { + children?: Children; +} +export class Tooltip

    extends MapComponent { + onTooltipOpen(arg: { tooltip: E }): void; + onTooltipClose(arg: { tooltip: E }): void; + renderTooltipContent(): void; + removeTooltipContent(): void; +} + +export type MapControlProps = Leaflet.ControlOptions; +export class MapControl

    extends React.Component

    { + leafletElement: E; + createLeafletElement(props: P): E; + updateLeafletElement(fromProps: P, toProps: P): void; +} + +export type AttributionControlProps = Leaflet.Control.AttributionOptions; +export class AttributionControl

    extends MapControl { } + +export interface LayersControlProps extends LayersControlEvents, Leaflet.Control.LayersOptions { + baseLayers?: Leaflet.Control.LayersObject; + children?: Children; + overlays?: Leaflet.Control.LayersObject; +} +export class LayersControl

    extends MapControl { } + +export namespace LayersControl { + interface BaseControlledLayerProps { + checked?: boolean; + children?: Children; + removeLayer?(layer: Leaflet.Layer): void; + removeLayerControl?(layer: Leaflet.Layer): void; + } + interface ControlledLayerProps extends BaseControlledLayerProps { + addBaseLayer?(layer: Leaflet.Layer, name: string, checked: boolean): void; + addOverlay?(layer: Leaflet.Layer, name: string, checked: boolean): void; + name: string; + } + class ControlledLayer

    extends React.Component

    { + layer?: Leaflet.Layer; + getChildContext(): { layerContainer: LayerContainer }; + addLayer(): void; + removeLayer(layer: Leaflet.Layer): void; + } + class BaseLayer

    extends ControlledLayer

    { } + class Overlay

    extends ControlledLayer

    { } +} + +export type ScaleControlProps = Leaflet.Control.ScaleOptions; +export class ScaleControl

    extends MapControl { } + +export type ZoomControlProps = Leaflet.Control.ZoomOptions; +export class ZoomControl

    extends MapControl { } diff --git a/types/react-leaflet/v1/react-leaflet-tests.tsx b/types/react-leaflet/v1/react-leaflet-tests.tsx new file mode 100644 index 0000000000..fe9825c465 --- /dev/null +++ b/types/react-leaflet/v1/react-leaflet-tests.tsx @@ -0,0 +1,747 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import * as PropTypes from 'prop-types'; +import * as L from 'leaflet'; +import { Component } from 'react'; +import { + Children, + Circle, + CircleMarker, + FeatureGroup, + LayerGroup, + LayersControl, + Map, + MapControl, + MapControlProps, + MapProps, + Marker, + MarkerProps, + Pane, + Polygon, + Polyline, + Popup, + PopupProps, + Rectangle, + TileLayer, + Tooltip, + WMSTileLayer, + ZoomControl +} from 'react-leaflet'; +const { BaseLayer, Overlay } = LayersControl; + +/// animate.js +interface AnimateExampleState { + animate: boolean; + hasLocation: boolean; + latlng: L.LatLngExpression; +} + +export class AnimateExample extends Component { + state = { + animate: false, + hasLocation: false, + latlng: { + lat: 51.505, + lng: -0.09, + }, + }; + + handleClick = (e: L.LeafletMouseEvent) => { + this.setState({ + latlng: e.latlng, + }); + } + + toggleAnimate = () => { + this.setState({ + animate: !this.state.animate, + }); + } + + render() { + const marker = this.state.hasLocation ? ( + + + You are here + + + ) : null; + + return ( +

    + + + + {marker} + +
    + ); + } +} + +// bounds.js +const outer: L.LatLngBoundsLiteral = [ + [50.505, -29.09], + [52.505, 29.09], +]; +const inner: L.LatLngBoundsLiteral = [ + [49.505, -2.09], + [53.505, 2.09], +]; + +interface BoundsExampleState { + bounds: L.LatLngBoundsLiteral; +} + +export class BoundsExample extends Component { + state = { + bounds: outer, + }; + + onClickInner = () => { + this.setState({ bounds: inner }); + } + + onClickOuter = () => { + this.setState({ bounds: outer }); + } + + render() { + return ( + + + + + + ); + } +} + +// custom-component.js +interface MyPopupMarkerProps { + children: Children; + position: L.LatLngExpression; +} + +interface MyMarker extends MyPopupMarkerProps { + key: string; +} + +const MyPopupMarker = ({ children, position }: MyPopupMarkerProps) => ( + + + {children} + + +); + +interface MyMarkersListProps { + markers: MyMarker[]; +} + +const MyMarkersList = ({ markers }: MyMarkersListProps) => { + const items = markers.map(({ key, ...props }) => ( + + )); + return
    {items}
    ; +}; + +interface CustomComponentState { + lat: number; + lng: number; + zoom: number; +} + +export class CustomComponent extends Component { + state = { + lat: 51.505, + lng: -0.09, + zoom: 13, + }; + + render() { + const center: L.LatLngExpression = [this.state.lat, this.state.lng]; + + const markers: MyMarker[] = [ + { key: 'marker1', position: [51.5, -0.1], children: 'My first popup' }, + { key: 'marker2', position: [51.51, -0.1], children: 'My second popup' }, + { key: 'marker3', position: [51.49, -0.05], children: 'My third popup' }, + ]; + return ( + + + + + ); + } +} + +// SOURCE ??? +export class MarkerWithDivIconExample extends Component { + render() { + return ( + + + + ); + } +} + +// draggable-marker.js +interface DraggableExampleState { + center: L.LatLngLiteral; + marker: L.LatLngLiteral; + zoom: number; + draggable: boolean; +} + +export class DraggableExample extends Component { + state = { + center: { + lat: 51.505, + lng: -0.09, + }, + marker: { + lat: 51.505, + lng: -0.09, + }, + zoom: 13, + draggable: true, + }; + + toggleDraggable = () => { + this.setState({ draggable: !this.state.draggable }); + } + + updatePosition = () => { + const { + lat, + lng, + } = (this.refs.marker as Marker).leafletElement.getLatLng(); + this.setState({ + marker: { lat, lng }, + }); + } + + render() { + const position: L.LatLngExpression = [this.state.center.lat, this.state.center.lng]; + const markerPosition: L.LatLngExpression = [this.state.marker.lat, this.state.marker.lng]; + + return ( + + + + + + {this.state.draggable ? 'DRAG MARKER' : 'MARKER FIXED'} + + + + + ); + } +} + +// events.js +interface EventsExampleState { + hasLocation: boolean; + latlng: L.LatLngLiteral; +} + +export class EventsExample extends Component { + state = { + hasLocation: false, + latlng: { + lat: 51.505, + lng: -0.09, + }, + }; + + handleClick = () => { + (this.refs.map as Map).leafletElement.locate(); + } + + handleLocationFound = (e: L.LocationEvent) => { + this.setState({ + hasLocation: true, + latlng: e.latlng, + }); + } + + render() { + const marker = this.state.hasLocation ? ( + + + You are here + + + ) : null; + + return ( + + + {marker} + + ); + } +} + +// layers-control.js +export class LayersControlExample extends Component { + render() { + const center: L.LatLngExpression = [51.505, -0.09]; + const rectangle: L.LatLngBoundsExpression = [ + [51.49, -0.08], + [51.5, -0.06], + ]; + + return ( + + + + + + + + + + + + A pretty CSS3 popup.
    Easily customizable.
    +
    +
    +
    + + + + + + + + + + + + + Popup in FeatureGroup + + + + + +
    +
    + ); + } +} + +// other-layers.js +export class OtherLayersExample extends Component { + render() { + const center: L.LatLngExpression = [51.505, -0.09]; + const rectangle: L.LatLngBoundsExpression = [ + [51.49, -0.08], + [51.5, -0.06], + ]; + + return ( + + + + + + + + + + + + Popup in FeatureGroup + + + + + + ); + } +} + +// pane.js +interface PaneExampleState { + render: boolean; +} + +export class PaneExample extends Component { + state = { + render: true, + }; + + componentDidMount() { + setInterval(() => { + this.setState({ + render: !this.state.render, + }); + }, 5000); + } + + render() { + return ( + + + {this.state.render ? ( + + + + ) : null} + + + + + + + + ); + } +} + +// simple.js +interface SimpleExampleState { + lat: number; + lng: number; + zoom: number; +} + +export class SimpleExample extends Component { + state = { + lat: 51.505, + lng: -0.09, + zoom: 13, + }; + + render() { + const position: L.LatLngExpression = [this.state.lat, this.state.lng]; + return ( + + + + + A pretty CSS3 popup.
    Easily customizable.
    +
    +
    +
    + ); + } +} + +// tooltip.js +interface TooltipExampleState { + clicked: number; +} + +export class TooltipExample extends Component { + state = { + clicked: 0, + }; + + onClickCircle = () => { + this.setState({ clicked: this.state.clicked + 1 }); + } + + render() { + const center: L.LatLngExpression = [51.505, -0.09]; + + const multiPolygon: L.LatLngExpression[][] = [ + [[51.51, -0.12], [51.51, -0.13], [51.53, -0.13]], + [[51.51, -0.05], [51.51, -0.07], [51.53, -0.07]], + ]; + + const rectangle: L.LatLngBoundsExpression = [ + [51.49, -0.08], + [51.5, -0.06], + ]; + + const clickedText = this.state.clicked === 0 + ? 'Click this Circle to change the Tooltip text' + : `Circle click: ${this.state.clicked}`; + + return ( + + + + + {clickedText} + + + + + Tooltip for CircleMarker + + + + + Popup for Marker + + + Tooltip for Marker + + + + + sticky Tooltip for Polygon + + + + + permanent Tooltip for Rectangle + + + + ); + } +} + +// vector-layers.js +export class VectorLayersExample extends Component { + render() { + const center: L.LatLngExpression = [51.505, -0.09]; + + const polyline: L.LatLngExpression[] = [ + [51.505, -0.09], + [51.51, -0.1], + [51.51, -0.12], + ]; + + const multiPolyline: L.LatLngExpression[][] = [ + [[51.5, -0.1], [51.5, -0.12], [51.52, -0.12]], + [[51.5, -0.05], [51.5, -0.06], [51.52, -0.06]], + ]; + + const polygon: L.LatLngExpression[] = [ + [51.515, -0.09], + [51.52, -0.1], + [51.52, -0.12], + ]; + + const multiPolygon: L.LatLngExpression[][] = [ + [[51.51, -0.12], [51.51, -0.13], [51.53, -0.13]], + [[51.51, -0.05], [51.51, -0.07], [51.53, -0.07]], + ]; + + const rectangle: L.LatLngBoundsExpression = [ + [51.49, -0.08], + [51.5, -0.06], + ]; + + return ( + + + + + + Popup in CircleMarker + + + + + + + + + ); + } +} + +// wms-tile-layer.js +interface WMSTileLayerExampleState { + lat: number; + lng: number; + zoom: number; + bluemarble: boolean; +} + +export class WMSTileLayerExample extends Component { + state = { + lat: 51.505, + lng: -0.09, + zoom: 5, + bluemarble: false, + }; + + onClick = () => { + this.setState({ + bluemarble: !this.state.bluemarble, + }); + } + + render() { + return ( + + + + + ); + } +} + +// zoom-control.js +const ZoomControlExample = () => ( + + + + +); + +// MapControl https://github.com/PaulLeCam/react-leaflet/issues/130 +class CenterControl extends MapControl { // note we're extending MapControl from react-leaflet, not Component from react + componentWillMount() { + const centerControl = new L.Control({ position: 'bottomright' }); // see http://leafletjs.com/reference.html#control-positions for other positions + const jsx = ( + // PUT YOUR JSX FOR THE COMPONENT HERE: +
    + {/* add your JSX */} +
    + ); + + centerControl.onAdd = (map) => { + const div = L.DomUtil.create('div', ''); + ReactDOM.render(jsx, div); + return div; + }; + + this.leafletElement = centerControl; + } +} + +const mapControlCenter: L.LatLngExpression = [51.505, -0.09]; + +const CenterControlExample = () => ( + + + +); + +class LegendControl extends MapControl { + componentWillMount() { + const legend = new L.Control({ position: 'bottomright' }); + const jsx = ( +
    + {this.props.children} +
    + ); + + legend.onAdd = (map) => { + const div = L.DomUtil.create('div', ''); + ReactDOM.render(jsx, div); + return div; + }; + + this.leafletElement = legend; + } +} + +const LegendControlExample = () => ( + + + +
      +
    • Strong Support
    • +
    • Weak Support
    • +
    • Weak Oppose
    • +
    • Strong Oppose
    • +
    +
    +
    +); diff --git a/types/react-leaflet/v1/tsconfig.json b/types/react-leaflet/v1/tsconfig.json new file mode 100644 index 0000000000..bb2d85cfe8 --- /dev/null +++ b/types/react-leaflet/v1/tsconfig.json @@ -0,0 +1,33 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "jsx": "react", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "react-leaflet": [ + "react-leaflet/v1" + ], + "react-leaflet/*": [ + "react-leaflet/v1/*" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-leaflet-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-leaflet/v1/tslint.json b/types/react-leaflet/v1/tslint.json new file mode 100644 index 0000000000..440efbd687 --- /dev/null +++ b/types/react-leaflet/v1/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-duplicate-imports": false + } +} 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-dialog/index.d.ts b/types/react-native-dialog/index.d.ts index 14d7458140..50866d6d0c 100644 --- a/types/react-native-dialog/index.d.ts +++ b/types/react-native-dialog/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native-dialog 4.0 +// Type definitions for react-native-dialog 5.5 // Project: https://github.com/mmazzarolo/react-native-dialog // Definitions by: MrLuje // Stack Builders @@ -39,6 +39,10 @@ interface ContainerProps { * default: false */ visible?: boolean; + buttonSeparatorStyle?: ViewStyle; + contentStyle?: ViewStyle; + footerStyle?: ViewStyle; + headerStyle?: ViewStyle; } interface TitleProps { 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-percentage-circle/index.d.ts b/types/react-native-percentage-circle/index.d.ts new file mode 100644 index 0000000000..a1762ab962 --- /dev/null +++ b/types/react-native-percentage-circle/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for react-native-percentage-circle 1.0 +// Project: https://github.com/JackPu/react-native-percentage-circle +// Definitions by: Haseeb Majid +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +import { TextStyle } from 'react-native'; + +export interface PercentageCircleProps { + color?: string; + bgcolor?: string; + innerColor?: string; + radius?: number; + percent?: number; + borderWidth?: number; + textStyle?: TextStyle[]; + disabled?: boolean; +} + +export default class PercentageCircle extends React.Component {} diff --git a/types/react-native-percentage-circle/react-native-percentage-circle-tests.tsx b/types/react-native-percentage-circle/react-native-percentage-circle-tests.tsx new file mode 100644 index 0000000000..7c016122d9 --- /dev/null +++ b/types/react-native-percentage-circle/react-native-percentage-circle-tests.tsx @@ -0,0 +1,20 @@ +import * as React from "react"; +import { View } from "react-native"; +import PercentageCircle from "react-native-percentage-circle"; + +class PercentageCircleTest extends React.Component { + render() { + return ( + + + + ); + } +} diff --git a/types/react-native-percentage-circle/tsconfig.json b/types/react-native-percentage-circle/tsconfig.json new file mode 100644 index 0000000000..77789ef23c --- /dev/null +++ b/types/react-native-percentage-circle/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react-native" + }, + "files": [ + "index.d.ts", + "react-native-percentage-circle-tests.tsx" + ] +} diff --git a/types/react-native-percentage-circle/tslint.json b/types/react-native-percentage-circle/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-percentage-circle/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-snackbar-component/index.d.ts b/types/react-native-snackbar-component/index.d.ts new file mode 100644 index 0000000000..dfa31773e4 --- /dev/null +++ b/types/react-native-snackbar-component/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for react-native-snackbar-components 1.1 +// Project: https://github.com/sidevesh/react-native-snackbar +// Definitions by: Haseeb Majid +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +import { TextStyle } from 'react-native'; + +export interface SnackbarComponentProps { + accentColor?: string; + actionText?: string; + messageColor?: string; + backgroundColor?: string; + distanceCallback?: () => void; + actionHandler?: () => void; + left?: number; + right?: number; + bottom?: number; + position?: string; + textMessage?: string; + autoHidingTime?: number; + visible?: boolean; +} + +export default class SnackbarComponent extends React.Component {} diff --git a/types/react-native-snackbar-component/react-native-snackbar-component-tests.tsx b/types/react-native-snackbar-component/react-native-snackbar-component-tests.tsx new file mode 100644 index 0000000000..1795cce93a --- /dev/null +++ b/types/react-native-snackbar-component/react-native-snackbar-component-tests.tsx @@ -0,0 +1,18 @@ +import * as React from "react"; +import { View } from "react-native"; +import SnackbarComponent from "react-native-snackbar-component"; + +class SnackbarComponentTest extends React.Component { + render() { + return ( + + + + ); + } +} diff --git a/types/react-native-snackbar-component/tsconfig.json b/types/react-native-snackbar-component/tsconfig.json new file mode 100644 index 0000000000..7205073e63 --- /dev/null +++ b/types/react-native-snackbar-component/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react-native" + }, + "files": [ + "index.d.ts", + "react-native-snackbar-component-tests.tsx" + ] +} diff --git a/types/react-native-snackbar-component/tslint.json b/types/react-native-snackbar-component/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-snackbar-component/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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-swipeable-views/index.d.ts b/types/react-swipeable-views/index.d.ts index 68545673e6..24fbaf618d 100644 --- a/types/react-swipeable-views/index.d.ts +++ b/types/react-swipeable-views/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-swipeable-views 0.12 +// Type definitions for react-swipeable-views 0.13 // Project: https://github.com/oliviertassinari/react-swipeable-views // Definitions by: Michael Ledin // Deividas Bakanas @@ -29,6 +29,10 @@ export interface SwipeableViewsProps extends React.HTMLProps { axis?: AxisType; containerStyle?: React.CSSProperties; disabled?: boolean; + /* + * This is the config used to disable lazy loading, if true it will render all the views in first rendering. + */ + disableLazyLoading?: boolean; enableMouseEvents?: boolean; hysteresis?: number; ignoreNativeScroll?: boolean; diff --git a/types/react-swipeable-views/react-swipeable-views-tests.ts b/types/react-swipeable-views/react-swipeable-views-tests.ts index e35be787fb..0bdc2fabfd 100644 --- a/types/react-swipeable-views/react-swipeable-views-tests.ts +++ b/types/react-swipeable-views/react-swipeable-views-tests.ts @@ -44,7 +44,8 @@ React.createElement(SwipeableViews, { title: "Carousel", onTransitionEnd, axis: "x-reverse", - springConfig + springConfig, + disableLazyLoading: false }); React.createElement(SwipeableViews, {}); diff --git a/types/react-tooltip/index.d.ts b/types/react-tooltip/index.d.ts index 9030a2c1f4..aba9cdf734 100644 --- a/types/react-tooltip/index.d.ts +++ b/types/react-tooltip/index.d.ts @@ -79,6 +79,7 @@ declare namespace ReactTooltip { } interface Props { + children?: React.ReactNode; id?: string; place?: Place; type?: Type; 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} /> + = + type ElementType

    = { [K in keyof JSX.IntrinsicElements]: P extends JSX.IntrinsicElements[K] ? K : never }[keyof JSX.IntrinsicElements] | ComponentType

    ; + /** + * @deprecated Please use `ElementType` + */ + type ReactType

    = ElementType

    ; type ComponentType

    = ComponentClass

    | FunctionComponent

    ; type JSXElementConstructor

    = @@ -422,7 +426,7 @@ declare namespace React { // always pass children as variadic arguments to `createElement`. // In the future, if we can define its call signature conditionally // on the existence of `children` in `P`, then we should remove this. - readonly props: Readonly<{ children?: ReactNode }> & Readonly

    ; + readonly props: Readonly>; state: Readonly; /** * @deprecated @@ -468,7 +472,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 +480,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 +726,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. @@ -732,11 +738,11 @@ declare namespace React { : T extends keyof JSX.IntrinsicElements ? JSX.IntrinsicElements[T] : {}; - type ComponentPropsWithRef = + type ComponentPropsWithRef = T extends ComponentClass ? PropsWithoutRef

    & RefAttributes> : PropsWithRef>; - type ComponentPropsWithoutRef = + type ComponentPropsWithoutRef = PropsWithoutRef>; // will show `Memo(${Component.displayName || Component.name})` in devtools by default, @@ -747,7 +753,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 88d286159a..44f97c933b 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -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/rivets/rivets-tests.ts b/types/rivets/rivets-tests.ts index 81c97e7d9e..67beebdc13 100644 --- a/types/rivets/rivets-tests.ts +++ b/types/rivets/rivets-tests.ts @@ -10,7 +10,7 @@ Rivets.configure({ // Template delimiters for text bindings templateDelimiters: ['[[', ']]'], // Augment the event handler of the on-* binder - handler: (target: any, event: any, binding: any) => { + handler(target: any, event: any, binding: any) { this.call(target, event, binding.view.models); } }); 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/rtlcss/index.d.ts b/types/rtlcss/index.d.ts new file mode 100644 index 0000000000..3e2dcb1711 --- /dev/null +++ b/types/rtlcss/index.d.ts @@ -0,0 +1,80 @@ +// Type definitions for rtlcss 2.4 +// Project: http://rtlcss.com +// Definitions by: Adam Zerella +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.3 + +export interface MapOptions { + scope: string; + ignoreCase: boolean; + greedy?: boolean; +} + +export interface StringMap { + name: string; + priority: number; + exclusive?: boolean; + search: string|string[]; + replace: string|string[]; + options: MapOptions; +} + +export interface ConfigOptions { + /** + * Applies to CSS rules containing no directional properties, + * it will update the selector by applying String Map. + */ + autoRename: boolean; + /** + * Ensures autoRename is applied only if pair exists. + */ + autoRenameStrict: boolean; + /** + * An object map of disabled plugins directives, + * where keys are plugin names and value are object + * hash of disabled directives. e.g. {'rtlcss':{'config':true}}. + */ + blacklist: object; + /** + * Removes directives comments from output CSS. + */ + clean: boolean; + /** + * Fallback value for String Map options. + */ + greedy: boolean; + /** + * Applies String Map to URLs. You can also target specific node types using an object literal. + * e.g. {'atrule': true, 'decl': false}. + */ + processUrls: boolean|object; + /** + * The default array of String Map. + */ + stringMap: StringMap[]; + /** + * When enabled, flips background-position expressed in length units using calc. + */ + useCalc: boolean; +} + +export interface HookOptions { + /** + * The function to be called before processing the CSS. + */ + pre: () => void; + /** + * The function to be called after processing the CSS. + */ + post: () => void; +} + +/** + * Creates a new RTLCSS instance, process the input and return its result. + */ +export function process(css: string, options?: object, plugins?: object|string[], hooks?: HookOptions): string; + +/** + * Creates a new instance of RTLCSS using the passed configuration object. + */ +export function configure(config: ConfigOptions): object; diff --git a/types/rtlcss/rtlcss-tests.ts b/types/rtlcss/rtlcss-tests.ts new file mode 100644 index 0000000000..1355074c56 --- /dev/null +++ b/types/rtlcss/rtlcss-tests.ts @@ -0,0 +1,27 @@ +import * as rtlcss from "rtlcss"; + +rtlcss.process("body { direction:ltr; }"); + +const config = { + autoRename: false, + autoRenameStrict: false, + blacklist: {}, + clean: true, + greedy: false, + processUrls: false, + stringMap: [ + { + name : 'left-right', + priority: 100, + search : ['left', 'Left', 'LEFT'], + replace : ['right', 'Right', 'RIGHT'], + options : { + scope : '*', + ignoreCase : false + } + } + ], + useCalc: false +}; + +rtlcss.configure(config); diff --git a/types/rtlcss/tsconfig.json b/types/rtlcss/tsconfig.json new file mode 100644 index 0000000000..94644d49ad --- /dev/null +++ b/types/rtlcss/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", + "rtlcss-tests.ts" + ] +} diff --git a/types/rtlcss/tslint.json b/types/rtlcss/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/rtlcss/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/rx-angular/rx-angular-tests.ts b/types/rx-angular/rx-angular-tests.ts index f2413695af..25d0f1887b 100644 --- a/types/rx-angular/rx-angular-tests.ts +++ b/types/rx-angular/rx-angular-tests.ts @@ -8,7 +8,7 @@ var app = angular.module('testModule'); interface AppScope extends rx.angular.IRxScope { } -app.controller('Ctrl', ($scope: AppScope) => { +app.controller('Ctrl', function ($scope: AppScope) { this.inputObservable = $scope.$toObservable('term') .safeApply($scope, (results: any) => { 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/screenfull/index.d.ts b/types/screenfull/index.d.ts index 0ca3d642b9..2c7b93e453 100644 --- a/types/screenfull/index.d.ts +++ b/types/screenfull/index.d.ts @@ -1,36 +1,85 @@ -// Type definitions for screenfull.js 3.3.3 +// Type definitions for screenfull.js 4.0 // Project: https://github.com/sindresorhus/screenfull.js // Definitions by: Ilia Choly // lionelb // Joel Shepherd +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.5 -declare var screenfull: IScreenfull | false; - -interface IScreenfullRaw { - requestFullscreen?: string; - exitFullscreen?: string; - fullscreenElement?: string; - fullscreenEnabled?: string; - fullscreenchange?: string; - fullscreenerror?: string; -} - -interface IScreenfull { - isFullscreen: boolean; - element: Element; - enabled: boolean; - raw: IScreenfullRaw; - request(elem?: Element): void; - toggle(elem?: Element): void; - exit(): void; - onchange(handler: () => void): void; - onerror(handler: (event: Event) => void): void; - on(name: EventNameMap, handler: (event: Event) => void): void; - off(name: EventNameMap, handler: (event: Event) => void): void; -} - -type EventNameMap = 'change' | 'error'; - export = screenfull; +export as namespace screenfull; + +declare const screenfull: screenfull.Screenfull | false; + +declare namespace screenfull { + interface Screenfull { + /** + * Returns a boolean whether fullscreen is active. + */ + readonly isFullscreen: boolean; + /** + * Returns the element currently in fullscreen, otherwise `null`. + */ + readonly element: Element | null; + /** + * Returns a boolean whether you are allowed to enter fullscreen. If your page is inside an `