diff --git a/types/async-retry/async-retry-tests.ts b/types/async-retry/async-retry-tests.ts index 68327b66bd..20dfc62c4b 100644 --- a/types/async-retry/async-retry-tests.ts +++ b/types/async-retry/async-retry-tests.ts @@ -10,12 +10,12 @@ const o: Options = { onRetry: (e: Error) => 42 }; -retry( +const hello: Promise = retry( bail => 'hello', { retries: 3 } ); -retry( +const answer: Promise = retry( bail => Promise.resolve(42), { retries: 3 } ); diff --git a/types/async-retry/index.d.ts b/types/async-retry/index.d.ts index a2f65e00a4..6b50c71b63 100644 --- a/types/async-retry/index.d.ts +++ b/types/async-retry/index.d.ts @@ -19,7 +19,7 @@ declare namespace AsyncRetry { onRetry?: (e: Error) => any; } - type RetryFunction = (bail: (e: Error) => A, attempt: number) => A|Promise; + type RetryFunction = (bail: (e: Error) => void, attempt: number) => A|Promise; } export = AsyncRetry; diff --git a/types/elasticsearch/elasticsearch-tests.ts b/types/elasticsearch/elasticsearch-tests.ts index 3236a181a1..35b4e39798 100644 --- a/types/elasticsearch/elasticsearch-tests.ts +++ b/types/elasticsearch/elasticsearch-tests.ts @@ -206,7 +206,8 @@ client.mget({ index: 'myindex', type: 'mytype', body: { - ids: [1, 2, 3] + ids: [1, 2, 3], + _source: ['test'] } }, (error, response) => { // ... diff --git a/types/elasticsearch/index.d.ts b/types/elasticsearch/index.d.ts index 7973b598ab..2cfd14f689 100644 --- a/types/elasticsearch/index.d.ts +++ b/types/elasticsearch/index.d.ts @@ -465,7 +465,7 @@ export interface MGetParams extends GenericParams { preference?: string; realtime?: boolean; refresh?: boolean; - source?: NameList; + _source?: NameList; _sourceExclude?: NameList; _sourceInclude?: NameList; index?: string; diff --git a/types/express-serve-static-core/index.d.ts b/types/express-serve-static-core/index.d.ts index f8521d433d..96c4c233c2 100644 --- a/types/express-serve-static-core/index.d.ts +++ b/types/express-serve-static-core/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Express 4.11 +// Type definitions for Express 4.16 // Project: http://expressjs.com // Definitions by: Boris Yankov // Michał Lytek @@ -23,6 +23,7 @@ declare global { import * as http from "http"; import { EventEmitter } from "events"; +import { Options as RangeParserOptions, Result as RangeParserResult, Ranges as RangeParserRanges } from "range-parser"; export interface NextFunction { // tslint:disable-next-line callable-types (In ts2.1 it thinks the type alias has no call signatures) @@ -174,7 +175,7 @@ export interface CookieOptions { export interface ByteRange { start: number; end: number; } -export interface RequestRanges extends Array { type: string; } +export interface RequestRanges extends RangeParserRanges { } export type Errback = (err: Error) => void; @@ -283,21 +284,19 @@ export interface Request extends http.IncomingMessage, Express.Request { acceptsLanguages(...lang: string[]): string | false; /** - * Parse Range header field, - * capping to the given `size`. + * Parse Range header field, capping to the given `size`. * - * Unspecified ranges such as "0-" require - * knowledge of your resource length. In - * the case of a byte range this is of course - * the total number of bytes. If the Range - * header field is not given `null` is returned, - * `-1` when unsatisfiable, `-2` when syntactically invalid. + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. + * If the Range header field is not given `undefined` is returned. + * If the Range header field is given, return value is a result of range-parser. + * See more ./types/range-parser/index.d.ts + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. * - * NOTE: remember that ranges are inclusive, so - * for example "Range: users=0-3" should respond - * with 4 users when available, not 3. */ - range(size: number): RequestRanges|null|-1|-2; + range(size: number, options?: RangeParserOptions): RangeParserRanges | RangeParserResult | undefined; /** * Return an array of Accepted media types @@ -450,6 +449,13 @@ export interface Request extends http.IncomingMessage, Express.Request { baseUrl: string; app: Application; + + /** + * After middleware.init executed, Request will contain res and next properties + * See: express/lib/middleware/init.js + */ + res?: Response; + next?: NextFunction; } export interface MediaType { @@ -827,7 +833,13 @@ export interface Response extends http.ServerResponse, Express.Response { * * @since 4.11.0 */ - append(field: string, value?: string[]|string): Response; + append(field: string, value?: string[] | string): Response; + + /** + * After middleware.init executed, Response will contain req property + * See: express/lib/middleware/init.js + */ + req?: Request; } export interface Handler extends RequestHandler { } @@ -1062,6 +1074,22 @@ export interface Application extends EventEmitter, IRouter, Express.Application _router: any; use: ApplicationRequestHandler; + + /** + * The mount event is fired on a sub-app, when it is mounted on a parent app. + * The parent app is passed to the callback function. + * + * NOTE: + * Sub-apps will: + * - Not inherit the value of settings that have a default value. You must set the value in the sub-app. + * - Inherit the value of settings with no default value. + */ + on: (event: string, callback: (parent: Application) => void) => this; + + /** + * The app.mountpath property contains one or more path patterns on which a sub-app was mounted. + */ + mountpath: string | string[]; } export interface Express extends Application { diff --git a/types/express/express-tests.ts b/types/express/express-tests.ts index 137c70c8e8..07bf2fc5c3 100644 --- a/types/express/express-tests.ts +++ b/types/express/express-tests.ts @@ -104,6 +104,9 @@ namespace express_tests { req.headers.existingHeader as string; req.headers.nonExistingHeader as any as undefined; + // Since 4.14.0 req.range() has options + req.range(2, { combine: true }); + res.send(req.query['token']); }); @@ -128,6 +131,19 @@ namespace express_tests { app.use(router); + // Test req.res, req.next, res.req should exists after middleware.init + app.use((req, res) => { + req.res; + req.next; + res.req; + }); + + // Test on mount event + app.on('mount', (parent) => true); + + // Test mountpath + const mountPath: string|string[] = app.mountpath; + app.listen(3000); const next: express.NextFunction = () => { }; @@ -139,6 +155,7 @@ namespace express_tests { * * ***************************/ import * as http from 'http'; +import { RequestRanges } from 'express-serve-static-core'; namespace node_tests { { diff --git a/types/express/index.d.ts b/types/express/index.d.ts index 4e6ed8fcc1..81821ca98c 100644 --- a/types/express/index.d.ts +++ b/types/express/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Express 4.11 +// Type definitions for Express 4.16 // Project: http://expressjs.com // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/helmet/index.d.ts b/types/helmet/index.d.ts index a78e768688..0162912d99 100644 --- a/types/helmet/index.d.ts +++ b/types/helmet/index.d.ts @@ -20,6 +20,7 @@ declare namespace helmet { ieNoOpen?: boolean, noCache?: boolean, noSniff?: boolean, + referrerPolicy?: boolean | IHelmetReferrerPolicyConfiguration, xssFilter?: boolean | IHelmetXssFilterConfiguration, expectCt?: boolean | IHelmetExpectCtConfiguration, } diff --git a/types/imperium/imperium-tests.ts b/types/imperium/imperium-tests.ts new file mode 100644 index 0000000000..f7380c25cc --- /dev/null +++ b/types/imperium/imperium-tests.ts @@ -0,0 +1,19 @@ +import imperium from 'imperium'; + +imperium.role('admin', async (req) => { + return true; +}); + +imperium.role('user') + .can('seeUser', { user: '@' }) + .can('manageUser', { user: '@' }); + +imperium.role('admin') + .is('user', { user: '*' }); + +imperium.can('seeUser'); +imperium.can(['seeUser', 'manageUser']); +imperium.can({ action: 'seeUser', user: ':userId' }); +imperium.can([{ action: 'manageUser', user: ':userId' }]); +imperium.is('admin'); +imperium.is(['admin', 'user']); diff --git a/types/imperium/index.d.ts b/types/imperium/index.d.ts new file mode 100644 index 0000000000..67eace244e --- /dev/null +++ b/types/imperium/index.d.ts @@ -0,0 +1,98 @@ +// Type definitions for imperium 2.0 +// Project: https://www.npmjs.org/package/imperium +// Definitions by: Gaetan SENN +// Definitions: https://github.com/psnider/DefinitelyTyped/imperium +// TypeScript Version: 2.7 + +/// + +import express = require('express'); + +export type GetAcl = (req: express.Request) => Promise | Promise; +export type Actions = string[] | string; +export type Context = Array<'params' | 'query' | 'headers' | 'body'>; +// Can contain when key that is evaluated during route action +export interface RoleParams { + [key: string]: string; +} + +export const context: string[]; +export const roles: Roles; + +// Add new role with specific ImperiumGetAcl +export function role(roleName: string, getAcl?: GetAcl): Role; + +// Check if user has role(s) act like as an OR +export function is(roleNames: string | string[]): Promise; + +// Check if current user can do action(s) +export function can(actionS: string | string[] | Action | Action[]): Promise; + +export function evaluateRouteActions(req: express.Request, action: Action[], context: Context): Actions; + +export function evaluateRouteAction(req: express.Request, expr: string, key: string, context: Context): string; + +export function evaluateUserActions(req: express.Request, roles: Role[]): Promise; + +export function evaluateUserAction(action: RoleParams, context: { [key: string]: string[] }): { [key: string]: string[] }; + +export class Imperium { + constructor() + + context: string[]; + roles: Roles; + + // Add new role with specific ImperiumGetAcl + role(roleName: string, getAcl?: GetAcl): Role; + + // Check if user has role(s) act like as an OR + is(roleNames: string | string[]): Promise; + + // Check if current user can do action(s) + can(actionS: string | string[] | Action | Action[]): Promise; + + private addRole(roleName: string, getAcl: GetAcl): void; + + evaluateRouteActions(req: express.Request, action: Action[], context: Context): Actions; + + evaluateRouteAction(req: express.Request, expr: string, key: string, context: Context): string; + + evaluateUserActions(req: express.Request, roles: Role[]): Promise; + + evaluateUserAction(action: RoleParams, context: { [key: string]: string[] }): { [key: string]: string[] }; +} + +export interface Roles { + [key: string]: RoleActions; +} + +export interface RoleActions { + actions: Action[]; + getAcl?: GetAcl; +} + +export interface Action { + action: string; + [key: string]: string; +} + +export class Role { + constructor(imperium: Imperium, roleName: string) + + // Imperium instance to retreive child role + imperium: Imperium; + // Role name + roleName: string; + // Contain all the actions for this specific role + role: RoleActions; + + /* Add action with specific params */ + can(action: string, params: RoleParams): Role; + + /* Get actions of childRoleName and replace params */ + is(childRoleName: string, params: RoleParams): Role; +} + +export class UnauthorizedError extends Error { + constructor(message: string, status: number, context: any) +} diff --git a/types/imperium/tsconfig.json b/types/imperium/tsconfig.json new file mode 100644 index 0000000000..caaa7b74ce --- /dev/null +++ b/types/imperium/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "esModuleInterop": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "imperium-tests.ts" + ] +} diff --git a/types/imperium/tslint.json b/types/imperium/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/imperium/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/jquery-mouse-exit/index.d.ts b/types/jquery-mouse-exit/index.d.ts new file mode 100644 index 0000000000..f0ba17996e --- /dev/null +++ b/types/jquery-mouse-exit/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for jquery-mouse-exit 1.0 +// Project: https://github.com/makeup-jquery/jquery-mouse-exit +// Definitions by: Anderson Friaça +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +export type Options = Partial<{ + delay: number; +}>; + +export type FocusElements = Partial<{ + lostFocus: HTMLElement; + gainedFocus: HTMLElement; +}>; + +declare global { + interface JQuery { + mouseExit(options?: Options): JQuery; + on(event: 'mouseExit', handler: ((event: JQuery.Event, data: FocusElements) => void)): JQuery; + } +} diff --git a/types/jquery-mouse-exit/jquery-mouse-exit-tests.ts b/types/jquery-mouse-exit/jquery-mouse-exit-tests.ts new file mode 100644 index 0000000000..7ae495ee1b --- /dev/null +++ b/types/jquery-mouse-exit/jquery-mouse-exit-tests.ts @@ -0,0 +1,9 @@ +// init plugin +$('#container').mouseExit({ + delay: 500 +}); + +// handle event +$('#container').on('mouseExit', (e, data) => { + console.log(data.lostFocus, data.gainedFocus); +}); diff --git a/types/jquery-mouse-exit/tsconfig.json b/types/jquery-mouse-exit/tsconfig.json new file mode 100644 index 0000000000..a9bc588d0d --- /dev/null +++ b/types/jquery-mouse-exit/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "jquery-mouse-exit-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jquery-mouse-exit/tslint.json b/types/jquery-mouse-exit/tslint.json new file mode 100644 index 0000000000..d04fe2e1fa --- /dev/null +++ b/types/jquery-mouse-exit/tslint.json @@ -0,0 +1 @@ +{"extends": "dtslint/dt.json"} \ No newline at end of file diff --git a/types/jsforce/cache.d.ts b/types/jsforce/cache.d.ts new file mode 100644 index 0000000000..35241eb639 --- /dev/null +++ b/types/jsforce/cache.d.ts @@ -0,0 +1,21 @@ +import { EventEmitter } from 'events'; + +export class CacheEntry extends EventEmitter { + get(callback?: (err: Error, result: T) => void): T | undefined; + set(value: T): void; + clear(): void; +} + +export class Cache { + /** + * Clear cache entries prefix matching given key + * @param key Key prefix of cache entry to clear + */ + clear(key?: string): void; + + /** + * Retrieve cache entry, or create if not exists + * @param key Key of cache entry + */ + get(key?: string): CacheEntry; +} \ No newline at end of file diff --git a/types/jsforce/connection.d.ts b/types/jsforce/connection.d.ts index 32ed4de267..fcf614eb92 100644 --- a/types/jsforce/connection.d.ts +++ b/types/jsforce/connection.d.ts @@ -8,6 +8,7 @@ import { Analytics } from './api/analytics'; import { Chatter } from './api/chatter'; import { Metadata } from './api/metadata'; import { Bulk } from './bulk'; +import { Cache } from './cache' import { OAuth2, Streaming } from '.'; export type Callback = (err: Error, result: T) => void; @@ -111,7 +112,17 @@ export abstract class BaseConnection extends EventEmitter { callback?: (err: Error, result: RecordResult | RecordResult[]) => void): Promise<(RecordResult | RecordResult[])>; destroy(type: string, ids: string | string[], options?: Object, callback?: (err: Error, result: RecordResult | RecordResult[]) => void): Promise<(RecordResult | RecordResult[])>; - describe(type: string, callback?: (err: Error, result: DescribeSObjectResult) => void): Promise; + describe$: { + /** Returns a value from the cache if it exists, otherwise calls Connection.describe */ + (type: string, callback?: (err: Error, result: DescribeSObjectResult) => void): DescribeSObjectResult; + clear(): void; + } + describe(type: string, callback?: (err: Error, result: DescribeSObjectResult) => void): Promise; + describeGlobal$: { + /** Returns a value from the cache if it exists, otherwise calls Connection.describeGlobal */ + (callback?: (err: Error, result: DescribeGlobalResult) => void): DescribeGlobalResult; + clear(): void; + } describeGlobal(callback?: (err: Error, result: DescribeGlobalResult) => void): Promise; sobject(resource: string): SObject; } @@ -126,6 +137,7 @@ export class Connection extends BaseConnection { bulk: Bulk; oauth2: OAuth2; streaming: Streaming; + cache: Cache; // Specific to Connection instanceUrl: string; diff --git a/types/jsforce/describe-result.d.ts b/types/jsforce/describe-result.d.ts index 352c4223a6..17da9f5917 100644 --- a/types/jsforce/describe-result.d.ts +++ b/types/jsforce/describe-result.d.ts @@ -1,9 +1,217 @@ +type maybe = (T | null | undefined) + +// From +// https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_describesobjects_describesobjectresult.htm export interface DescribeSObjectResult { + activateable: boolean; + actionOverrides?: maybe; + childRelationships: ChildRelationship[]; + compactLayoutable: boolean; + createable: boolean; + custom: boolean; + customSetting: boolean; + deleteable: boolean; + deprecatedAndHidden: boolean; + feedEnabled: boolean; + fields: Field[]; + keyPrefix?: maybe; label: string; - fields: object[]; + labelPlural: string; + layoutable: boolean; + listviewable?: maybe; + lookupLayoutable?: maybe; + mergeable: boolean; + mruEnabled: boolean; + name: string; + namedLayoutInfos: NamedLayoutInfo[]; + networkScopeFieldName?: maybe; + queryable: boolean; + recordTypeInfos: RecordTypeInfo[]; + replicateable: boolean; + retrieveable: boolean; + searchable: boolean; + searchLayoutable: boolean; + supportedScopes: ScopeInfo[]; + triggerable: boolean; + undeleteable: boolean; + updateable: boolean; + urlDetail?: string; + urlEdit?: string; + urlNew?: string; + urls: Record; } -export interface DescribeGlobalResult { +export interface ActionOverride { + formFactor: string; + isAvailableInTouch: boolean; + name: string; + pageId: string; + url?: maybe; +} + +export interface ChildRelationship { + cascadeDelete: boolean; + childSObject: string; + deprecatedAndHidden: boolean; + field: string; + junctionIdListNames: string[]; + junctionReferenceTo: string[]; + relationshipName?: maybe; + restrictedDelete: boolean; +} + +export interface Field { + aggregatable: boolean; + autonumber: boolean; + byteLength: number; + calculated: boolean; + calculatedFormula?: maybe; + cascadeDelete: boolean; + caseSensitive: boolean; + compoundFieldName?: maybe; + controllerName?: maybe; + creatable: boolean; + custom: boolean; + defaultValue?: maybe; + defaultValueFormula?: maybe; + defaultedOnCreate: boolean; + dependentPicklist: boolean; + deprecatedAndHidden: boolean; + digits?: maybe; + displayLocationInDecimal?: maybe; + encrypted?: maybe; + externalId: boolean; + extraTypeInfo?: maybe; + filterable: boolean; + filteredLookupInfo?: maybe; + formula?: maybe; + groupable: boolean; + highScaleNumber?: maybe; + htmlFormatted :boolean; + idLookup: boolean; + inlineHelpText?: maybe; + label: string; + length: number; + mask?: maybe; + maskType?: maybe; + name: string; + nameField: boolean; + namePointing: boolean; + nillable: boolean; + permissionable: boolean; + picklistValues?: maybe; + polymorphicForeignKey: boolean; + precision?: maybe; + queryByDistance: boolean; + relationshipName?: maybe; + relationshipOrder?: maybe; + referenceTargetField?: maybe; + referenceTo?: maybe; + restrictedPicklist: boolean; + scale: number; + searchPrefilterable: boolean; + soapType: SOAPType; + sortable: boolean; + type: FieldType; + unique: boolean; + updateable: boolean; + writeRequiresMasterRead?: maybe; +} + +export type ExtraTypeInfo = + | 'imageurl' + | 'personname' + | 'plaintextarea' + | 'richtextarea' + | 'switchablepersonname' + | 'externallookup' + | 'indirectlookup' + +export type FieldType = + | 'string' + | 'boolean' + | 'int' + | 'double' + | 'date' + | 'datetime' + | 'base64' + | 'id' + | 'reference' + | 'currency' + | 'textarea' + | 'percent' + | 'phone' + | 'url' + | 'email' + | 'combobox' + | 'picklist' + | 'multipicklist' + | 'anyType' + | 'location' + // the following are not found in official documentation, but still occur when describing an sobject + | 'time' + | 'encryptedstring' + | 'address' + | 'complexvalue' + +export interface FilteredLookupInfo { + controllingFields: string[]; + dependent: boolean; + optionalFilter: boolean; +} + +export type SOAPType = + | 'tns:ID' + | 'xsd:anyType' + | 'xsd:base64Binary' + | 'xsd:boolean' + | 'xsd:date' + | 'xsd:dateTime' + | 'xsd:double' + | 'xsd:int' + | 'xsd:string' + // the following are not found in official documentation, but still occur when describing an sobject + | 'xsd:time' + | 'urn:address' + | 'urn:JunctionIdListNames' + | 'urn:location' + | 'urn:RecordTypesSupported' + | 'urn:RelationshipReferenceTo' + | 'urn:SearchLayoutButtonsDisplayed' + | 'urn:SearchLayoutFieldsDisplayed' + +export interface PicklistEntry { + active: boolean; + validFor?: maybe; + defaultValue: boolean; + label?: maybe; + value: string; +} + +export interface RecordTypeInfo { + available: boolean; + defaultRecordTypeMapping: boolean; + developerName?: maybe; + master: boolean; + name: string; + recordTypeId: string; + urls: Record; +} + +export interface NamedLayoutInfo { + name: string; + urls: Record; +} + +export interface ScopeInfo { + label: string; + name: string; +} + +// From +// https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_describeglobal_describeglobalresult.htm#! + +export interface DescribeGlobalSObjectResult { activateable: boolean; createable: boolean; custom: boolean; @@ -13,7 +221,7 @@ export interface DescribeGlobalResult { feedEnabled: boolean; hasSubtypes: boolean; isSubtype: boolean; - keyPrefix: string; + keyPrefix: string | null; label: string; labelPlural: string; layoutable: boolean; @@ -27,4 +235,11 @@ export interface DescribeGlobalResult { triggerable: boolean; undeletable: boolean; updateable: boolean; + urls: Record; +} + +export interface DescribeGlobalResult { + encoding: string; + maxBatchSize: number; + sobjects: DescribeGlobalSObjectResult[]; } diff --git a/types/jsforce/index.d.ts b/types/jsforce/index.d.ts index 704bb07655..ddcb0d8260 100644 --- a/types/jsforce/index.d.ts +++ b/types/jsforce/index.d.ts @@ -4,6 +4,7 @@ // Kamil Ejsymont // Thomas Dvornik // Tim Noonan +// Abraham White // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -12,9 +13,11 @@ export * from './api/chatter'; export * from './api/metadata'; export * from './batch'; export * from './bulk'; +export * from './cache'; export * from './channel'; export * from './connection'; export * from './date-enum'; +export * from './describe-result'; export * from './job'; export * from './oauth2'; export * from './promise'; diff --git a/types/jsforce/jsforce-tests.ts b/types/jsforce/jsforce-tests.ts index c0be86e92c..8eb97aebc7 100644 --- a/types/jsforce/jsforce-tests.ts +++ b/types/jsforce/jsforce-tests.ts @@ -45,8 +45,8 @@ salesforceConnection.sobject("Account").create({ Name: "Test Acc 2", BillingStreet: "Maplestory street", BillingPostalCode: "ME4 666" -}, (err: Error, ret: sf.RecordResult) => { - if (err || !ret.success) { +}, (err: Error, ret: sf.RecordResult | sf.RecordResult[]) => { + if (err || !Array.isArray(ret) && !ret.success) { return; } }); @@ -56,8 +56,8 @@ salesforceConnection.sobject("ContentVersion").create({ Title: 'hello', PathOnClient: './hello-world.jpg', VersionData: '{ Test: Data }' -}, (err: Error, ret: sf.RecordResult) => { - if (err || !ret.success) { +}, (err: Error, ret: sf.RecordResult | sf.RecordResult[]) => { + if (err || !Array.isArray(ret) && !ret.success) { return; } }); @@ -77,8 +77,8 @@ salesforceConnection.sobject("ContentDocumentLink").create({ ContentDocumentId: '', LinkedEntityId: '', ShareType: "I" -}, (err: Error, ret: sf.RecordResult) => { - if (err || !ret.success) { +}, (err: Error, ret: sf.RecordResult | sf.RecordResult[]) => { + if (err || !Array.isArray(ret) && !ret.success) { return; } }); @@ -157,7 +157,7 @@ async function testMetadata(conn: sf.Connection): Promise { m.metadataObjects.filter((value: sf.MetadataObject) => value.directoryName === 'pages'); console.log(`ApexPage?: ${pages[0].xmlName === 'ApexPage'}`); - const types: sf.ListMetadataQuery[] = [{ type: 'CustomObject', folder: null }]; + const types: sf.ListMetadataQuery[] = [{ type: 'CustomObject', folder: undefined }]; md.list(types, '39.0', (err, properties: sf.FileProperties[]) => { if (err) { console.error('err', err); @@ -335,7 +335,8 @@ batch.on("response", (rets: sf.BatchResultInfo[]) => { if (rets[i].success) { console.log(`# ${(i + 1)} loaded successfully, id = ${rets[i].id}`); } else { - console.log(`# ${(i + 1)} error occurred, message = ${rets[i].errors.join(', ')}`); + const errors = rets[i].errors; + console.log(`# ${(i + 1)} error occurred, message = ${errors ? errors.join(', ') : ''}`); } } }); @@ -350,3 +351,31 @@ salesforceConnection.streaming.topic("InvoiceStatementUpdates").subscribe((messa console.log('Event Created : ' + message.event.createdDate); console.log('Object Id : ' + message.sobject.Id); }); + +async function testDescribe() { + const global: sf.DescribeGlobalResult = await salesforceConnection.describeGlobal(); + const globalCached: sf.DescribeGlobalResult = salesforceConnection.describeGlobal$(); + const globalCachedCorrectly = global === globalCached; + salesforceConnection.describeGlobal$.clear(); + + globalCached.sobjects.forEach(async (sobject: sf.DescribeGlobalSObjectResult) => { + const object: sf.DescribeSObjectResult = await salesforceConnection.describe(sobject.name); + const cachedObject: sf.DescribeSObjectResult = salesforceConnection.describe$(sobject.name); + salesforceConnection.describe$.clear(); + + object.fields.forEach(field => { + const type: sf.FieldType = field.type; + // following should never compile + // const fail = type === 'hey' + + const isString = type === 'string'; + }); + + // following should never compile (if StrictNullChecks is on) + // object.keyPrefix.length; + + console.log(`${sobject.name} Label: `, object.label); + + const correctlyCached = object === cachedObject; + }); +} diff --git a/types/jsforce/salesforce-object.d.ts b/types/jsforce/salesforce-object.d.ts index 2c54d598fc..ab3e398891 100644 --- a/types/jsforce/salesforce-object.d.ts +++ b/types/jsforce/salesforce-object.d.ts @@ -18,9 +18,6 @@ export class SObject { upsert(records: Record, extIdField: SalesforceId, options?: Object, callback?: (err: Error, ret: RecordResult) => void): Promise; upsert(records: Array>, extIdField: SalesforceId, options?: Object, callback?: (err: Error, ret: RecordResult[]) => void): Promise; upsertBulk(input?: Array> | stream.Stream | string, callback?: (err: Error, ret: RecordResult[] | BatchResultInfo[]) => void): Batch; - describeGlobal(callback: (err: Error, res: any) => void): void; - describe$(callback: (err: Error, ret: DescribeSObjectResult) => void): void; - describeGlobal$(callback: (err: Error, res: any) => void): void; find(query?: any, callback?: (err: Error, ret: T[]) => void): Query; find(query?: any, fields?: Object | string[] | string, callback?: (err: Error, ret: T[]) => void): Query; @@ -30,8 +27,18 @@ export class SObject { findOne(query?: any, fields?: Object | string[] | string, callback?: (err: Error, ret: T) => void): Query; findOne(query?: any, fields?: Object | string[] | string, options?: Object, callback?: (err: Error, ret: T) => void): Query; + approvalLayouts$: { + /** Returns a value from the cache if it exists, otherwise calls SObject.approvalLayouts */ + (callback?: (layoutInfo: ApprovalLayoutInfo) => void): ApprovalLayoutInfo; + clear(): void; + } approvalLayouts(callback?: (layoutInfo: ApprovalLayoutInfo) => void): Promise; bulkload(operation: string, options?: { extIdField?: string }, input?: Array> | stream.Stream[] | string[], callback?: (err: Error, ret: RecordResult) => void): Batch; + compactLayouts$: { + /** Returns a value from the cache if it exists, otherwise calls SObject.compactLayouts */ + (callback?: CompactLayoutInfo): CompactLayoutInfo; + clear(): void; + } compactLayouts(callback?: CompactLayoutInfo): Promise; count(conditions?: Object | string, callback?: (err: Error, num: number) => void): Promise; create(options: any | any[], callback?: (err: Error, ret: RecordResult | RecordResult[]) => void): Promise; @@ -45,8 +52,18 @@ export class SObject { deleted(start: Date | string, end: Date | string, callback?: (info: DeletedRecordsInfo) => void): Promise; deleteHardBulk(input?: Array> | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; describe(callback?: (err: Error, ret: DescribeSObjectResult) => void): Promise; + describe$: { + /** Returns a value from the cache if it exists, otherwise calls SObject.describe */ + (callback?: (err: Error, ret: DescribeSObjectResult) => void): DescribeSObjectResult; + clear(): void; + } insert(options: any | any[], callback?: (err: Error, ret: RecordResult | RecordResult[]) => void): Promise; insertBulk(input?: Array> | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; + /** Returns a value from the cache if it exists, otherwise calls SObject.layouts */ + layouts$: { + (layoutName?: string, callback?: (err: Error, info: LayoutInfo) => void): LayoutInfo; + clear(): void; + } layouts(layoutName?: string, callback?: (err: Error, info: LayoutInfo) => void): Promise; listview(id: string): ListView; listviews(callback?: (err: Error, info: ListViewsInfo) => void): Promise; diff --git a/types/jsforce/tsconfig.json b/types/jsforce/tsconfig.json index bf92077cd0..4d6aee9825 100644 --- a/types/jsforce/tsconfig.json +++ b/types/jsforce/tsconfig.json @@ -6,8 +6,8 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": false, + "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/koa-webpack/index.d.ts b/types/koa-webpack/index.d.ts index 79bd913ef4..5e9ccec4f5 100644 --- a/types/koa-webpack/index.d.ts +++ b/types/koa-webpack/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for koa-webpack 5.0 // Project: https://github.com/shellscape/koa-webpack // Definitions by: Luka Maljic +// Lee Benson +// miZyind // Tomek Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -8,8 +10,7 @@ import Koa = require('koa'); import webpack = require('webpack'); import webpackDevMiddleware = require('webpack-dev-middleware'); -import webpackHotMiddleware = require('webpack-hot-middleware'); -import connect = require('connect'); +import webpackHotClient = require('webpack-hot-client'); declare function koaWebpack( options?: koaWebpack.Options @@ -20,12 +21,19 @@ declare namespace koaWebpack { compiler?: webpack.Compiler; config?: webpack.Configuration; devMiddleware?: webpackDevMiddleware.Options; - hotClient?: webpackHotMiddleware.Options | boolean; + hotClient?: webpackHotClient.Options | boolean; } interface CombinedWebpackMiddleware { - devMiddleware: connect.NextHandleFunction & webpackDevMiddleware.WebpackDevMiddleware; - hotClient: connect.NextHandleFunction & webpackHotMiddleware.EventStream; + devMiddleware: webpackDevMiddleware.WebpackDevMiddleware; + /** + * @todo make this a `webpack-hot-client@^4.0.0` instance, no typings for v4 available yet + */ + hotClient: { + close: () => void; + options: webpackHotClient.Options; + server: any; + }; close(callback?: () => any): void; } } diff --git a/types/koa-webpack/koa-webpack-tests.ts b/types/koa-webpack/koa-webpack-tests.ts index fb36247d90..f7f8aaf813 100644 --- a/types/koa-webpack/koa-webpack-tests.ts +++ b/types/koa-webpack/koa-webpack-tests.ts @@ -7,45 +7,56 @@ const config: webpack.Configuration = {}; const compiler = webpack(config); // Using the middleware - koaWebpack({ compiler, config, + // Reference: https://github.com/webpack/webpack-dev-middleware#options devMiddleware: { - lazy: true, - watchOptions: { - aggregateTimeout: 300, - poll: true, - }, - publicPath: '/assets/', + headers: { 'X-Custom-Header': 'yes' }, index: 'index.html', - headers: { - 'X-Custom-Header': 'yes' - }, - stats: { - colors: true, - }, + lazy: false, + logger: undefined, + logLevel: 'info', + // logTime: false, + // mimeTypes: null, + publicPath: '/assets/', reporter: null, - serverSideRender: false + serverSideRender: false, + stats: { context: process.cwd() }, + watchOptions: { aggregateTimeout: 200 }, + // writeToDisk: false }, + // Reference: https://github.com/webpack-contrib/webpack-hot-client#api hotClient: { - log: console.log.bind(console), - path: '/__what', - heartbeat: 2000 + allEntries: false, + autoConfigure: true, + host: 'localhost', + hmr: true, + https: false, + logLevel: 'info', + logTime: false, + port: 0, + reload: true, + server: undefined, + stats: { context: process.cwd() } } -}).then((middleware) => { - app.use(middleware); +}) + .then((middleware) => { + app.use(middleware); - // Accessing the underlying middleware + // Accessing the underlying middleware + middleware.devMiddleware.close(); + middleware.devMiddleware.invalidate(); + middleware.devMiddleware.waitUntilValid(); + middleware.devMiddleware.getFilenameFromUrl('/public/index.html'); + middleware.devMiddleware.fileSystem; + middleware.hotClient.close(); + middleware.hotClient.options; + middleware.hotClient.server; - middleware.devMiddleware.close(); - middleware.devMiddleware.invalidate(); - middleware.devMiddleware.waitUntilValid(); - middleware.hotClient.publish(null); - return middleware; -}).then((middleware) => { - // close the middleware - - middleware.close(); -}); + // close the middleware + middleware.close(() => { + console.log('closed'); + }); + }); diff --git a/types/kraken-js/index.d.ts b/types/kraken-js/index.d.ts index 0980e31eb1..3013938dd2 100644 --- a/types/kraken-js/index.d.ts +++ b/types/kraken-js/index.d.ts @@ -1,16 +1,16 @@ // Type definitions for krakenjs 2.2 // Project: http://krakenjs.com // Definitions by: Timur Manyanov +// Satana Charuwichitratana // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 import { Express } from 'express'; -import { EventEmitter } from 'events'; declare function k(options?: k.Options | string): Express; declare namespace k { - interface Kraken extends Express, EventEmitter { + interface Kraken extends Express { kraken: Kraken; } diff --git a/types/mathjax/index.d.ts b/types/mathjax/index.d.ts index 8c0dc99e1a..aaf4a6109c 100644 --- a/types/mathjax/index.d.ts +++ b/types/mathjax/index.d.ts @@ -1030,6 +1030,17 @@ declare namespace MathJax { * they were MathML, you might need to set this to true. */ addMMLclasses?: boolean; + /*This controls whether the SVG output uses elements to re-use font paths rather than repeat paths every + * time. If useGlobalCache (see below) is set to false, this will still reduce duplication of paths while keeping + * each SVG self-contained. + */ + useFontCache?: boolean; + /*When set to true the SVG Output stores paths (corresponding to “fonts” in the SVG output) in a global SVG + * object using elements so that it can re-use them in all equations via elements (much like a font + * file allows re-use of characters across the document). While set to true by default, it will have no effect if + * useFontCache is set to false. + */ + useGlobalCache?: boolean; /*EqnChunk is the number of equations that will be typeset before they appear on screen. Larger values make for * less visual flicker as the equations are drawn, but also mean longer delays before the reader sees anything. */ diff --git a/types/mathjax/mathjax-tests.ts b/types/mathjax/mathjax-tests.ts index 619a8fc591..755e3bc4bd 100644 --- a/types/mathjax/mathjax-tests.ts +++ b/types/mathjax/mathjax-tests.ts @@ -57,4 +57,11 @@ MathJax.Hub.Config({ "HTML-CSS": { linebreaks: { automatic: true } }, CommonHTML: { linebreaks: { automatic: true } }, SVG: { linebreaks: { automatic: true } } -}); \ No newline at end of file +}); + +MathJax.Hub.Config({ + SVG: { + useFontCache: true, + useGlobalCache: true + } +}) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index def335cf3c..f7519cb076 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -2178,6 +2178,7 @@ declare module "child_process" { } export interface SpawnOptions { + argv0?: string; cwd?: string; env?: any; stdio?: any; @@ -2320,6 +2321,7 @@ declare module "child_process" { export function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; export interface SpawnSyncOptions { + argv0?: string; cwd?: string; input?: string | Buffer; stdio?: any; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 52ec31af07..740ad1f61a 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -2097,8 +2097,10 @@ namespace child_process_tests { childProcess.exec("echo test"); childProcess.exec("echo test", { windowsHide: true }); childProcess.spawn("echo", ["test"], { windowsHide: true }); + childProcess.spawn("echo", ["test"], { windowsHide: true, argv0: "echo-test" }); childProcess.spawnSync("echo test"); childProcess.spawnSync("echo test", {windowsVerbatimArguments: false}); + childProcess.spawnSync("echo test", {windowsVerbatimArguments: false, argv0: "echo-test"}); } { diff --git a/types/nvd3/index.d.ts b/types/nvd3/index.d.ts index cd60da4b8d..7f92d2410e 100644 --- a/types/nvd3/index.d.ts +++ b/types/nvd3/index.d.ts @@ -1698,6 +1698,8 @@ id(value: number|string): this; valueFormat(): string; /*D3 Format object for the label of pie/donut, discrete bar and multibar charts.*/ valueFormat(value: string): this; + /*D3 Format object for the label of pie/donut, discrete bar and multibar charts.*/ + valueFormat(format: (d: any) => string): this; /* The width the graph or component created inside the SVG should be made*/ width(): number; /*The width the graph or component created inside the SVG should be made.*/ @@ -2649,6 +2651,8 @@ id(value: number|string): this; valueFormat(): string; /*D3 Format object for the label of pie/donut, discrete bar and multibar charts.*/ valueFormat(value: string): this; + /*D3 Format object for the label of pie/donut, discrete bar and multibar charts.*/ + valueFormat(format: (d: any) => string): this; /*.*/ valuePadding(): number; /**/ diff --git a/types/nvd3/test/discreteBarChart.ts b/types/nvd3/test/discreteBarChart.ts index 2f31a29a0c..d9c8998fb1 100644 --- a/types/nvd3/test/discreteBarChart.ts +++ b/types/nvd3/test/discreteBarChart.ts @@ -48,6 +48,7 @@ namespace nvd3_test_discreteBarChart { //.staggerLabels(historicalBarChart[0].values.length > 8) .showValues(true) .duration(250) + .valueFormat(d3.format("d")) ; d3.select('#chart1 svg') diff --git a/types/nvd3/test/multibarHorizontalChart.ts b/types/nvd3/test/multibarHorizontalChart.ts index 748c83e10a..5bfc5d976f 100644 --- a/types/nvd3/test/multibarHorizontalChart.ts +++ b/types/nvd3/test/multibarHorizontalChart.ts @@ -136,6 +136,7 @@ namespace nvd3_test_multibarHorizontalChart { .barColor(d3.scale.category20().range()) .duration(250) .margin({ left: 100 }) + .valueFormat(d3.format("d")) .stacked(true); chart.yAxis.tickFormat(d3.format(',.2f')); diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 09d19de4ed..8e62f6d8f8 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -413,11 +413,11 @@ declare namespace Office { */ auth: Auth; /** - * True if developers can display, on the current platform, a UI in the add-in sell or upgrade; otherwise returns False. - * - * @remarks - * The iOS App Store doesn't support apps with add-ins that provide links to additional payment systems. However, Office Add-ins running on the Windows desktop or for Office Online in the browser, do allow such links. If you want the UI of your add-in to provide a link to an external payment system on platforms other than iOS, you can use the commerceAllowed property to control when that link is displayed. - */ + * True, if the current platform allows the add-in to display a UI for selling or upgrading; otherwise returns False. + * + * @remarks + * The iOS App Store doesn't support apps with add-ins that provide links to additional payment systems. However, Office Add-ins running on the Windows desktop or for Office Online in the browser, do allow such links. If you want the UI of your add-in to provide a link to an external payment system on platforms other than iOS, you can use the commerceAllowed property to control when that link is displayed. + */ commerceAllowed: boolean; /** * Gets the locale (language) specified by the user for editing the document or item. @@ -426,20 +426,7 @@ declare namespace Office { /** * Gets information about the environment in which the add-in is running. */ - diagnostics: { - /** - * Gets the Office application host in which the add-in is running. - */ - host: HostType; - /** - * Gets the platform on which the add-in is running. - */ - platform: PlatformType; - /** - * Gets the version of Office on which the add-in is running. - */ - version: string; - }; + diagnostics: ContextInformation; /** * Gets the locale (language) specified by the user for the UI of the Office host application. * @remarks @@ -488,14 +475,7 @@ declare namespace Office { /** * Provides a method for determining what requirement sets are supported on the current host and platform. */ - requirements: { - /** - * Check if the specified requirement set is supported by the host Office application. - * @param name - Set name; e.g., "MatrixBindings". - * @param minVersion - The minimum required version; e.g., "1.4". - */ - isSetSupported(name: string, minVersion?: number): boolean; - } + requirements: RequirementSetSupport; /** * Gets an object that represents the custom settings or state of a mail add-in saved to a user's mailbox. * @@ -605,6 +585,17 @@ declare namespace Office { */ closeContainer(): void; } + /** + * Provides information about what Requirement Sets are supported in current environment. + */ + interface RequirementSetSupport { + /** + * Check if the specified requirement set is supported by the host Office application. + * @param name - Set name; e.g., "MatrixBindings". + * @param minVersion - The minimum required version; e.g., "1.4". + */ + isSetSupported(name: string, minVersion?: number): boolean; +} /** * Provides options for how a dialog is displayed. */ @@ -673,6 +664,23 @@ declare namespace Office { */ asyncContext?: any } + /** + * Provides information about the environment in which the add-in is running. + */ + interface ContextInformation { + /** + * Gets the Office application host in which the add-in is running. + */ + host: Office.HostType; + /** + * Gets the platform on which the add-in is running. + */ + platform: Office.PlatformType; + /** + * Gets the version of Office on which the add-in is running. + */ + version: string; + } /** * Provides options for how to get the data in a binding. * @@ -772,7 +780,7 @@ declare namespace Office { format: object } /** - * Specifies a cell, or row, or column, by its zero-based row and/or column number. Example: {row: 4, column: 3} specifies the cell in the 3rd (zero-based) row in the 4th (zero-based) column. + * Specifies a cell, or row, or column, by its zero-based row and/or column number. Example: {row: 3, column: 4} specifies the cell in the 3rd (zero-based) row in the 4th (zero-based) column. */ interface RangeCoordinates { /** @@ -805,10 +813,6 @@ declare namespace Office { * The unique ID of the binding. Autogenerated if not supplied. */ id?: string - /** - * The names of the columns involved in the binding. - */ - columns?: Array /** * A user-defined item of any type that is returned, unchanged, in the value property of the AsyncResult object that is passed to a callback. */ @@ -829,7 +833,7 @@ declare namespace Office { /** * Specifies a table of sample data displayed in the prompt UI as an example of the kinds of fields (columns) that can be bound by your add-in. The headers provided in the TableData object specify the labels used in the field selection UI. Note: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. */ - sampleData?: TableData + sampleData?: Office.TableData /** * A user-defined item of any type that is returned, unchanged, in the value property of the AsyncResult object that is passed to a callback. */ @@ -997,7 +1001,6 @@ declare namespace Office { * - DialogEventReceived. Triggered when the dialog box has been closed or otherwise unloaded. */ addEventHandler(eventType: Office.EventType, handler: Function): void; - } } @@ -1110,6 +1113,44 @@ declare namespace Office { */ ReadWrite } + /** + * Specifies the type of the XML node. + * + * @remarks + * Hosts: Word + * + * Available in Requirement set: CustomXmlParts + */ + enum CustomXMLNodeType { + /** + * The node is an attribute. + */ + Attribute, + /** + * The node is CData. + */ + CData, + /** + * The node is a comment. + */ + NodeComment, + /** + * The node is an element. + */ + Element, + /** + * The node is a Document element. + */ + NodeDocument, + /** + * The node is a processing instruction. + */ + ProcessingInstruction, + /** + * The node is text. + */ + Text, + } /** * Specifies the kind of event that was raised. Returned by the type property of an EventNameEventArgs object. * @@ -1249,12 +1290,6 @@ declare namespace Office { */ Index } - enum Index { - First, - Last, - Next, - Previous - } /** * Specifies whether to select (highlight) the location to navigate to (when using the Document.goToByIdAsync method). * @@ -2038,6 +2073,60 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. */ setSelectedDataAsync(data: string | TableData | any[][], options?: SetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get Project field (Ex. ProjectWebAccessURL). + * @param fieldId Project level fields. + * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + */ + getProjectFieldAsync(fieldId: number, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get resource field for provided resource Id. (Ex.ResourceName) + * @param resourceId Either a string or value of the Resource Id. + * @param fieldId Resource Fields. + * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + */ + getResourceFieldAsync(resourceId: string, fieldId: number, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the current selected Resource's Id. + * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + */ + getSelectedResourceAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the current selected Task's Id. + * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + */ + getSelectedTaskAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the current selected View Type (Ex. Gantt) and View Name. + * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + */ + getSelectedViewAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the Task Name, WSS Task Id, and ResourceNames for given taskId. + * @param taskId Either a string or value of the Task Id. + * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + */ + getTaskAsync(taskId: string, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get task field for provided task Id. (Ex. StartDate). + * @param taskId Either a string or value of the Task Id. + * @param fieldId Task Fields. + * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + */ + getTaskFieldAsync(taskId: string, fieldId: number, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too. + * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + */ + getWSSUrlAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; } /** * Provides information about the document that raised the SelectionChanged event. @@ -4668,63 +4757,6 @@ declare namespace Office { */ Timeline } - // Objects - interface Document { - /** - * Get Project field (Ex. ProjectWebAccessURL). - * @param fieldId Project level fields. - * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. - * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. - */ - getProjectFieldAsync(fieldId: number, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; - /** - * Get resource field for provided resource Id. (Ex.ResourceName) - * @param resourceId Either a string or value of the Resource Id. - * @param fieldId Resource Fields. - * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. - * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. - */ - getResourceFieldAsync(resourceId: string, fieldId: number, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; - /** - * Get the current selected Resource's Id. - * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. - * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. - */ - getSelectedResourceAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; - /** - * Get the current selected Task's Id. - * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. - * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. - */ - getSelectedTaskAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; - /** - * Get the current selected View Type (Ex. Gantt) and View Name. - * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. - * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. - */ - getSelectedViewAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; - /** - * Get the Task Name, WSS Task Id, and ResourceNames for given taskId. - * @param taskId Either a string or value of the Task Id. - * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. - * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. - */ - getTaskAsync(taskId: string, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; - /** - * Get task field for provided task Id. (Ex. StartDate). - * @param taskId Either a string or value of the Task Id. - * @param fieldId Task Fields. - * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. - * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. - */ - getTaskFieldAsync(taskId: string, fieldId: number, options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; - /** - * Get the WSS Url and list name for the Tasks List, the MPP is synced too. - * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. - * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. - */ - getWSSUrlAsync(options?: AsyncContextOptions, callback?: (result: AsyncResult) => void): void; - } } @@ -9907,15 +9939,11 @@ declare namespace Excel { * Copy a worksheet and place it at the specified position. Return the copied worksheet. * * [Api set: ExcelApi 1.7] + * + * @param positionType Specifies where to put the copy relative to the worksheet specified in relativeTo param. Can be Excel.WorksheetPositionType or string equivalent. Must not be Excel.WorksheetPositionType.none or "None". + * @param relativeTo Specifies the worksheet that is the basis for intepreting the positionType param. If not specified, the worksheet on which the copy() is called is assumed. */ - copy(positionType?: Excel.WorksheetPositionType, relativeTo?: Excel.Worksheet): Excel.Worksheet; - /** - * - * Copy a worksheet and place it at the specified position. Return the copied worksheet. - * - * [Api set: ExcelApi 1.7] - */ - copy(positionType?: "None" | "Before" | "After" | "Beginning" | "End", relativeTo?: Excel.Worksheet): Excel.Worksheet; + copy(positionType?: Excel.WorksheetPositionType | string, relativeTo?: Excel.Worksheet): Excel.Worksheet; /** * * Deletes the worksheet from the workbook. diff --git a/types/openpgp/index.d.ts b/types/openpgp/index.d.ts index 79e92daa7f..6c8e073c04 100644 --- a/types/openpgp/index.d.ts +++ b/types/openpgp/index.d.ts @@ -1,22 +1,73 @@ // Type definitions for openpgpjs // Project: http://openpgpjs.org/ // Definitions by: Guillaume Lacasa +// Errietta Kostala // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace openpgp; -export interface KeyPair { +export interface UserId { + name?: string, + email?: string, +} + +export interface SessionKey { + data: Uint8Array, + algorithm: string +} + +export interface EncryptOptions { + data: string|Uint8Array, + dataType?: 'utf8'|'binary'|'text'|'mime', + publicKeys?: key.Key | key.Key[], + privateKeys?: key.Key | key.Key[], + passwords?: string|string[], + sessionKey?: SessionKey, + filename?: string, + compression?: enums.compression, + armor?: boolean, + detached?: boolean, + signature?: Signature, + returnSessionKey?: boolean, + wildcard?: boolean, + date?: Date, + fromUserId?: UserId, + toUserId?: UserId, +} + +export interface EncryptedMessage { + data: string, + message: string, +} + +export interface DecryptOptions { + message: message.Message, + privateKeys?: key.Key | key.Key[], + passwords?: string | string[], + sessionKeys?: SessionKey | SessionKey[], + publicKeys?: key.Key | key.Key[], + format?: string, + signature?: Signature, + date?: Date, +} + +export interface KeyContainer { key: key.Key, +} + +export interface KeyPair extends KeyContainer { privateKeyArmored: string, publicKeyArmored: string } export interface KeyOptions { - keyType?: enums.publicKey, - numBits: number, - userId: string, - passphrase: string, - unlocked?: boolean + userIds?: UserId[], + passphrase?: string, + numBits?: number, + keyExpirationTime?: number, + curve?: string, + date?: Date, + subkeys?: KeyOptions[] } export interface Keyid { @@ -29,91 +80,153 @@ export interface Signature { } export interface VerifiedMessage { - text: string, - signatures: Array + data: Uint8Array|string, + signatures: Array, + filename: string, } -/** Decrypts message and verifies signatures +export interface OpenPGPWorker { + randomCallback(): void; + configure(config: any): void; + seedRandom(buffer: ArrayBuffer): void; + delegate(id: number, method: string, options: any): void; + response(event: any): void; +} - @param privateKey private key with decrypted secret key data - @param publicKeys array of keys to verify signatures - @param msg the message object with signed and encrypted data - */ -export function decryptAndVerifyMessage(privateKey: key.Key, publicKeys: Array, msg: string): Promise; -/** Decrypts message and verifies signatures +export interface WorkerOptions { + path?: string, + n?: number, + workers?: OpenPGPWorker[], + config?: any, +} - @param privateKey private key with decrypted secret key data - @param publicKey single key to verify signatures - @param msg the message object with signed and encrypted data - */ -export function decryptAndVerifyMessage(privateKey: key.Key, publicKey: key.Key, msg: string): Promise; +export class AsyncProxy { + constructor(options: WorkerOptions); + getId(): number; + seedRandom(workerId: number, size: number): Promise; + terminate(): void; + delegate(method: string, options: any): void; -/** Decrypts message + workers: OpenPGPWorker[]; +} - @param privateKey private key with decrypted secret key data - @param msg the message object with the encrypted data - */ -export function decryptMessage(privateKey: key.Key, msg: message.Message): Promise; +/** + * Set the path for the web worker script and create an instance of the async proxy + * @param {String} path relative path to the worker scripts, default: 'openpgp.worker.js' + * @param {Number} n number of workers to initialize + * @param {Array} workers alternative to path parameter: web workers initialized with 'openpgp.worker.js' + */ +export function initWorker(options: WorkerOptions): boolean; -/** Encrypts message text with keys - @param keys array of keys used to encrypt the message - @param text message as native JavaScript string - @returns encrypted ASCII armored message - */ -export function encryptMessage(keys: Array, message: string): Promise; -/** Encrypts message text with keys +/** + * Returns a reference to the async proxy if the worker was initialized with openpgp.initWorker() + * @returns {module:worker/async_proxy.AsyncProxy|null} the async proxy or null if not initialized + */ +export function getWorker(): AsyncProxy; - @param single key used to encrypt the message - @param text message as native JavaScript string - */ -export function encryptMessage(key: key.Key, message: string): Promise; +/** + * Cleanup the current instance of the web worker. + */ +export function destroyWorker(): void; -/** Generates a new OpenPGP key pair. Currently only supports RSA keys. Primary and subkey will be of same type. - @param options - */ -export function generateKeyPair(options: KeyOptions): Promise; +/** + * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords + * must be specified. If private keys are specified, those will be used to sign the message. + * @param {String|Uint8Array} data text/data to be encrypted as JavaScript binary string or Uint8Array + * @param {utf8|binary|text|mime} dataType (optional) data packet type + * @param {Key|Array} publicKeys (optional) array of keys or single key, used to encrypt the message + * @param {Key|Array} privateKeys (optional) private keys for signing. If omitted message will not be signed + * @param {String|Array} passwords (optional) array of passwords or a single password to encrypt the message + * @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String } + * @param {String} filename (optional) a filename for the literal data packet + * @param {module:enums.compression} compression (optional) which compression algorithm to compress the message with, defaults to what is specified in config + * @param {Boolean} armor (optional) if the return values should be ascii armored or the message/signature objects + * @param {Boolean} detached (optional) if the signature should be detached (if true, signature will be added to returned object) + * @param {Signature} signature (optional) a detached signature to add to the encrypted message + * @param {Boolean} returnSessionKey (optional) if the unencrypted session key should be added to returned object + * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param {Date} date (optional) override the creation date of the message and the message signature + * @param {Object} fromUserId (optional) user ID to sign with, e.g. { name:'Steve Sender', email:'steve@openpgp.org' } + * @param {Object} toUserId (optional) user ID to encrypt for, e.g. { name:'Robert Receiver', email:'robert@openpgp.org' } + * @returns {Promise} encrypted (and optionally signed message) in the form: + * {data: ASCII armored message if 'armor' is true, + * message: full Message object if 'armor' is false, signature: detached signature if 'detached' is true} + * @async + * @static + */ +export function encrypt(options: EncryptOptions): Promise; -/** Signs message text and encrypts it +/** + * Decrypts a message with the user's private key, a session key or a password. Either a private key, + * a session key or a password must be specified. + * @param {Message} message the message object with the encrypted data + * @param {Key|Array} privateKeys (optional) private keys with decrypted secret key data or session key + * @param {String|Array} passwords (optional) passwords to decrypt the message + * @param {Object|Array} sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String } + * @param {Key|Array} publicKeys (optional) array of public keys or single key, to verify signatures + * @param {String} format (optional) return data format either as 'utf8' or 'binary' + * @param {Signature} signature (optional) detached signature for verification + * @param {Date} date (optional) use the given date for verification instead of the current time + * @returns {Promise} decrypted and verified message in the form: + * { data:Uint8Array|String, filename:String, signatures:[{ keyid:String, valid:Boolean }] } + * @async + * @static + */ +export function decrypt(options: DecryptOptions): Promise; - @param publicKeys array of keys used to encrypt the message - @param privateKey private key with decrypted secret key data for signing - @param text private key with decrypted secret key data for signing - */ -export function signAndEncryptMessage(publicKeys: Array, privateKey: key.Key, text: string): Promise; -/** Signs message text and encrypts it +/** + * Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type. + * @param {Array} userIds array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }] + * @param {String} passphrase (optional) The passphrase used to encrypt the resulting private key + * @param {Number} numBits (optional) number of bits for RSA keys: 2048 or 4096. + * @param {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires + * @param {String} curve (optional) elliptic curve for ECC keys: + * curve25519, p256, p384, p521, secp256k1, + * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1. + * @param {Date} date (optional) override the creation date of the key and the key signatures + * @param {Array} subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + * @returns {Promise} The generated key object in the form: + * { key:Key, privateKeyArmored:String, publicKeyArmored:String } + * @async + * @static + */ +export function generateKey(options: KeyOptions): Promise; - @param publicKeys single key used to encrypt the message - @param privateKey private key with decrypted secret key data for signing - @param text private key with decrypted secret key data for signing - */ -export function signAndEncryptMessage(publicKey: key.Key, privateKey: key.Key, text: string): Promise; +/** + * Reformats signature packets for a key and rewraps key object. + * @param {Key} privateKey private key to reformat + * @param {Array} userIds array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }] + * @param {String} passphrase (optional) The passphrase used to encrypt the resulting private key + * @param {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires + * @returns {Promise} The generated key object in the form: + * { key:Key, privateKeyArmored:String, publicKeyArmored:String } + * @async + * @static + */ +export function reformatKey(options: { + privateKey: key.Key, + userIds?: UserId[], + passphrase?: string, + keyExpirationTime?: number, +}): Promise; -/** Signs a cleartext message - - @param privateKeys array of keys with decrypted secret key data to sign cleartext - @param text cleartext - */ -export function signClearMessage(privateKeys: Array, text: string): Promise; -/** Signs a cleartext message - - @param privateKeys single key with decrypted secret key data to sign cleartext - @param text cleartext - */ -export function signClearMessage(privateKey: key.Key, text: string): Promise; - -/** Verifies signatures of cleartext signed message - - @param publicKeys array of keys to verify signatures - @param msg cleartext message object with signatures - */ -export function verifyClearSignedMessage(publicKeys: Array, msg: cleartext.CleartextMessage): Promise; -/** Verifies signatures of cleartext signed message - - @param publicKeys single key to verify signatures - @param msg cleartext message object with signatures - */ -export function verifyClearSignedMessage(publicKey: key.Key, msg: cleartext.CleartextMessage): Promise; +/** + * Unlock a private key with your passphrase. + * @param {Key} privateKey the private key that is to be decrypted + * @param {String|Array} passphrase the user's passphrase(s) chosen during key generation + * @returns {Promise} the unlocked key object in the form: { key:Key } + * @async + */ +export function decryptKey(options: { + privateKey: key.Key, + passphrase?: string | string[], +}): Promise; +export function encryptKey(options: { + privateKey: key.Key, + passphrase?: string +}): Promise; export namespace armor { /** Armor an OpenPGP binary packet block @@ -471,6 +584,14 @@ export namespace message { @param armoredText text to be parsed */ function readArmored(armoredText: string): Message; + + /** + * reads an OpenPGP message as byte array and returns a message object + * @param {Uint8Array} input binary message + * @returns {Message} new message object + * @static + */ + function read(data: Uint8Array): Message; } export namespace packet { diff --git a/types/openpgp/openpgp-tests.ts b/types/openpgp/openpgp-tests.ts index fbe8a2e691..3bd3551d0b 100644 --- a/types/openpgp/openpgp-tests.ts +++ b/types/openpgp/openpgp-tests.ts @@ -2,11 +2,14 @@ var options: openpgp.KeyOptions = { numBits: 2048, - userId: 'Jon Smith ', + userIds: [{ + name: 'Jon Smith', + email: 'jon.smith@example.org', + }], passphrase: 'super long and hard to guess secret' }; -openpgp.generateKeyPair(options).then(function (keypair) { +openpgp.generateKey(options).then(function (keypair) { // success var privkey = keypair.privateKeyArmored; var pubkey = keypair.publicKeyArmored; @@ -18,14 +21,15 @@ openpgp.generateKeyPair(options).then(function (keypair) { var spubkey = '-----BEGIN PGP PUBLIC KEY BLOCK ... END PGP PUBLIC KEY BLOCK-----'; var publicKey = openpgp.key.readArmored(spubkey); -openpgp.encryptMessage(publicKey.keys, 'Hello, World!').then(function (pgpMessage) { +openpgp.encrypt({ + data: 'Hello, World!', + publicKeys: publicKey.keys +}).then(function (pgpMessage) { // success }).catch(function (error) { // failure }); - - var sprivkey = '-----BEGIN PGP PRIVATE KEY BLOCK ... END PGP PRIVATE KEY BLOCK-----'; var privateKey = openpgp.key.readArmored(sprivkey).keys[0]; privateKey.decrypt('passphrase'); @@ -33,7 +37,10 @@ privateKey.decrypt('passphrase'); var pgpMessageStr = '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'; var pgpMessage = openpgp.message.readArmored(pgpMessageStr); -openpgp.decryptMessage(privateKey, pgpMessage).then(function (plaintext) { +openpgp.decrypt({ + privateKeys: privateKey, + message: pgpMessage +}).then(function (plaintext) { // success }).catch(function (error) { // failure @@ -44,35 +51,9 @@ openpgp.decryptMessage(privateKey, pgpMessage).then(function (plaintext) { var keyoptions: openpgp.KeyOptions; -var key= openpgp.key.generate(keyoptions); -var keys: Array; -var message = openpgp.message.readArmored(""); -var cleartextmessage = openpgp.cleartext.readArmored(""); var mpi: openpgp.crypto.Mpi; var mpis: Array; - -openpgp.decryptAndVerifyMessage(key, key, "").then(); -openpgp.decryptAndVerifyMessage(key, keys, "").then(); - -openpgp.decryptMessage(key, message).then(); - -openpgp.encryptMessage(key, "").then(); -openpgp.encryptMessage(keys, "").then(); - -openpgp.generateKeyPair(keyoptions).then(function (keypair) { - key = keypair.key; -}); - -openpgp.signAndEncryptMessage(key, key, "").then(); -openpgp.signAndEncryptMessage(keys, key, "").then(); - -openpgp.signClearMessage(key, "").then(); -openpgp.signClearMessage(keys, "").then(); - -openpgp.verifyClearSignedMessage(key, cleartextmessage); -openpgp.verifyClearSignedMessage(keys, cleartextmessage); - openpgp.armor.armor(openpgp.enums.armor.message, {}, 0, 1); openpgp.armor.dearmor(""); diff --git a/types/range-parser/index.d.ts b/types/range-parser/index.d.ts index 5912777ec0..a1bcf4c9dc 100644 --- a/types/range-parser/index.d.ts +++ b/types/range-parser/index.d.ts @@ -3,6 +3,13 @@ // Definitions by: Tomek Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/** + * Returns `-1` when unsatisfiable and `-2` when syntactically invalid. + * + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. + */ declare function RangeParser(size: number, str: string, options?: RangeParser.Options): RangeParser.Result | RangeParser.Ranges; declare namespace RangeParser { @@ -14,6 +21,10 @@ declare namespace RangeParser { end: number; } interface Options { + /** + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. + */ combine?: boolean; } const enum Result { diff --git a/types/react-dom/index.d.ts b/types/react-dom/index.d.ts index bd9541217d..e7a5afe59d 100644 --- a/types/react-dom/index.d.ts +++ b/types/react-dom/index.d.ts @@ -19,7 +19,7 @@ import { export function findDOMNode(instance: ReactInstance): Element | null | Text; export function unmountComponentAtNode(container: Element): boolean; -export function createPortal(children: ReactNode, container: Element): ReactPortal; +export function createPortal(children: ReactNode, container: Element, key?: null | string): ReactPortal; export const version: string; export const render: Renderer; diff --git a/types/react-dom/react-dom-tests.tsx b/types/react-dom/react-dom-tests.tsx index 3f153b0a75..ff5ef5850e 100644 --- a/types/react-dom/react-dom-tests.tsx +++ b/types/react-dom/react-dom-tests.tsx @@ -42,7 +42,14 @@ describe('ReactDOM', () => { } } - ReactDOM.createPortal(React.createElement('div'), portalTarget); + ReactDOM.createPortal(
, document.createElement('div')); + ReactDOM.createPortal(
, document.createElement('div'), null); + ReactDOM.createPortal(
, document.createElement('div'), 'key'); + + ReactDOM.createPortal(React.createElement('div'), document.createElement('div')); + ReactDOM.createPortal(React.createElement('div'), document.createElement('div'), null); + ReactDOM.createPortal(React.createElement('div'), document.createElement('div'), 'key'); + ReactDOM.render(, rootElement); }); }); diff --git a/types/react-native-custom-tabs/index.d.ts b/types/react-native-custom-tabs/index.d.ts new file mode 100644 index 0000000000..ed74ff4303 --- /dev/null +++ b/types/react-native-custom-tabs/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for react-native-custom-tabs 0.1 +// Project: https://github.com/droibit/react-native-custom-tabs +// Definitions by: Phil Nova +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Animations { + startEnter: string; + startExit: string; + endEnter: string; + endExit: string; +} + +export interface CustomTabsOptions { + toolbarColor?: string; + enableUrlBarHiding?: boolean; + showPageTitle?: boolean; + enableDefaultShare?: boolean; + animations?: Animations; + headers?: any; +} + +export function openURL(url: string, options?: CustomTabsOptions): Promise; diff --git a/types/react-native-custom-tabs/react-native-custom-tabs-tests.ts b/types/react-native-custom-tabs/react-native-custom-tabs-tests.ts new file mode 100644 index 0000000000..86dad3b3ee --- /dev/null +++ b/types/react-native-custom-tabs/react-native-custom-tabs-tests.ts @@ -0,0 +1,10 @@ +import * as ReactNativeCustomTabs from 'react-native-custom-tabs'; + +const rnt: ReactNativeCustomTabs.CustomTabsOptions = { + toolbarColor: 'blue', + enableUrlBarHiding: false, + showPageTitle: true, + enableDefaultShare: true, +}; + +const url: Promise = ReactNativeCustomTabs.openURL('testurl.com', rnt); diff --git a/types/react-native-custom-tabs/tsconfig.json b/types/react-native-custom-tabs/tsconfig.json new file mode 100644 index 0000000000..fcbc50b580 --- /dev/null +++ b/types/react-native-custom-tabs/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 + }, + "files": [ + "index.d.ts", + "react-native-custom-tabs-tests.ts" + ] +} \ No newline at end of file diff --git a/types/react-native-custom-tabs/tslint.json b/types/react-native-custom-tabs/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/react-native-custom-tabs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/react-native-tab-view/index.d.ts b/types/react-native-tab-view/index.d.ts index 2c6546a628..c761d80d14 100644 --- a/types/react-native-tab-view/index.d.ts +++ b/types/react-native-tab-view/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for react-native-tab-view 0.0 +// Type definitions for react-native-tab-view 1.0 // Project: https://github.com/react-native-community/react-native-tab-view // Definitions by: Kalle Ott +// Kyle Roach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 - import { PureComponent, ReactNode, ComponentType } from 'react' import { Animated, @@ -39,7 +39,7 @@ export type SceneRendererProps = { } navigationState: NavigationState position: Animated.Value - jumpToIndex: (index: number) => void + jumpTo: (key: string) => void getLastPosition: () => number subscribe: ( event: SubscriptionName, @@ -75,24 +75,24 @@ export type PagerProps = { children?: ReactNode } -export type TabViewAnimatedProps< +export type TabViewProps< T extends RouteBase = RouteBase > = PagerProps & { navigationState: NavigationState + tabBarPosition?: 'bottom' | 'top' onIndexChange: (index: number) => void onPositionChange?: (props: { value: number }) => void initialLayout?: Layout canJumpToTab?: (route: T) => boolean renderPager?: (props: SceneRendererProps & PagerProps) => ReactNode renderScene: (props: SceneRendererProps & Scene) => ReactNode - renderHeader?: (props: SceneRendererProps) => ReactNode - renderFooter?: (props: SceneRendererProps) => ReactNode + renderTabBar?: (props: SceneRendererProps) => ReactNode lazy?: boolean style?: StyleProp } -export class TabViewAnimated extends PureComponent< - TabViewAnimatedProps, +export class TabView extends PureComponent< + TabViewProps, any > {} @@ -125,7 +125,7 @@ export type GestureState = { export type GestureHandler = (event: GestureEvent, state: GestureState) => void -export type TabViewPagerPanProps< +export type PagerPanProps< T extends RouteBase = RouteBase > = SceneRendererProps & { configureTransition?: TransitionConfigurator @@ -144,8 +144,8 @@ export type DefaultTransitionSpec = { friction: 35 } -export class TabViewPagerPan extends PureComponent< - TabViewPagerPanProps, +export class PagerPan extends PureComponent< + PagerPanProps, void > { static defaultProps: { @@ -168,7 +168,7 @@ export type ScrollEvent = { } } -export type TabViewPagerScrollProps< +export type PagerScrollProps< T extends RouteBase = RouteBase > = SceneRendererProps & { animationEnabled?: boolean @@ -176,8 +176,8 @@ export type TabViewPagerScrollProps< children?: ReactNode } -export class TabViewPagerScroll extends PureComponent< - TabViewPagerScrollProps, +export class PagerScroll extends PureComponent< +PagerScrollProps, any > {} @@ -190,7 +190,7 @@ export type PageScrollEvent = { export type PageScrollState = 'dragging' | 'settling' | 'idle' -export type TabViewPagerAndroidProps< +export type PagerAndroidProps< T extends RouteBase = RouteBase > = SceneRendererProps & { animationEnabled?: boolean @@ -198,8 +198,8 @@ export type TabViewPagerAndroidProps< children?: ReactNode } -export class TabViewPagerAndroid extends PureComponent< - TabViewPagerAndroidProps, +export class PagerAndroid extends PureComponent< + PagerAndroidProps, void > {} diff --git a/types/react-native-tab-view/react-native-tab-view-tests.tsx b/types/react-native-tab-view/react-native-tab-view-tests.tsx index 97d8c09257..a7530b9ec9 100644 --- a/types/react-native-tab-view/react-native-tab-view-tests.tsx +++ b/types/react-native-tab-view/react-native-tab-view-tests.tsx @@ -1,7 +1,7 @@ import { PureComponent, Component } from 'react' import { View, StyleSheet } from 'react-native' import { - TabViewAnimated, + TabView, TabBar, SceneMap, TabBarProps, @@ -31,7 +31,7 @@ class TabViewExample extends PureComponent { _handleIndexChange = (index: number) => this.setState({ index }) - _renderHeader = (props: TabBarProps) => + _renderTabBar = (props: TabBarProps) => _renderScene = SceneMap({ first: FirstRoute, @@ -40,11 +40,12 @@ class TabViewExample extends PureComponent { render() { return ( - ) diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index a7f3dea705..a3e19267de 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -108,17 +108,17 @@ export interface Connect { ( mapStateToProps: MapStateToPropsParam - ): InferableComponentEnhancerWithProps; + ): InferableComponentEnhancerWithProps; ( mapStateToProps: null | undefined, mapDispatchToProps: MapDispatchToPropsParam - ): InferableComponentEnhancerWithProps; + ): InferableComponentEnhancerWithProps; ( mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam - ): InferableComponentEnhancerWithProps; + ): InferableComponentEnhancerWithProps; ( mapStateToProps: MapStateToPropsParam, diff --git a/types/react-router-navigation-core/react-router-navigation-core-tests.tsx b/types/react-router-navigation-core/react-router-navigation-core-tests.tsx index 6d6d048886..e99fffdc77 100644 --- a/types/react-router-navigation-core/react-router-navigation-core-tests.tsx +++ b/types/react-router-navigation-core/react-router-navigation-core-tests.tsx @@ -2,7 +2,7 @@ import * as React from "react"; import { View } from "react-native"; import { TabStack, renderSubView } from "react-router-navigation-core"; import { TabBarProps, TabProps } from "react-router-navigation"; -import { TabViewAnimated } from "react-native-tab-view"; +import { TabView } from "react-native-tab-view"; type Props = TabBarProps & { children?: Array>; @@ -24,7 +24,7 @@ class BottomNavigation extends React.Component { render={props => { const ownProps = { ...this.props, ...props }; return ( - { sceneProps => , ownProps )} - renderFooter={renderSubView( + renderTabBar={renderSubView( sceneProps => , ownProps )} + tabBarPosition="bottom" renderScene={renderSubView( sceneProps => , ownProps diff --git a/types/react-router-navigation/index.d.ts b/types/react-router-navigation/index.d.ts index 120ffb0d82..e43f08e652 100644 --- a/types/react-router-navigation/index.d.ts +++ b/types/react-router-navigation/index.d.ts @@ -6,7 +6,6 @@ import { Component, ReactNode, ReactElement, ComponentClass } from "react"; import { StyleProp, ViewProps, ViewStyle, TextStyle } from "react-native"; -import { TabViewAnimated, TabViewPagerPan } from "react-native-tab-view"; import { RouteProps } from "react-router-navigation-core"; import { NavigationTransitionProps, diff --git a/types/react-stripe-elements/index.d.ts b/types/react-stripe-elements/index.d.ts index fa68cb1b31..e8e88757b2 100644 --- a/types/react-stripe-elements/index.d.ts +++ b/types/react-stripe-elements/index.d.ts @@ -30,7 +30,7 @@ export namespace ReactStripeElements { interface StripeProviderOptions { stripeAccount?: string; } - type StripeProviderProps = { apiKey: string; stripe?: never; options?: StripeProviderOptions } | { apiKey?: never; stripe: StripeProps | null; options?: StripeProviderOptions; }; + type StripeProviderProps = { apiKey: string; stripe?: never; } & StripeProviderOptions | { apiKey?: never; stripe: StripeProps | null; } & StripeProviderOptions; interface StripeProps { createSource(sourceData?: SourceOptions): Promise; diff --git a/types/react-stripe-elements/react-stripe-elements-tests.tsx b/types/react-stripe-elements/react-stripe-elements-tests.tsx index 575987a1d9..ef1af5fa86 100644 --- a/types/react-stripe-elements/react-stripe-elements-tests.tsx +++ b/types/react-stripe-elements/react-stripe-elements-tests.tsx @@ -197,6 +197,7 @@ const TestStripeProviderProps3: React.SFC<{ }> = props => ; /** - * StripeProvider should be able to accept an `options` prop + * StripeProvider should be able to accept options. + * See: https://stripe.com/docs/stripe-js/reference#stripe-function for options. */ -const TestStripeProviderOptions: React.SFC = () => ; +const TestStripeProviderOptions: React.SFC = () => ; diff --git a/types/recharts/README.MD b/types/recharts/README.MD index 063a6dab3c..970e15ec0b 100644 --- a/types/recharts/README.MD +++ b/types/recharts/README.MD @@ -2,3 +2,11 @@ Typings for [Recharts](http://recharts.org/), a composable charting library buil The [Recharts website](https://github.com/recharts/recharts.org) has comprehensive API documentation which is generated from JavaScript files. Those files are used as input to generate these typings. + +# How to run tests + +As of 1.6.2018. + +1) Install typescript globally: `npm i -g typescript` +2) Install React's dependencies: `cd ../react && npm i` +3) Run tests: `cd ../recharts && tsc` \ No newline at end of file diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index ecdcd1f420..342c1a07bb 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -6,6 +6,7 @@ // Zheyang Song // Rich Baird // Dan Torberg +// Peter Keuter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -163,7 +164,7 @@ export interface AreaProps extends EventAttributes, Partial | ContentRenderer; dot?: boolean | object | React.ReactElement | ContentRenderer; - label?: boolean | object | React.ReactElement | LabelProps['content']; + label?: boolean | object | ContentRenderer | React.ReactElement; hide?: boolean; layout?: LayoutType; baseLine?: number | any[]; @@ -207,7 +208,7 @@ export interface BarProps extends EventAttributes, Partial | ContentRenderer; data?: BarData[]; // see label section at http://recharts.org/#/en-US/api/Bar - label?: boolean | Label | React.SFC | React.ReactElement | ContentRenderer
); } diff --git a/types/request-promise-native/index.d.ts b/types/request-promise-native/index.d.ts index 0b5ef4300c..201983dd6e 100644 --- a/types/request-promise-native/index.d.ts +++ b/types/request-promise-native/index.d.ts @@ -9,10 +9,10 @@ import request = require('request'); import http = require('http'); declare namespace requestPromise { - interface RequestPromise extends request.Request { - then: Promise["then"]; - catch: Promise["catch"]; - promise(): Promise; + interface RequestPromise extends request.Request { + then: Promise["then"]; + catch: Promise["catch"]; + promise(): Promise; } interface RequestPromiseOptions extends request.CoreOptions { diff --git a/types/swagger-schema-official/index.d.ts b/types/swagger-schema-official/index.d.ts index dc184d3e91..190e1ead7d 100644 --- a/types/swagger-schema-official/index.d.ts +++ b/types/swagger-schema-official/index.d.ts @@ -147,7 +147,7 @@ export interface Schema extends BaseSchema { readOnly?: boolean; xml?: XML; externalDocs?: ExternalDocs; - example?: {[exampleName: string]: {}}; + example?: any; required?: string[]; } diff --git a/types/webpack-hot-client/index.d.ts b/types/webpack-hot-client/index.d.ts index 337581fedb..295e6819be 100644 --- a/types/webpack-hot-client/index.d.ts +++ b/types/webpack-hot-client/index.d.ts @@ -7,7 +7,7 @@ /// import * as webpack from 'webpack'; -import * as http from 'http'; +import * as net from 'net'; export = WebpackHotClient; @@ -44,7 +44,7 @@ declare namespace WebpackHotClient { /** Reload the page if a patch cannot be applied by webpack */ reload?: boolean; /** Server instance for webpack-hot-client to connect to */ - server?: http.Server; + server?: net.Server; /** Webpack stats configuration */ stats?: webpack.Options.Stats; } diff --git a/types/yauzl-promise/index.d.ts b/types/yauzl-promise/index.d.ts new file mode 100644 index 0000000000..b859d8891e --- /dev/null +++ b/types/yauzl-promise/index.d.ts @@ -0,0 +1,68 @@ +// Type definitions for yauzl-promise 2.1 +// Project: https://github.com/overlookmotel/yauzl-promise +// Definitions by: Dave Lee +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.1 + +/// + +import { Entry as BaseEntry, Options, ZipFileOptions, RandomAccessReader } from 'yauzl'; +import { Readable } from 'stream'; +import { EventEmitter } from 'events'; + +// This class is not directly compatible with @types/yauzl 's ZipFile as this library changes the function signatures +// Therefore, it is replaced, albeit with a significant portion +export class ZipFile extends EventEmitter { + // This chunk taken directly from @types/yauzl + autoClose: boolean; + comment: string; + decodeStrings: boolean; + emittedError: boolean; + entriesRead: number; + entryCount: number; + fileSize: number; + isOpen: boolean; + lazyEntries: boolean; + readEntryCursor: boolean; + validateEntrySizes: boolean; + + constructor( + reader: RandomAccessReader, + centralDirectoryOffset: number, + fileSize: number, + entryCount: number, + comment: string, + autoClose: boolean, + lazyEntries: boolean, + decodeStrings: boolean, + validateEntrySizes: boolean, + ); + + // These funcitons are custom to yauzl-promise + + close(): Promise; + readEntry(): Promise; + readEntries(numEntries?: number): Promise; + walkEntries(callback: (entry: Entry) => Promise | void, numEntries?: number): Promise; + openReadStream(entry: Entry, options?: ZipFileOptions): Promise; +} + +export class Entry extends BaseEntry { + openReadStream(options?: ZipFileOptions): Promise; +} + +export function open(path: string, options?: Options): Promise; +// export function open(path: string): Promise; +export function fromFd(fd: number, options?: Options): Promise; +// export function fromFd(fd: number): Promise; +export function fromBuffer(buffer: Buffer, options?: Options): Promise; +// export function fromBuffer(buffer: Buffer): Promise; +export function fromRandomAccessReader(reader: RandomAccessReader, totalSize: number, options?: Options): Promise; +// export function fromRandomAccessReader(reader: RandomAccessReader, totalSize: number): Promise; + +// These are copied directly from @types/yauzl, I beleive they are unmodified +export function dosDateTimeToDate(date: number, time: number): Date; +export function validateFileName(fileName: string): string | null; + +export { RandomAccessReader, Options, ZipFileOptions }; diff --git a/types/yauzl-promise/tsconfig.json b/types/yauzl-promise/tsconfig.json new file mode 100644 index 0000000000..86c1696468 --- /dev/null +++ b/types/yauzl-promise/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "yauzl-promise-tests.ts" + ] +} diff --git a/types/yauzl-promise/tslint.json b/types/yauzl-promise/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/yauzl-promise/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/yauzl-promise/yauzl-promise-tests.ts b/types/yauzl-promise/yauzl-promise-tests.ts new file mode 100644 index 0000000000..0a33ad6440 --- /dev/null +++ b/types/yauzl-promise/yauzl-promise-tests.ts @@ -0,0 +1,49 @@ +import * as yauzl from 'yauzl-promise'; + +class FakeRaR extends yauzl.RandomAccessReader {} + +const options: yauzl.Options = { + autoClose: true +}; + +const zipOptions: yauzl.ZipFileOptions = { + decrypt: true, + decompress: true, + start: 0, + end: 1 +}; + +const date = yauzl.dosDateTimeToDate(1, 1); +const fn = yauzl.validateFileName("fake"); + +async function test() { + const zip = await yauzl.open(""); + const open2 = await yauzl.open("", options); + + const fd1 = await yauzl.fromFd(0); + const fd2 = await yauzl.fromFd(0, options); + + const buffer1 = await yauzl.fromBuffer(Buffer.from("test", "utf-8")); + const buffer2 = await yauzl.fromBuffer(Buffer.from("test", "utf-8"), options); + + const rar1 = await yauzl.fromRandomAccessReader(new FakeRaR(), 1); + const rar2 = await yauzl.fromRandomAccessReader(new FakeRaR(), 1, options); + + const entry = await zip.readEntry(); + await zip.readEntries(); + await zip.readEntries(1); + + const rs = await zip.openReadStream(entry); + await zip.openReadStream(entry, zipOptions); + + await entry.openReadStream(); + await entry.openReadStream(zipOptions); + + await zip.walkEntries(async (entry: yauzl.Entry) => { + console.log("foo"); + }); + + await zip.walkEntries(async (entry: yauzl.Entry) => { + console.log("foo"); + }, 1); +} diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 3b45b3fcaa..243cb985c1 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -37,8 +37,8 @@ export interface Schema { meta(): any; describe(): SchemaDescription; concat(schema: this): this; - validate(value: T, options?: ValidateOptions): Promise; - validateSync(value: T, options?: ValidateOptions): ValidationError | T; + validate(value: T, options?: ValidateOptions): Promise; + validateSync(value: T, options?: ValidateOptions): T; isValid(value: T, options?: any): Promise; isValidSync(value: T, options?: any): boolean; cast(value: any, options?: any): T; diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index 0ce88a6c66..871df0e8e0 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -307,7 +307,7 @@ const testObject: MyInterface = { arrayField: ["hi"], }; -typedSchema.validateSync(testObject); // $ExpectType ValidationError | MyInterface +typedSchema.validateSync(testObject); // $ExpectType MyInterface // $ExpectError yup.object({